file_name
stringlengths 71
779k
| comments
stringlengths 0
29.4k
| code_string
stringlengths 20
7.69M
| __index_level_0__
int64 2
17.2M
|
---|---|---|---|
//SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.7.0;
//import "hardhat/console.sol";
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
contract DpoppPassport is ERC721, Ownable {
/// ****************************
/// *****DATA TYPES*****
/// ****************************
using Counters for Counters.Counter;
Counters.Counter private _passportIds;
/**
* @notice A struct containing the necessary information to reconstruct an EIP-712 typed data signature.
*
* @param v The signature's recovery parameter.
* @param r The signature's r parameter.
* @param s The signature's s parameter
* @param deadline The signature's deadline
*/
struct EIP712Signature {
uint8 v;
bytes32 r;
bytes32 s;
uint256 deadline;
}
struct passportData {
uint256 passportId;
bytes32 passportName;
bytes32 issuanceDate;
EIP712Signature sig;
}
/// ****************************
/// *****MAPPINGS*****
/// ****************************
mapping(address => passportData) public passports;
/// ****************************
/// *****EVENTS*****
/// ****************************
/// @notice Emitted when a passport is minted
event onMintPassport(
uint256 indexed passportId,
bytes32 indexed issuanceDate,
uint256 timestamp
);
constructor() public ERC721("YourCollectible", "YCB") {
_setBaseURI("https://ipfs.io/ipfs/");
}
/// ****************************
/// *****FUNCTIONS*****
/// ****************************
/// @notice Mint Passport
function mintPassport(
address to,
string memory _issuanceDate,
string memory tokenURI
) public returns (uint256) {
bytes32 issuanceDate = keccak256(abi.encodePacked(_issuanceDate));
//Increment Passport Ids
_passportIds.increment();
uint256 id = _passportIds.current();
_mint(to, id);
_setTokenURI(id, tokenURI);
passports[to].passportId = id;
passports[to].issuanceDate = issuanceDate;
passports[to].passportName = passportName;
emit onMintPassport(id, passportName, issuanceDate, block.timestamp);
return id;
}
function checkForSignatureMatch(
uint8 v,
bytes32 r,
bytes s,
address sender,
uint256 deadline,
uint x
) external {
require(block.timestamp < deadline, "Signature Expired");
uint chainId;
assembly {
chainId := chainId
}
bytes32 ip712DomainHash = keccak256(
abi.encode(
keccak256(
"EIP712Domain(string name, string version, uint256 chainId, address verifyingContract)"
),
keccak256(bytes("SetTest")),
keccak256(bytes("1")),
chainId,
address(this)
);
)
};
bytes32 hashStruct = keccak256(
abi.encode(
keccak256("set(address sender, uint x, uint deadline)"),
sender,
x,
deadline
);
)
bytes32 hash = keccak256(abi.encodePacked("\x19\x01", eip712DomainHash, hashStruct));
address signer = ecrecover(hash, v, r, s);
require(signer == sender, "Invalid Signature");
require(signer != address(0), "Invalid Signature");
set(x);
}
|
Mint PassportIncrement Passport Ids
|
function mintPassport(
address to,
string memory _issuanceDate,
string memory tokenURI
) public returns (uint256) {
bytes32 issuanceDate = keccak256(abi.encodePacked(_issuanceDate));
_passportIds.increment();
uint256 id = _passportIds.current();
_mint(to, id);
_setTokenURI(id, tokenURI);
passports[to].passportId = id;
passports[to].issuanceDate = issuanceDate;
passports[to].passportName = passportName;
emit onMintPassport(id, passportName, issuanceDate, block.timestamp);
return id;
}
| 6,369,530 |
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.9;
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Multicall.sol";
import "./interfaces/IHeroInfinityNodePool.sol";
contract HeroInfinityNFT is ERC721Enumerable, Ownable, Multicall {
using Strings for uint256;
/// @notice Hero Infinity Node Pool Address
address public nodePool = 0xFAd5Ef0F347eb7bB89E798B5d026F60aFA3E2bF4;
/// @notice Max number of NFTs that can be minted per wallet.
uint256 public maxPerWallet = 5;
/// @notice Index of the last NFT reserved for team members (0 - 28).
uint256 public constant HIGHEST_TEAM = 28;
/// @notice Index of the last NFT for sale (29 - 1078).
uint256 public constant HIGHEST_PUBLIC = 1078;
/// @notice Price of each NFT for whitelisted users.
uint256 public whitelistMintPrice = 0.09 ether;
/// @notice Price of each NFT for users in mint event.
uint256 public publicMintPrice = 0.12 ether;
/// @notice Price of each NFT for users after mint event.
uint256 public saleMintPrice = 0.2 ether;
/// @notice Mint start timestamp.
uint256 public mintEndTimestamp;
/// @notice sale enabled.
bool private isSaleEnabled = false;
/// @notice NFT cards reserved.
bool private isReserved = false;
/// @dev Index of the next NFT reserved for team members.
uint256 internal teamPointer = 0;
/// @dev Index of the next NFT for sale.
uint256 internal publicPointer = 29;
/// @dev Base uri of the NFT metadata
string internal baseUri;
/// @notice Number of NFTs minted by each address.
mapping(address => uint256) public mintedAmount;
constructor() ERC721("Hero Infinity Cards", "HRIC") {}
/// @notice Allows the public to mint a maximum of 5 NFTs per address.
/// NFTs minted using this function range from #29 to #1078.
/// @param amount Number of NFTs to mint (max 5).
function mint(uint256 amount) external payable {
require(isMintOpen(), "MINT_NOT_OPEN");
address account = msg.sender;
uint256 price = mintPrice(account);
_mintInternal(account, amount, price);
}
function sale(uint256 amount) external payable {
require(isSaleEnabled, "SALE_NOT_OPEN");
require(amount * saleMintPrice == msg.value, "WRONG_ETH_VALUE");
for (uint256 i = 0; i < amount; i++) {
_safeMint(msg.sender, publicPointer + i);
}
publicPointer = publicPointer + amount;
}
/// @notice Used by the owner (DAO) to mint NFTs reserved for team members.
/// NFTs minted using this function range from #0 to #49.
/// @param amount Number of NFTs to mint.
function mintTeam(uint256 amount) external onlyOwner {
require(amount != 0, "INVALID_AMOUNT");
uint256 currentPointer = teamPointer;
uint256 newPointer = currentPointer + amount;
require(newPointer - 1 <= HIGHEST_TEAM, "TEAM_LIMIT_EXCEEDED");
teamPointer = newPointer;
for (uint256 i = 0; i < amount; i++) {
// No _safeMint because the owner is a gnosis safe
_mint(msg.sender, currentPointer + i);
}
}
/// @dev Function called by `mintWhitelist` and `mint`.
/// Performs common checks and mints `amount` of NFTs.
/// @param account The account to mint the NFTs to.
/// @param amount The amount of NFTs to mint.
function _mintInternal(
address account,
uint256 amount,
uint256 price
) internal {
require(amount != 0, "INVALID_AMOUNT");
uint256 mintedWallet = mintedAmount[account] + amount;
require(mintedWallet <= maxPerWallet, "WALLET_LIMIT_EXCEEDED");
uint256 currentPointer = publicPointer;
uint256 newPointer = currentPointer + amount;
require(newPointer - 1 <= HIGHEST_PUBLIC, "SALE_LIMIT_EXCEEDED");
require(amount * price <= msg.value, "WRONG_ETH_VALUE");
publicPointer = newPointer;
mintedAmount[account] = mintedWallet;
for (uint256 i = 0; i < amount; i++) {
_safeMint(account, currentPointer + i);
}
}
function mintPrice(address account) public view returns (uint256) {
uint256 price = publicMintPrice;
uint256 nodeCount = IHeroInfinityNodePool(nodePool).getNodeNumberOf(
account
);
if (nodeCount > 4) {
price = whitelistMintPrice;
}
return price;
}
/// @return `true` if the mint event is open, otherwise `false`.
function isMintOpen() public view returns (bool) {
return
mintEndTimestamp > 0 &&
block.timestamp <= mintEndTimestamp &&
publicPointer <= HIGHEST_PUBLIC;
}
/// @return `true` if the sale is open after mint event, otherwise `false`.
function isSaleOpen() public view returns (bool) {
return isSaleEnabled;
}
/// @notice Allows the owner to set the sale open after nft mint event.
function setSaleOpen(bool _open) external onlyOwner {
isSaleEnabled = _open;
}
/// @notice Allows the owner to reserve all NFT cards.
function setReserved(bool _open) external onlyOwner {
isReserved = _open;
}
/// @notice Allows the owner to set price set.
function setMintPrice(
uint256 _whitelist,
uint256 _public,
uint256 _sale
) external onlyOwner {
whitelistMintPrice = _whitelist;
publicMintPrice = _public;
saleMintPrice = _sale;
}
/// @notice Allows the owner to set the mint timestamps
/// @param _mintEndTimestamp The end of the nft mint event (needs to be greater than block.timestamp).
function setTimestamps(uint256 _mintEndTimestamp) external onlyOwner {
require(_mintEndTimestamp > block.timestamp, "INVALID_TIMESTAMPS");
mintEndTimestamp = _mintEndTimestamp;
}
/// @notice Used by the owner to withdraw the eth raised during the sale.
function withdrawETH() external onlyOwner {
payable(msg.sender).transfer(address(this).balance);
}
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
!isReserved
? "https://heroinfinity.mypinata.cloud/ipfs/QmRqqznPbCUdeJArzUYLMiuGrepmJvmjbiTopYMpTJbABb"
: string(abi.encodePacked(baseURI, tokenId.toString(), ".json"));
}
/// @notice Used by the owner (DAO) to reveal the NFTs.
/// NOTE: This allows the owner to change the metadata this contract is pointing to,
/// ownership of this contract should be renounced after reveal.
function setBaseURI(string memory uri) external onlyOwner {
baseUri = uri;
}
function _baseURI() internal view override returns (string memory) {
return baseUri;
}
function setNodePool(address poolAddress) external onlyOwner {
nodePool = poolAddress;
}
function setMaxPerWallet(uint256 limit) external onlyOwner {
maxPerWallet = limit;
}
}
// 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.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 (last updated v4.5.0) (utils/Multicall.sol)
pragma solidity ^0.8.0;
import "./Address.sol";
/**
* @dev Provides a function to batch together multiple calls in a single external call.
*
* _Available since v4.1._
*/
abstract contract Multicall {
/**
* @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] = Address.functionDelegateCall(address(this), data[i]);
}
return results;
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.9;
interface IHeroInfinityNodePool {
function getNodeNumberOf(address account) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.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);
_afterTokenTransfer(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);
_afterTokenTransfer(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 from incorrect owner");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
_afterTokenTransfer(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 {}
/**
* @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.
* - `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 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (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);
/**
* @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.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 (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);
}
}
}
}
// 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);
}
|
Used by the owner (DAO) to mint NFTs reserved for team members. NFTs minted using this function range from 0 to 49. amount Number of NFTs to mint. No _safeMint because the owner is a gnosis safe
|
function mintTeam(uint256 amount) external onlyOwner {
require(amount != 0, "INVALID_AMOUNT");
uint256 currentPointer = teamPointer;
uint256 newPointer = currentPointer + amount;
require(newPointer - 1 <= HIGHEST_TEAM, "TEAM_LIMIT_EXCEEDED");
teamPointer = newPointer;
for (uint256 i = 0; i < amount; i++) {
_mint(msg.sender, currentPointer + i);
}
}
| 6,089,245 |
/**
*Submitted for verification at Etherscan.io on 2021-03-31
*/
// File: node_modules\@openzeppelin\contracts\utils\Context.sol
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin\contracts\GSN\Context.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
// File: @openzeppelin\contracts\access\Ownable.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: node_modules\@openzeppelin\contracts\token\ERC20\IERC20.sol
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);
}
// File: node_modules\@openzeppelin\contracts\math\SafeMath.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// File: node_modules\@openzeppelin\contracts\utils\Address.sol
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin\contracts\token\ERC20\SafeERC20.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: contracts\LiquidityMining.sol
pragma solidity 0.6.12;
contract LiquidityMining is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
uint256 private constant DECIMALS = 18;
uint256 private constant UNITS = 10**DECIMALS;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
uint256 rewardDebtAtBlock; // the last block user stake
}
// Info of each pool.
struct PoolInfo {
IERC20 token; // Address of LP token contract.
uint256 tokenPerBlock; // TOKENs to distribute per block.
uint256 lastRewardBlock; // Last block number that TOKEN distribution occurs.
uint256 accTokenPerShare; // Accumulated TOKENs per share, times 1e18 (UNITS).
}
IERC20 public immutable token;
address public tokenRewardsAddress;
// The block number when TOKEN mining starts.
uint256 public immutable START_BLOCK;
// Info of each pool.
PoolInfo[] public poolInfo;
// tokenToPoolId
mapping(address => uint256) public tokenToPoolId;
// Info of each user that stakes LP tokens. pid => user address => info
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
event Deposit(address indexed user, uint256 indexed poolId, uint256 amount);
event Withdraw(
address indexed user,
uint256 indexed poolId,
uint256 amount
);
event EmergencyWithdraw(
address indexed user,
uint256 indexed poolId,
uint256 amount
);
event SendTokenReward(
address indexed user,
uint256 indexed poolId,
uint256 amount
);
//set token sc, reward address and start block
constructor(
address _tokenAddress,
address _tokenRewardsAddress,
uint256 _startBlock
) public {
require(_tokenAddress != address(0),"error zero address");
require(_tokenRewardsAddress != address(0),"error zero address");
token = IERC20(_tokenAddress);
tokenRewardsAddress = _tokenRewardsAddress;
START_BLOCK = _startBlock;
}
/********************** PUBLIC ********************************/
// Add a new erc20 token to the pool. Can only be called by the owner.
function add(
uint256 _tokenPerBlock,
IERC20 _token,
bool _withUpdate
) external onlyOwner {
require(
tokenToPoolId[address(_token)] == 0,
"Token is already in pool"
);
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock =
block.number > START_BLOCK ? block.number : START_BLOCK;
tokenToPoolId[address(_token)] = poolInfo.length + 1;
poolInfo.push(
PoolInfo({
token: _token,
tokenPerBlock: _tokenPerBlock,
lastRewardBlock: lastRewardBlock,
accTokenPerShare: 0
})
);
}
// Update the given pool's TOKEN allocation point. Can only be called by the owner.
function set(
uint256 _poolId,
uint256 _tokenPerBlock,
bool _withUpdate
) external onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
poolInfo[_poolId].tokenPerBlock = _tokenPerBlock;
}
// Update reward variables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 poolId = 0; poolId < length; ++poolId) {
updatePool(poolId);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _poolId) public {
PoolInfo storage pool = poolInfo[_poolId];
// Return if it's too early (if START_BLOCK is in the future probably)
if (block.number <= pool.lastRewardBlock) return;
// Retrieve amount of tokens held in contract
uint256 poolBalance = pool.token.balanceOf(address(this));
// If the contract holds no tokens at all, don't proceed.
if (poolBalance == 0) {
pool.lastRewardBlock = block.number;
return;
}
// Calculate the amount of TOKEN to send to the contract to pay out for this pool
uint256 rewards =
getPoolReward(pool.lastRewardBlock, block.number, pool.tokenPerBlock);
// Update the accumulated TOKENPerShare
pool.accTokenPerShare = pool.accTokenPerShare.add(
rewards.mul(UNITS).div(poolBalance)
);
// Update the last block
pool.lastRewardBlock = block.number;
}
// Get rewards for a specific amount of TOKENPerBlocks
function getPoolReward(
uint256 _from,
uint256 _to,
uint256 _tokenPerBlock
) public view returns (uint256 rewards) {
// Calculate number of blocks covered.
uint256 blockCount = _to.sub(_from);
// Get the amount of TOKEN for this pool
uint256 amount = blockCount.mul(_tokenPerBlock);
// Retrieve allowance and balance
uint256 allowedToken =
token.allowance(tokenRewardsAddress, address(this));
uint256 farmingBalance = token.balanceOf(tokenRewardsAddress);
// If the actual balance is less than the allowance, use the balance.
allowedToken = farmingBalance < allowedToken ? farmingBalance : allowedToken;
// If we reached the total amount allowed already, return the allowedToken
if (allowedToken < amount) {
rewards = allowedToken;
} else {
rewards = amount;
}
}
function claimReward(uint256 _poolId) external {
updatePool(_poolId);
_harvest(_poolId);
}
// Deposit LP tokens to TOKENStaking for TOKEN allocation.
function deposit(uint256 _poolId, uint256 _amount) external {
require(_amount > 0, "Amount cannot be 0");
PoolInfo storage pool = poolInfo[_poolId];
UserInfo storage user = userInfo[_poolId][msg.sender];
updatePool(_poolId);
_harvest(_poolId);
pool.token.safeTransferFrom(
address(msg.sender),
address(this),
_amount
);
// This is the very first deposit
if (user.amount == 0) {
user.rewardDebtAtBlock = block.number;
}
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(pool.accTokenPerShare).div(UNITS);
emit Deposit(msg.sender, _poolId, _amount);
}
// Withdraw LP tokens from TOKENStaking.
function withdraw(uint256 _poolId, uint256 _amount) external {
PoolInfo storage pool = poolInfo[_poolId];
UserInfo storage user = userInfo[_poolId][msg.sender];
require(_amount > 0, "Amount cannot be 0");
updatePool(_poolId);
_harvest(_poolId);
user.amount = user.amount.sub(_amount);
pool.token.safeTransfer(address(msg.sender), _amount);
user.rewardDebt = user.amount.mul(pool.accTokenPerShare).div(UNITS);
emit Withdraw(msg.sender, _poolId, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _poolId) external {
PoolInfo storage pool = poolInfo[_poolId];
UserInfo storage user = userInfo[_poolId][msg.sender];
uint256 amountToSend = user.amount;
user.amount = 0;
user.rewardDebt = 0;
user.rewardDebtAtBlock = 0;
pool.token.safeTransfer(address(msg.sender), amountToSend);
emit EmergencyWithdraw(msg.sender, _poolId, amountToSend);
}
/********************** EXTERNAL ********************************/
// Return the number of added pools
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// View function to see pending TOKENs on frontend.
function pendingReward(uint256 _poolId, address _user)
external
view
returns (uint256)
{
PoolInfo storage pool = poolInfo[_poolId];
UserInfo storage user = userInfo[_poolId][_user];
uint256 accTokenPerShare = pool.accTokenPerShare;
uint256 poolBalance = pool.token.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && poolBalance > 0) {
uint256 rewards =
getPoolReward(
pool.lastRewardBlock,
block.number,
pool.tokenPerBlock
);
accTokenPerShare = accTokenPerShare.add(
rewards.mul(UNITS).div(poolBalance)
);
}
uint256 pending =
user.amount.mul(accTokenPerShare).div(UNITS).sub(user.rewardDebt);
return pending;
}
/********************** INTERNAL ********************************/
function _harvest(uint256 _poolId) internal {
PoolInfo storage pool = poolInfo[_poolId];
UserInfo storage user = userInfo[_poolId][msg.sender];
if (user.amount == 0) return;
uint256 pending =
user.amount.mul(pool.accTokenPerShare).div(UNITS).sub(
user.rewardDebt
);
// Retrieve allowance and balance
uint256 allowedToken =
token.allowance(tokenRewardsAddress, address(this));
uint256 farmingBalance = token.balanceOf(tokenRewardsAddress);
// If the actual balance is less than the allowance, use the balance.
allowedToken = farmingBalance < allowedToken ? farmingBalance : allowedToken;
if (pending > allowedToken) {
pending = allowedToken;
}
if (pending > 0) {
user.rewardDebtAtBlock = block.number;
user.rewardDebt = user.amount.mul(pool.accTokenPerShare).div(UNITS);
// Pay out the pending rewards
token.safeTransferFrom(tokenRewardsAddress, msg.sender, pending);
emit SendTokenReward(msg.sender, _poolId, pending);
return;
}
user.rewardDebt = user.amount.mul(pool.accTokenPerShare).div(UNITS);
}
/********************** ADMIN ********************************/
function changeRewardAddress(address _rewardAddress) external onlyOwner {
require(_rewardAddress != address(0),"Address can't be 0");
tokenRewardsAddress = _rewardAddress;
}
}
|
Retrieve allowance and balance If the actual balance is less than the allowance, use the balance. Pay out the pending rewards
|
function _harvest(uint256 _poolId) internal {
PoolInfo storage pool = poolInfo[_poolId];
UserInfo storage user = userInfo[_poolId][msg.sender];
if (user.amount == 0) return;
uint256 pending =
user.amount.mul(pool.accTokenPerShare).div(UNITS).sub(
user.rewardDebt
);
uint256 allowedToken =
token.allowance(tokenRewardsAddress, address(this));
uint256 farmingBalance = token.balanceOf(tokenRewardsAddress);
allowedToken = farmingBalance < allowedToken ? farmingBalance : allowedToken;
if (pending > allowedToken) {
pending = allowedToken;
}
if (pending > 0) {
user.rewardDebtAtBlock = block.number;
user.rewardDebt = user.amount.mul(pool.accTokenPerShare).div(UNITS);
token.safeTransferFrom(tokenRewardsAddress, msg.sender, pending);
emit SendTokenReward(msg.sender, _poolId, pending);
return;
}
user.rewardDebt = user.amount.mul(pool.accTokenPerShare).div(UNITS);
}
| 10,899,047 |
pragma solidity 0.4.25;
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address _who) external view returns (uint256);
function allowance(address _owner, address _spender) external view returns (uint256);
function transfer(address _to, uint256 _value) external returns (bool);
function approve(address _spender, uint256 _value) external returns (bool);
function transferFrom(address _from, address _to, uint256 _value) external returns (bool);
event Transfer(
address indexed from,
address indexed to,
uint256 value
);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
/**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint256 _a, uint256 _b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (_a == 0) {
return 0;
}
uint256 c = _a * _b;
require(c / _a == _b,"Math error");
return c;
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
require(_b > 0,"Math error"); // Solidity only automatically asserts when dividing by 0
uint256 c = _a / _b;
// assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
require(_b <= _a,"Math error");
uint256 c = _a - _b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 _a, uint256 _b) internal pure returns (uint256) {
uint256 c = _a + _b;
require(c >= _a,"Math error");
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0,"Math error");
return a % b;
}
}
/**
* @title Standard ERC20 token
* @dev Implementation of the basic standard token.
*/
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) internal balances_;
mapping (address => mapping (address => uint256)) private allowed_;
uint256 private totalSupply_;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances_[_owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed_[_owner][_spender];
}
/**
* @dev Transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_value <= balances_[msg.sender],"Invalid value");
require(_to != address(0),"Invalid address");
balances_[msg.sender] = balances_[msg.sender].sub(_value);
balances_[_to] = balances_[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed_[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_value <= balances_[_from],"Value is more than balance");
require(_value <= allowed_[_from][msg.sender],"Value is more than alloved");
require(_to != address(0),"Invalid address");
balances_[_from] = balances_[_from].sub(_value);
balances_[_to] = balances_[_to].add(_value);
allowed_[_from][msg.sender] = allowed_[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(
address _spender,
uint256 _addedValue
)
public
returns (bool)
{
allowed_[msg.sender][_spender] = (allowed_[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed_[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(
address _spender,
uint256 _subtractedValue
)
public
returns (bool)
{
uint256 oldValue = allowed_[msg.sender][_spender];
if (_subtractedValue >= oldValue) {
allowed_[msg.sender][_spender] = 0;
} else {
allowed_[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed_[msg.sender][_spender]);
return true;
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param _account The account that will receive the created tokens.
* @param _amount The amount that will be created.
*/
function _mint(address _account, uint256 _amount) internal {
require(_account != 0,"Invalid address");
totalSupply_ = totalSupply_.add(_amount);
balances_[_account] = balances_[_account].add(_amount);
emit Transfer(address(0), _account, _amount);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param _account The account whose tokens will be burnt.
* @param _amount The amount that will be burnt.
*/
function _burn(address _account, uint256 _amount) internal {
require(_account != 0,"Invalid address");
require(_amount <= balances_[_account],"Amount is more than balance");
totalSupply_ = totalSupply_.sub(_amount);
balances_[_account] = balances_[_account].sub(_amount);
emit Transfer(_account, address(0), _amount);
}
}
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
function safeTransfer(
IERC20 _token,
address _to,
uint256 _value
)
internal
{
require(_token.transfer(_to, _value),"Transfer error");
}
function safeTransferFrom(
IERC20 _token,
address _from,
address _to,
uint256 _value
)
internal
{
require(_token.transferFrom(_from, _to, _value),"Tranfer error");
}
function safeApprove(
IERC20 _token,
address _spender,
uint256 _value
)
internal
{
require(_token.approve(_spender, _value),"Approve error");
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable {
event Paused();
event Unpaused();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused,"Contract is paused, sorry");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused, "Contract is running now");
_;
}
}
/**
* @title Pausable token
* @dev ERC20 modified with pausable transfers.
**/
contract ERC20Pausable is ERC20, Pausable {
function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) {
return super.transferFrom(_from, _to, _value);
}
function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) {
return super.approve(_spender, _value);
}
function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool success) {
return super.increaseApproval(_spender, _addedValue);
}
function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) {
return super.decreaseApproval(_spender, _subtractedValue);
}
}
/**
* @title Contract ATHLETICO token
* @dev ERC20 compatible token contract
*/
contract ATHLETICOToken is ERC20Pausable {
string public constant name = "ATHLETICO TOKEN";
string public constant symbol = "ATH";
uint32 public constant decimals = 18;
uint256 public INITIAL_SUPPLY = 1000000000 * 1 ether; // 1 000 000 000
address public CrowdsaleAddress;
bool public ICOover;
mapping (address => bool) public kyc;
mapping (address => uint256) public sponsors;
event LogSponsor(
address indexed from,
uint256 value
);
constructor(address _CrowdsaleAddress) public {
CrowdsaleAddress = _CrowdsaleAddress;
_mint(_CrowdsaleAddress, INITIAL_SUPPLY);
}
modifier onlyOwner() {
require(msg.sender == CrowdsaleAddress,"Only CrowdSale contract can run this");
_;
}
modifier validDestination( address to ) {
require(to != address(0),"Empty address");
require(to != address(this),"RESTO Token address");
_;
}
modifier isICOover {
if (msg.sender != CrowdsaleAddress){
require(ICOover == true,"Transfer of tokens is prohibited until the end of the ICO");
}
_;
}
/**
* @dev Override for testing address destination
*/
function transfer(address _to, uint256 _value) public validDestination(_to) isICOover returns (bool) {
return super.transfer(_to, _value);
}
/**
* @dev Override for testing address destination
*/
function transferFrom(address _from, address _to, uint256 _value)
public validDestination(_to) isICOover returns (bool)
{
return super.transferFrom(_from, _to, _value);
}
/**
* @dev Function to mint tokens
* can run only from crowdsale contract
* @param to The address that will receive the minted tokens.
* @param _value The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address to, uint256 _value) public onlyOwner {
_mint(to, _value);
}
/**
* @dev Function to burn tokens
* Anyone can burn their tokens and in this way help the project.
* Information about sponsors is public.
* On the project website you can get a sponsor certificate.
*/
function burn(uint256 _value) public {
_burn(msg.sender, _value);
sponsors[msg.sender] = sponsors[msg.sender].add(_value);
emit LogSponsor(msg.sender, _value);
}
/**
* @dev function set kyc bool to true
* can run only from crowdsale contract
* @param _investor The investor who passed the procedure KYC
*/
function kycPass(address _investor) public onlyOwner {
kyc[_investor] = true;
}
/**
* @dev function set kyc bool to false
* can run only from crowdsale contract
* @param _investor The investor who not passed the procedure KYC (change after passing kyc - something wrong)
*/
function kycNotPass(address _investor) public onlyOwner {
kyc[_investor] = false;
}
/**
* @dev function set ICOOver bool to true
* can run only from crowdsale contract
*/
function setICOover() public onlyOwner {
ICOover = true;
}
/**
* @dev function transfer tokens from special address to users
* can run only from crowdsale contract
*/
function transferTokensFromSpecialAddress(address _from, address _to, uint256 _value) public onlyOwner whenNotPaused returns (bool){
require (balances_[_from] >= _value,"Decrease value");
balances_[_from] = balances_[_from].sub(_value);
balances_[_to] = balances_[_to].add(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev called from crowdsale contract to pause, triggers stopped state
* can run only from crowdsale contract
*/
function pause() public onlyOwner whenNotPaused {
paused = true;
emit Paused();
}
/**
* @dev called from crowdsale contract to unpause, returns to normal state
* can run only from crowdsale contract
*/
function unpause() public onlyOwner whenPaused {
paused = false;
emit Unpaused();
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner and DAOContract addresses, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
address public DAOContract;
address private candidate;
constructor() public {
owner = msg.sender;
DAOContract = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner,"Access denied");
_;
}
modifier onlyDAO() {
require(msg.sender == DAOContract,"Access denied");
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
require(_newOwner != address(0),"Invalid address");
candidate = _newOwner;
}
function setDAOContract(address _newDAOContract) public onlyOwner {
require(_newDAOContract != address(0),"Invalid address");
DAOContract = _newDAOContract;
}
function confirmOwnership() public {
require(candidate == msg.sender,"Only from candidate");
owner = candidate;
delete candidate;
}
}
contract TeamAddress {
}
contract BountyAddress {
}
/**
* @title Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale
*/
contract Crowdsale is Ownable {
using SafeMath for uint256;
using SafeERC20 for ATHLETICOToken;
event LogStateSwitch(State newState);
event LogRefunding(address indexed to, uint256 amount);
mapping(address => uint) public crowdsaleBalances;
uint256 public softCap = 250 * 1 ether;
address internal myAddress = this;
ATHLETICOToken public token = new ATHLETICOToken(myAddress);
uint64 public crowdSaleStartTime;
uint64 public crowdSaleEndTime = 1559347200; // 01.06.2019 0:00:00
uint256 internal minValue = 0.005 ether;
//Addresses for store tokens
TeamAddress public teamAddress = new TeamAddress();
BountyAddress public bountyAddress = new BountyAddress();
// How many token units a buyer gets per wei.
uint256 public rate;
// Amount of wei raised
uint256 public weiRaised;
event LogWithdraw(
address indexed from,
address indexed to,
uint256 amount
);
event LogTokensPurchased(
address indexed purchaser,
address indexed beneficiary,
uint256 value,
uint256 amount
);
// Create state of contract
enum State {
Init,
CrowdSale,
Refunding,
WorkTime
}
State public currentState = State.Init;
modifier onlyInState(State state){
require(state==currentState);
_;
}
constructor() public {
uint256 totalTokens = token.INITIAL_SUPPLY();
/**
* @dev Inicial distributing tokens to special adresses
* TeamAddress - 10%
* BountyAddress - 5%
*/
_deliverTokens(teamAddress, totalTokens.div(10));
_deliverTokens(bountyAddress, totalTokens.div(20));
rate = 20000;
setState(State.CrowdSale);
crowdSaleStartTime = uint64(now);
}
/**
* @dev public function finishing crowdsale if enddate is coming or softcap is passed
*/
function finishCrowdSale() public onlyInState(State.CrowdSale) {
require(now >= crowdSaleEndTime || myAddress.balance >= softCap, "Too early");
if(myAddress.balance >= softCap) {
setState(State.WorkTime);
token.setICOover();
} else {
setState(State.Refunding);
}
}
/**
* @dev fallback function
*/
function () external payable {
buyTokens(msg.sender);
}
/**
* @dev token purchase
* @param _beneficiary Address performing the token purchase
*/
function buyTokens(address _beneficiary) public payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(_beneficiary, weiAmount);
// calculate token amount to be created
uint256 tokens = _getTokenAmount(weiAmount);
// update state
weiRaised = weiRaised.add(weiAmount);
_processPurchase(_beneficiary, tokens);
crowdsaleBalances[_beneficiary] = crowdsaleBalances[_beneficiary].add(weiAmount);
emit LogTokensPurchased(
msg.sender,
_beneficiary,
weiAmount,
tokens
);
}
function setState(State _state) internal {
currentState = _state;
emit LogStateSwitch(_state);
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pauseCrowdsale() public onlyOwner {
token.pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpauseCrowdsale() public onlyOwner {
token.unpause();
}
/**
* @dev called by the DAO to set new rate
*/
function setRate(uint256 _newRate) public onlyDAO {
rate = _newRate;
}
/**
* @dev function set kyc bool to true
* @param _investor The investor who passed the procedure KYC
*/
function setKYCpassed(address _investor) public onlyDAO returns(bool){
token.kycPass(_investor);
return true;
}
/**
* @dev function set kyc bool to false
* @param _investor The investor who not passed the procedure KYC after passing
*/
function setKYCNotPassed(address _investor) public onlyDAO returns(bool){
token.kycNotPass(_investor);
return true;
}
/**
* @dev the function tranfer tokens from TeamAddress
*/
function transferTokensFromTeamAddress(address _investor, uint256 _value) public onlyDAO returns(bool){
token.transferTokensFromSpecialAddress(address(teamAddress), _investor, _value);
return true;
}
/**
* @dev the function tranfer tokens from BountyAddress
*/
function transferTokensFromBountyAddress(address _investor, uint256 _value) public onlyDAO returns(bool){
token.transferTokensFromSpecialAddress(address(bountyAddress), _investor, _value);
return true;
}
/**
* @dev Validation of an incoming purchase. internal function.
* @param _beneficiary Address performing the token purchase
* @param _weiAmount Value in wei involved in the purchase
*/
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal view{
require(_beneficiary != address(0),"Invalid address");
require(_weiAmount >= minValue,"Min amount is 0.005 ether");
require(currentState != State.Refunding, "Only for CrowdSale and Work stage.");
}
/**
* @dev internal function
* @param _beneficiary Address performing the token purchase
* @param _tokenAmount Number of tokens to be emitted
*/
function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal {
token.safeTransfer(_beneficiary, _tokenAmount);
}
/**
* @dev Function transfer token to new investors
* Access restricted DAO
*/
function transferTokens(address _newInvestor, uint256 _tokenAmount) public onlyDAO {
_deliverTokens(_newInvestor, _tokenAmount);
}
/**
* @dev Function mint tokens to winners or prize funds contracts
* Access restricted DAO
*/
function mintTokensToWinners(address _address, uint256 _tokenAmount) public onlyDAO {
require(currentState == State.WorkTime, "CrowdSale is not finished yet. Access denied.");
token.mint(_address, _tokenAmount);
}
/**
* @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens.
* @param _beneficiary Address receiving the tokens
* @param _tokenAmount Number of tokens to be purchased
*/
function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal {
_deliverTokens(_beneficiary, _tokenAmount);
}
/**
* @dev this function is ether converted to tokens.
* @param _weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) {
uint256 bonus = 0;
uint256 resultAmount = _weiAmount;
/**
* ICO bonus UnisTimeStamp
* Start date End date
* StartTime -01.01.2019 - 100% 1543622400 1546300800
* 01.01.2019-01.02.2019 - 50% 1546300800 1548979200
* 01.02.2019-01.03.2019 - 25% 1548979200 1551398400
*/
if (now >= crowdSaleStartTime && now < 1546300800) {
bonus = 100;
}
if (now >= 1546300800 && now < 1548979200) {
bonus = 50;
}
if (now >= 1548979200 && now < 1551398400) {
bonus = 25;
}
if (bonus > 0) {
resultAmount += _weiAmount.mul(bonus).div(100);
}
return resultAmount.mul(rate);
}
/**
* @dev function returns funds to investors in case of project failure.
*/
function refund() public payable{
require(currentState == State.Refunding, "Only for Refunding stage.");
// refund ether to investors
uint value = crowdsaleBalances[msg.sender];
crowdsaleBalances[msg.sender] = 0;
msg.sender.transfer(value);
emit LogRefunding(msg.sender, value);
}
/**
* @dev function of withdrawal of funds for the development of the project if successful
*/
function withdrawFunds (address _to, uint256 _value) public onlyDAO {
require(currentState == State.WorkTime, "CrowdSale is not finished yet. Access denied.");
require (myAddress.balance >= _value,"Value is more than balance");
require(_to != address(0),"Invalid address");
_to.transfer(_value);
emit LogWithdraw(msg.sender, _to, _value);
}
}
|
Transfer token for a specified address _to The address to transfer to. _value The amount to be transferred./
|
function transfer(address _to, uint256 _value) public returns (bool) {
require(_value <= balances_[msg.sender],"Invalid value");
require(_to != address(0),"Invalid address");
balances_[msg.sender] = balances_[msg.sender].sub(_value);
balances_[_to] = balances_[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
| 7,275,053 |
./partial_match/1/0x412e5a36BDE71AA2c38e1c0E26BAAf7F2f0Bc24a/sources/Pusd.sol
|
Returns X PEGS = 1 USD
|
function pegs_price() public view returns (uint256) {
return oracle_price(PriceChoice.PEGS);
}
| 4,072,829 |
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity >=0.8.0;
/// @notice Trident pool ERC-20 with EIP-2612 extension.
/// @author Adapted from RariCapital, https://github.com/Rari-Capital/solmate/blob/main/src/erc20/ERC20.sol,
/// License-Identifier: AGPL-3.0-only.
abstract contract TridentERC20 {
event Transfer(address indexed sender, address indexed recipient, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
string public constant name = "Sushi LP Token";
string public constant symbol = "SLP";
uint8 public constant decimals = 18;
uint256 public totalSupply;
/// @notice owner -> balance mapping.
mapping(address => uint256) public balanceOf;
/// @notice owner -> spender -> allowance mapping.
mapping(address => mapping(address => uint256)) public allowance;
/// @notice Chain Id at this contract's deployment.
uint256 internal immutable DOMAIN_SEPARATOR_CHAIN_ID;
/// @notice EIP-712 typehash for this contract's domain at deployment.
bytes32 internal immutable _DOMAIN_SEPARATOR;
/// @notice EIP-712 typehash for this contract's {permit} struct.
bytes32 public constant PERMIT_TYPEHASH =
keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
/// @notice owner -> nonce mapping used in {permit}.
mapping(address => uint256) public nonces;
constructor() {
DOMAIN_SEPARATOR_CHAIN_ID = block.chainid;
_DOMAIN_SEPARATOR = _calculateDomainSeparator();
}
function _calculateDomainSeparator() internal view returns (bytes32 domainSeperator) {
domainSeperator = keccak256(
abi.encode(
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
keccak256(bytes(name)),
keccak256(bytes("1")),
block.chainid,
address(this)
)
);
}
/// @notice EIP-712 typehash for this contract's domain.
function DOMAIN_SEPARATOR() public view returns (bytes32 domainSeperator) {
domainSeperator = block.chainid == DOMAIN_SEPARATOR_CHAIN_ID ? _DOMAIN_SEPARATOR : _calculateDomainSeparator();
}
/// @notice Approves `amount` from `msg.sender` to be spent by `spender`.
/// @param spender Address of the party that can pull tokens from `msg.sender`'s account.
/// @param amount The maximum collective `amount` that `spender` can pull.
/// @return (bool) Returns 'true' if succeeded.
function approve(address spender, uint256 amount) external returns (bool) {
allowance[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
/// @notice Transfers `amount` tokens from `msg.sender` to `recipient`.
/// @param recipient The address to move tokens to.
/// @param amount The token `amount` to move.
/// @return (bool) Returns 'true' if succeeded.
function transfer(address recipient, uint256 amount) external returns (bool) {
balanceOf[msg.sender] -= amount;
// @dev This is safe from overflow - the sum of all user
// balances can't exceed 'type(uint256).max'.
unchecked {
balanceOf[recipient] += amount;
}
emit Transfer(msg.sender, recipient, amount);
return true;
}
/// @notice Transfers `amount` tokens from `sender` to `recipient`. Caller needs approval from `from`.
/// @param sender Address to pull tokens `from`.
/// @param recipient The address to move tokens to.
/// @param amount The token `amount` to move.
/// @return (bool) Returns 'true' if succeeded.
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool) {
if (allowance[sender][msg.sender] != type(uint256).max) {
allowance[sender][msg.sender] -= amount;
}
balanceOf[sender] -= amount;
// @dev This is safe from overflow - the sum of all user
// balances can't exceed 'type(uint256).max'.
unchecked {
balanceOf[recipient] += amount;
}
emit Transfer(sender, recipient, amount);
return true;
}
/// @notice Triggers an approval from `owner` to `spender`.
/// @param owner The address to approve from.
/// @param spender The address to be approved.
/// @param amount The number of tokens that are approved (2^256-1 means infinite).
/// @param deadline The time at which to expire the signature.
/// @param v The recovery byte of the signature.
/// @param r Half of the ECDSA signature pair.
/// @param s Half of the ECDSA signature pair.
function permit(
address owner,
address spender,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external {
require(deadline >= block.timestamp, "PERMIT_DEADLINE_EXPIRED");
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR(),
keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, amount, nonces[owner]++, deadline))
)
);
address recoveredAddress = ecrecover(digest, v, r, s);
require(recoveredAddress != address(0) && recoveredAddress == owner, "INVALID_PERMIT_SIGNATURE");
allowance[recoveredAddress][spender] = amount;
emit Approval(owner, spender, amount);
}
function _mint(address recipient, uint256 amount) internal {
totalSupply += amount;
// @dev This is safe from overflow - the sum of all user
// balances can't exceed 'type(uint256).max'.
unchecked {
balanceOf[recipient] += amount;
}
emit Transfer(address(0), recipient, amount);
}
function _burn(address sender, uint256 amount) internal {
balanceOf[sender] -= amount;
// @dev This is safe from underflow - users won't ever
// have a balance larger than `totalSupply`.
unchecked {
totalSupply -= amount;
}
emit Transfer(sender, address(0), amount);
}
}
|
EIP-712 typehash for this contract's domain.
|
function DOMAIN_SEPARATOR() public view returns (bytes32 domainSeperator) {
domainSeperator = block.chainid == DOMAIN_SEPARATOR_CHAIN_ID ? _DOMAIN_SEPARATOR : _calculateDomainSeparator();
}
| 1,035,719 |
pragma solidity ^0.4.24;
// File: contracts/libs/ERC223Receiver_Interface.sol
/**
* @title ERC223-compliant contract interface.
*/
contract ERC223Receiver {
constructor() internal {}
/**
* @dev Standard ERC223 function that will handle incoming token transfers.
*
* @param _from Token sender address.
* @param _value Amount of tokens.
* @param _data Transaction metadata.
*/
function tokenFallback(address _from, uint _value, bytes _data) public;
}
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
// 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/ERC20Basic.sol
/**
* @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/token/ERC20/BasicToken.sol
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev Transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender)
public view returns (uint256);
function transferFrom(address from, address to, uint256 value)
public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
// File: openzeppelin-solidity/contracts/token/ERC20/StandardToken.sol
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* 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(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(
address _spender,
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: contracts/libs/ERC223Token.sol
/**
* @title Implementation of the ERC223 standard token.
* @dev See https://github.com/Dexaran/ERC223-token-standard
*/
contract ERC223Token is StandardToken {
using SafeMath for uint;
event Transfer(address indexed from, address indexed to, uint value, bytes data);
modifier enoughBalance(uint _value) {
require (_value <= balanceOf(msg.sender));
_;
}
/**
* @dev Transfer the specified amount of tokens to the specified address.
* Invokes the `tokenFallback` function if the recipient is a contract.
* The token transfer fails if the recipient is a contract
* but does not implement the `tokenFallback` function
* or the fallback function to receive funds.
*
* @param _to Receiver address.
* @param _value Amount of tokens that will be transferred.
* @param _data Transaction metadata.
* @return Success.
*/
function transfer(address _to, uint _value, bytes _data) public returns (bool success) {
require(_to != address(0));
return isContract(_to) ?
transferToContract(_to, _value, _data) :
transferToAddress(_to, _value, _data)
;
}
/**
* @dev Transfer the specified amount of tokens to the specified address.
* This function works the same with the previous one
* but doesn't contain `_data` param.
* Added due to backwards compatibility reasons.
*
* @param _to Receiver address.
* @param _value Amount of tokens that will be transferred.
* @return Success.
*/
function transfer(address _to, uint _value) public returns (bool success) {
bytes memory empty;
return transfer(_to, _value, empty);
}
/**
* @dev Assemble the given address bytecode. If bytecode exists then the _addr is a contract.
* @return If the target is a contract.
*/
function isContract(address _addr) private view returns (bool is_contract) {
uint length;
assembly {
// Retrieve the size of the code on target address; this needs assembly
length := extcodesize(_addr)
}
return (length > 0);
}
/**
* @dev Helper function that transfers to address.
* @return Success.
*/
function transferToAddress(address _to, uint _value, bytes _data) private enoughBalance(_value) returns (bool success) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balanceOf(_to).add(_value);
emit Transfer(msg.sender, _to, _value, _data);
return true;
}
/**
* @dev Helper function that transfers to contract.
* @return Success.
*/
function transferToContract(address _to, uint _value, bytes _data) private enoughBalance(_value) returns (bool success) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balanceOf(_to).add(_value);
ERC223Receiver receiver = ERC223Receiver(_to);
receiver.tokenFallback(msg.sender, _value, _data);
emit Transfer(msg.sender, _to, _value, _data);
return true;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/BurnableToken.sol
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract BurnableToken is BasicToken {
event Burn(address indexed burner, uint256 value);
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) public {
_burn(msg.sender, _value);
}
function _burn(address _who, uint256 _value) internal {
require(_value <= balances[_who]);
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
balances[_who] = balances[_who].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit Burn(_who, _value);
emit Transfer(_who, address(0), _value);
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/StandardBurnableToken.sol
/**
* @title Standard Burnable Token
* @dev Adds burnFrom method to ERC20 implementations
*/
contract StandardBurnableToken is BurnableToken, StandardToken {
/**
* @dev Burns a specific amount of tokens from the target address and decrements allowance
* @param _from address The address which you want to send tokens from
* @param _value uint256 The amount of token to be burned
*/
function burnFrom(address _from, uint256 _value) public {
require(_value <= allowed[_from][msg.sender]);
// Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted,
// this function needs to emit an event with the updated approval.
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
_burn(_from, _value);
}
}
// File: contracts/libs/BaseToken.sol
/**
* @title Base token contract for oracle.
*/
contract BaseToken is ERC223Token, StandardBurnableToken {
}
// File: openzeppelin-solidity/contracts/ownership/Ownable.sol
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to 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/ShintakuToken.sol
/**
* @title Shintaku token contract
* @dev Burnable ERC223 token with set emission curve.
*/
contract ShintakuToken is BaseToken, Ownable {
using SafeMath for uint;
string public constant symbol = "SHN";
string public constant name = "Shintaku";
uint8 public constant demicals = 18;
// Unit of tokens
uint public constant TOKEN_UNIT = (10 ** uint(demicals));
// Parameters
// Number of blocks for each period (100000 = ~2-3 weeks)
uint public PERIOD_BLOCKS;
// Number of blocks to lock owner balance (50x = ~2 years)
uint public OWNER_LOCK_BLOCKS;
// Number of blocks to lock user remaining balances (25x = ~1 year)
uint public USER_LOCK_BLOCKS;
// Number of tokens per period during tail emission
uint public constant TAIL_EMISSION = 400 * (10 ** 3) * TOKEN_UNIT;
// Number of tokens to emit initially: tail emission is 4% of this
uint public constant INITIAL_EMISSION_FACTOR = 25;
// Absolute cap on funds received per period
// Note: this should be obscenely large to prevent larger ether holders
// from monopolizing tokens at low cost. This cap should never be hit in
// practice.
uint public constant MAX_RECEIVED_PER_PERIOD = 10000 ether;
/**
* @dev Store relevant data for a period.
*/
struct Period {
// Block this period has started at
uint started;
// Total funds received this period
uint totalReceived;
// Locked owner balance, will unlock after a long time
uint ownerLockedBalance;
// Number of tokens to mint this period
uint minting;
// Sealed purchases for each account
mapping (address => bytes32) sealedPurchaseOrders;
// Balance received from each account
mapping (address => uint) receivedBalances;
// Locked balance for each account
mapping (address => uint) lockedBalances;
// When withdrawing, withdraw to an alias address (e.g. cold storage)
mapping (address => address) aliases;
}
// Modifiers
modifier validPeriod(uint _period) {
require(_period <= currentPeriodIndex());
_;
}
// Contract state
// List of periods
Period[] internal periods;
// Address the owner can withdraw funds to (e.g. cold storage)
address public ownerAlias;
// Events
event NextPeriod(uint indexed _period, uint indexed _block);
event SealedOrderPlaced(address indexed _from, uint indexed _period, uint _value);
event SealedOrderRevealed(address indexed _from, uint indexed _period, address indexed _alias, uint _value);
event OpenOrderPlaced(address indexed _from, uint indexed _period, address indexed _alias, uint _value);
event Claimed(address indexed _from, uint indexed _period, address indexed _alias, uint _value);
// Functions
constructor(address _alias, uint _periodBlocks, uint _ownerLockFactor, uint _userLockFactor) public {
require(_alias != address(0));
require(_periodBlocks >= 2);
require(_ownerLockFactor > 0);
require(_userLockFactor > 0);
periods.push(Period(block.number, 0, 0, calculateMinting(0)));
ownerAlias = _alias;
PERIOD_BLOCKS = _periodBlocks;
OWNER_LOCK_BLOCKS = _periodBlocks.mul(_ownerLockFactor);
USER_LOCK_BLOCKS = _periodBlocks.mul(_userLockFactor);
}
/**
* @dev Go to the next period, if sufficient time has passed.
*/
function nextPeriod() public {
uint periodIndex = currentPeriodIndex();
uint periodIndexNext = periodIndex.add(1);
require(block.number.sub(periods[periodIndex].started) > PERIOD_BLOCKS);
periods.push(Period(block.number, 0, 0, calculateMinting(periodIndexNext)));
emit NextPeriod(periodIndexNext, block.number);
}
/**
* @dev Creates a sealed purchase order.
* @param _from Account that will purchase tokens.
* @param _period Period of purchase order.
* @param _value Purchase funds, in wei.
* @param _salt Random value to keep purchase secret.
* @return The sealed purchase order.
*/
function createPurchaseOrder(address _from, uint _period, uint _value, bytes32 _salt) public pure returns (bytes32) {
return keccak256(abi.encodePacked(_from, _period, _value, _salt));
}
/**
* @dev Submit a sealed purchase order. Wei sent can be different then sealed value.
* @param _sealedPurchaseOrder The sealed purchase order.
*/
function placePurchaseOrder(bytes32 _sealedPurchaseOrder) public payable {
if (block.number.sub(periods[currentPeriodIndex()].started) > PERIOD_BLOCKS) {
nextPeriod();
}
// Note: current period index may update from above call
Period storage period = periods[currentPeriodIndex()];
// Each address can only make a single purchase per period
require(period.sealedPurchaseOrders[msg.sender] == bytes32(0));
period.sealedPurchaseOrders[msg.sender] = _sealedPurchaseOrder;
period.receivedBalances[msg.sender] = msg.value;
emit SealedOrderPlaced(msg.sender, currentPeriodIndex(), msg.value);
}
/**
* @dev Reveal a sealed purchase order and commit to a purchase.
* @param _sealedPurchaseOrder The sealed purchase order.
* @param _period Period of purchase order.
* @param _value Purchase funds, in wei.
* @param _period Period for which to reveal purchase order.
* @param _salt Random value to keep purchase secret.
* @param _alias Address to withdraw tokens and excess funds to.
*/
function revealPurchaseOrder(bytes32 _sealedPurchaseOrder, uint _period, uint _value, bytes32 _salt, address _alias) public {
// Sanity check to make sure user enters an alias
require(_alias != address(0));
// Can only reveal sealed orders in the next period
require(currentPeriodIndex() == _period.add(1));
Period storage period = periods[_period];
// Each address can only make a single purchase per period
require(period.aliases[msg.sender] == address(0));
// Note: don't *need* to advance period here
bytes32 h = createPurchaseOrder(msg.sender, _period, _value, _salt);
require(h == _sealedPurchaseOrder);
// The value revealed must not be greater than the value previously sent
require(_value <= period.receivedBalances[msg.sender]);
period.totalReceived = period.totalReceived.add(_value);
uint remainder = period.receivedBalances[msg.sender].sub(_value);
period.receivedBalances[msg.sender] = _value;
period.aliases[msg.sender] = _alias;
emit SealedOrderRevealed(msg.sender, _period, _alias, _value);
// Return any extra balance to the alias
_alias.transfer(remainder);
}
/**
* @dev Place an unsealed purchase order immediately.
* @param _alias Address to withdraw tokens to.
*/
function placeOpenPurchaseOrder(address _alias) public payable {
// Sanity check to make sure user enters an alias
require(_alias != address(0));
if (block.number.sub(periods[currentPeriodIndex()].started) > PERIOD_BLOCKS) {
nextPeriod();
}
// Note: current period index may update from above call
Period storage period = periods[currentPeriodIndex()];
// Each address can only make a single purchase per period
require(period.aliases[msg.sender] == address(0));
period.totalReceived = period.totalReceived.add(msg.value);
period.receivedBalances[msg.sender] = msg.value;
period.aliases[msg.sender] = _alias;
emit OpenOrderPlaced(msg.sender, currentPeriodIndex(), _alias, msg.value);
}
/**
* @dev Claim previously purchased tokens for an account.
* @param _from Account to claim tokens for.
* @param _period Period for which to claim tokens.
*/
function claim(address _from, uint _period) public {
// Claiming can only be done at least two periods after submitting sealed purchase order
require(currentPeriodIndex() > _period.add(1));
Period storage period = periods[_period];
require(period.receivedBalances[_from] > 0);
uint value = period.receivedBalances[_from];
delete period.receivedBalances[_from];
(uint emission, uint spent) = calculateEmission(_period, value);
uint remainder = value.sub(spent);
address alias = period.aliases[_from];
// Mint tokens based on spent funds
mint(alias, emission);
// Lock up remaining funds for account
period.lockedBalances[_from] = period.lockedBalances[_from].add(remainder);
// Lock up spent funds for owner
period.ownerLockedBalance = period.ownerLockedBalance.add(spent);
emit Claimed(_from, _period, alias, emission);
}
/*
* @dev Users can withdraw locked balances after the lock time has expired, for an account.
* @param _from Account to withdraw balance for.
* @param _period Period to withdraw funds for.
*/
function withdraw(address _from, uint _period) public {
require(currentPeriodIndex() > _period);
Period storage period = periods[_period];
require(block.number.sub(period.started) > USER_LOCK_BLOCKS);
uint balance = period.lockedBalances[_from];
require(balance <= address(this).balance);
delete period.lockedBalances[_from];
address alias = period.aliases[_from];
// Don't delete this, as a user may have unclaimed tokens
//delete period.aliases[_from];
alias.transfer(balance);
}
/**
* @dev Contract owner can withdraw unlocked owner funds.
* @param _period Period to withdraw funds for.
*/
function withdrawOwner(uint _period) public onlyOwner {
require(currentPeriodIndex() > _period);
Period storage period = periods[_period];
require(block.number.sub(period.started) > OWNER_LOCK_BLOCKS);
uint balance = period.ownerLockedBalance;
require(balance <= address(this).balance);
delete period.ownerLockedBalance;
ownerAlias.transfer(balance);
}
/**
* @dev The owner can withdraw any unrevealed balances after the deadline.
* @param _period Period to withdraw funds for.
* @param _from Account to withdraw unrevealed funds against.
*/
function withdrawOwnerUnrevealed(uint _period, address _from) public onlyOwner {
// Must be past the reveal deadline of one period
require(currentPeriodIndex() > _period.add(1));
Period storage period = periods[_period];
require(block.number.sub(period.started) > OWNER_LOCK_BLOCKS);
uint balance = period.receivedBalances[_from];
require(balance <= address(this).balance);
delete period.receivedBalances[_from];
ownerAlias.transfer(balance);
}
/**
* @dev Calculate the number of tokens to mint during a period.
* @param _period The period.
* @return Number of tokens to mint.
*/
function calculateMinting(uint _period) internal pure returns (uint) {
// Every period, decrease emission by 5% of initial, until tail emission
return
_period < INITIAL_EMISSION_FACTOR ?
TAIL_EMISSION.mul(INITIAL_EMISSION_FACTOR.sub(_period)) :
TAIL_EMISSION
;
}
/**
* @dev Helper function to get current period index.
* @return The array index of the current period.
*/
function currentPeriodIndex() public view returns (uint) {
assert(periods.length > 0);
return periods.length.sub(1);
}
/**
* @dev Calculate token emission.
* @param _period Period for which to calculate emission.
* @param _value Amount paid. Emissions is proportional to this.
* @return Number of tokens to emit.
* @return The spent balance.
*/
function calculateEmission(uint _period, uint _value) internal view returns (uint, uint) {
Period storage currentPeriod = periods[_period];
uint minting = currentPeriod.minting;
uint totalReceived = currentPeriod.totalReceived;
uint scaledValue = _value;
if (totalReceived > MAX_RECEIVED_PER_PERIOD) {
// If the funds received this period exceed the maximum, scale
// emission to refund remaining
scaledValue = _value.mul(MAX_RECEIVED_PER_PERIOD).div(totalReceived);
}
uint emission = scaledValue.mul(minting).div(MAX_RECEIVED_PER_PERIOD);
return (emission, scaledValue);
}
/**
* @dev Mints new tokens.
* @param _account Account that will receive new tokens.
* @param _value Number of tokens to mint.
*/
function mint(address _account, uint _value) internal {
balances[_account] = balances[_account].add(_value);
totalSupply_ = totalSupply_.add(_value);
}
// Getters
function getPeriodStarted(uint _period) public view validPeriod(_period) returns (uint) {
return periods[_period].started;
}
function getPeriodTotalReceived(uint _period) public view validPeriod(_period) returns (uint) {
return periods[_period].totalReceived;
}
function getPeriodOwnerLockedBalance(uint _period) public view validPeriod(_period) returns (uint) {
return periods[_period].ownerLockedBalance;
}
function getPeriodMinting(uint _period) public view validPeriod(_period) returns (uint) {
return periods[_period].minting;
}
function getPeriodSealedPurchaseOrderFor(uint _period, address _account) public view validPeriod(_period) returns (bytes32) {
return periods[_period].sealedPurchaseOrders[_account];
}
function getPeriodReceivedBalanceFor(uint _period, address _account) public view validPeriod(_period) returns (uint) {
return periods[_period].receivedBalances[_account];
}
function getPeriodLockedBalanceFor(uint _period, address _account) public view validPeriod(_period) returns (uint) {
return periods[_period].lockedBalances[_account];
}
function getPeriodAliasFor(uint _period, address _account) public view validPeriod(_period) returns (address) {
return periods[_period].aliases[_account];
}
}
|
Go to the next period, if sufficient time has passed./
|
function nextPeriod() public {
uint periodIndex = currentPeriodIndex();
uint periodIndexNext = periodIndex.add(1);
require(block.number.sub(periods[periodIndex].started) > PERIOD_BLOCKS);
periods.push(Period(block.number, 0, 0, calculateMinting(periodIndexNext)));
emit NextPeriod(periodIndexNext, block.number);
}
| 6,420,987 |
./partial_match/1/0x2a5eb6515c7c36Fd30079ddFAAb0a1bdD6e07ef0/sources/SeigniorageShares.sol
|
Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. This method is included for ERC20 compatibility. increaseAllowance and decreaseAllowance should be used instead. Changing an allowance with this method brings the risk that someone may transfer both the old and the new allowance - if they are both greater than zero - if a transfer transaction is mined before the later approve() call is mined. spender The address which will spend the funds. value The amount of tokens to be spent./
|
function approve(address spender, uint256 value)
public
validRecipient(spender)
returns (bool)
{
_allowedShares[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
| 2,650,623 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721EnumerableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721URIStorageUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import "../../v1/Auction.sol";
import "../../v1/FixedPrice.sol";
import "../../v1/OpenOffers.sol";
interface IFarbeMarketplace {
function assignToInstitution(address _institutionAddress, uint256 _tokenId, address _owner) external;
function getIsFarbeMarketplace() external view returns (bool);
}
/**
* @title ERC721 contract implementation
* @dev Implements the ERC721 interface for the Farbe artworks
*/
contract FarbeArtV3Upgradeable is Initializable, ERC721Upgradeable, ERC721EnumerableUpgradeable, ERC721URIStorageUpgradeable, AccessControlUpgradeable {
// counter for tracking token IDs
CountersUpgradeable.Counter internal _tokenIdCounter;
// details of the artwork
struct artworkDetails {
address tokenCreator;
uint16 creatorCut;
bool isSecondarySale;
}
// mapping of token id to original creator
mapping(uint256 => artworkDetails) public tokenIdToDetails;
// not using this here anymore, it has been moved to the farbe marketplace contract
// platform cut on primary sales in %age * 10
uint16 public platformCutOnPrimarySales;
// constant for defining the minter role
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
// reference to auction contract
AuctionSale public auctionSale;
// reference to fixed price contract
FixedPriceSale public fixedPriceSale;
// reference to open offer contract
OpenOffersSale public openOffersSale;
event TokenUriChanged(uint256 tokenId, string uri);
/**
* @dev Initializer for the ERC721 contract
*/
function initialize() public initializer {
__ERC721_init("FarbeArt", "FBA");
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
_setupRole(MINTER_ROLE, msg.sender);
}
/**
* @dev Implementation of ERC721Enumerable
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal
override(ERC721Upgradeable, ERC721EnumerableUpgradeable) {
super._beforeTokenTransfer(from, to, tokenId);
}
/**
* @dev Destroy (burn) the NFT
* @param tokenId The ID of the token to burn
*/
function _burn(uint256 tokenId) internal override(ERC721Upgradeable, ERC721URIStorageUpgradeable) {
super._burn(tokenId);
}
/**
* @dev Returns the Uniform Resource Identifier (URI) for the token
* @param tokenId ID of the token to return URI of
* @return URI for the token
*/
function tokenURI(uint256 tokenId) public view
override(ERC721Upgradeable, ERC721URIStorageUpgradeable) returns (string memory) {
return super.tokenURI(tokenId);
}
/**
* @dev Implementation of the ERC165 interface
* @param interfaceId The Id of the interface to check support for
*/
function supportsInterface(bytes4 interfaceId) public view
override(ERC721Upgradeable, ERC721EnumerableUpgradeable, AccessControlUpgradeable) returns (bool) {
return super.supportsInterface(interfaceId);
}
uint256[1000] private __gap;
}
/**
* @title Farbe NFT sale contract
* @dev Extension of the FarbeArt contract to add sale functionality
*/
contract FarbeArtSaleV3Upgradeable is FarbeArtV3Upgradeable {
/**
* @dev Only allow owner to execute if no one (gallery) has been approved
* @param _tokenId Id of the token to check approval and ownership of
*/
modifier onlyOwnerOrApproved(uint256 _tokenId) {
if(getApproved(_tokenId) == address(0)){
require(ownerOf(_tokenId) == msg.sender, "Not owner or approved");
} else {
require(getApproved(_tokenId) == msg.sender, "Only approved can list, revoke approval to list yourself");
}
_;
}
/**
* @dev Make sure the starting time is not greater than 60 days
* @param _startingTime starting time of the sale in UNIX timestamp
*/
modifier onlyValidStartingTime(uint64 _startingTime) {
if(_startingTime > block.timestamp) {
require(_startingTime - block.timestamp <= 60 days, "Start time too far");
}
_;
}
using CountersUpgradeable for CountersUpgradeable.Counter;
/**
* @dev Function to mint an artwork as NFT. If no gallery is approved, the parameter is zero
* @param _to The address to send the minted NFT
* @param _creatorCut The cut that the original creator will take on secondary sales
*/
function safeMint(
address _to,
address _galleryAddress,
uint8 _numberOfCopies,
uint16 _creatorCut,
string[] memory _tokenURI
) public {
require(hasRole(MINTER_ROLE, msg.sender), "does not have minter role");
require(_tokenURI.length == _numberOfCopies, "Metadata URIs not equal to editions");
for(uint i = 0; i < _numberOfCopies; i++){
// mint the token
_safeMint(_to, _tokenIdCounter.current());
// approve the gallery (0 if no gallery authorized)
setApprovalForAll(farbeMarketplace, true);
// set the token URI
_setTokenURI(_tokenIdCounter.current(), _tokenURI[i]);
// track token creator
tokenIdToDetails[_tokenIdCounter.current()].tokenCreator = _to;
// track creator's cut
tokenIdToDetails[_tokenIdCounter.current()].creatorCut = _creatorCut;
if(_galleryAddress != address(0)){
IFarbeMarketplace(farbeMarketplace).assignToInstitution(_galleryAddress, _tokenIdCounter.current(), msg.sender);
}
// increment tokenId
_tokenIdCounter.increment();
}
}
/**
* @dev Initializer for the FarbeArtSale contract
* name for initializer changed from "initialize" to "farbeInitialze" as it was causing override error with the initializer of NFT contract
*/
function farbeInitialize() public initializer {
FarbeArtV3Upgradeable.initialize();
}
function burn(uint256 tokenId) external {
// must be owner
require(ownerOf(tokenId) == msg.sender);
_burn(tokenId);
}
/**
* @dev Change the tokenUri of the token. Can only be changed when the creator is the owner
* @param _tokenURI New Uri of the token
* @param _tokenId Id of the token to change Uri of
*/
function changeTokenUri(string memory _tokenURI, uint256 _tokenId) external {
// must be owner and creator
require(ownerOf(_tokenId) == msg.sender, "Not owner");
require(tokenIdToDetails[_tokenId].tokenCreator == msg.sender, "Not creator");
_setTokenURI(_tokenId, _tokenURI);
emit TokenUriChanged(
uint256(_tokenId),
string(_tokenURI)
);
}
function setFarbeMarketplaceAddress(address _address) external onlyRole(DEFAULT_ADMIN_ROLE) {
farbeMarketplace = _address;
}
function getTokenCreatorAddress(uint256 _tokenId) public view returns(address) {
return tokenIdToDetails[_tokenId].tokenCreator;
}
function getTokenCreatorCut(uint256 _tokenId) public view returns(uint16) {
return tokenIdToDetails[_tokenId].creatorCut;
}
uint256[1000] private __gap;
// #sbt upgrades-plugin does not support __gaps for now
// so including the new variable here
address public farbeMarketplace;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721Upgradeable.sol";
import "./IERC721ReceiverUpgradeable.sol";
import "./extensions/IERC721MetadataUpgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../utils/StringsUpgradeable.sol";
import "../../utils/introspection/ERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable {
using AddressUpgradeable for address;
using StringsUpgradeable for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
function __ERC721_init(string memory name_, string memory symbol_) internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721_init_unchained(name_, symbol_);
}
function __ERC721_init_unchained(string memory name_, string memory symbol_) internal initializer {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) {
return
interfaceId == type(IERC721Upgradeable).interfaceId ||
interfaceId == type(IERC721MetadataUpgradeable).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. 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 = ERC721Upgradeable.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721Upgradeable.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721Upgradeable.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721ReceiverUpgradeable(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
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 {}
uint256[44] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC721Upgradeable.sol";
import "./IERC721EnumerableUpgradeable.sol";
import "../../../proxy/utils/Initializable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721EnumerableUpgradeable is Initializable, ERC721Upgradeable, IERC721EnumerableUpgradeable {
function __ERC721Enumerable_init() internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721Enumerable_init_unchained();
}
function __ERC721Enumerable_init_unchained() internal initializer {
}
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165Upgradeable, ERC721Upgradeable) returns (bool) {
return interfaceId == type(IERC721EnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Upgradeable.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721EnumerableUpgradeable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721Upgradeable.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721Upgradeable.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
uint256[46] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC721Upgradeable.sol";
import "../../../proxy/utils/Initializable.sol";
/**
* @dev ERC721 token with storage based token URI management.
*/
abstract contract ERC721URIStorageUpgradeable is Initializable, ERC721Upgradeable {
function __ERC721URIStorage_init() internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721URIStorage_init_unchained();
}
function __ERC721URIStorage_init_unchained() internal initializer {
}
using StringsUpgradeable 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];
}
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library 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
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../utils/StringsUpgradeable.sol";
import "../utils/introspection/ERC165Upgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControlUpgradeable {
function hasRole(bytes32 role, address account) external view returns (bool);
function getRoleAdmin(bytes32 role) external view returns (bytes32);
function grantRole(bytes32 role, address account) external;
function revokeRole(bytes32 role, address account) external;
function renounceRole(bytes32 role, address account) external;
}
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable {
function __AccessControl_init() internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__AccessControl_init_unchained();
}
function __AccessControl_init_unchained() internal initializer {
}
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
StringsUpgradeable.toHexString(uint160(account), 20),
" is missing role ",
StringsUpgradeable.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, getRoleAdmin(role), adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
pragma experimental ABIEncoderV2;
import "./FarbeArt.sol";
import "./SaleBase.sol";
/**
* @title Base auction contract
* @dev This is the base auction contract which implements the auction functionality
*/
contract AuctionBase is SaleBase {
using Address for address payable;
// auction struct to keep track of the auctions
struct Auction {
address seller;
address creator;
address gallery;
address buyer;
uint128 currentPrice;
uint64 duration;
uint64 startedAt;
uint16 creatorCut;
uint16 platformCut;
uint16 galleryCut;
}
// mapping for tokenId to its auction
mapping(uint256 => Auction) tokenIdToAuction;
event AuctionCreated(uint256 tokenId, uint256 startingPrice, uint256 duration);
event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner);
/**
* @dev Add the auction to the mapping and emit the AuctionCreated event, duration must meet the requirements
* @param _tokenId ID of the token to auction
* @param _auction Reference to the auction struct to add to the mapping
*/
function _addAuction(uint256 _tokenId, Auction memory _auction) internal {
// check minimum and maximum time requirements
require(_auction.duration >= 1 hours && _auction.duration <= 30 days, "time requirement failed");
// update mapping
tokenIdToAuction[_tokenId] = _auction;
// emit event
emit AuctionCreated(
uint256(_tokenId),
uint256(_auction.currentPrice),
uint256(_auction.duration)
);
}
/**
* @dev Remove the auction from the mapping (sets everything to zero/false)
* @param _tokenId ID of the token to remove auction of
*/
function _removeAuction(uint256 _tokenId) internal {
delete tokenIdToAuction[_tokenId];
}
/**
* @dev Internal function to check the current price of the auction
* @param auction Reference to the auction to check price of
* @return uint128 The current price of the auction
*/
function _currentPrice(Auction storage auction) internal view returns (uint128) {
return (auction.currentPrice);
}
/**
* @dev Internal function to return the bid to the previous bidder if there was one
* @param _destination Address of the previous bidder
* @param _amount Amount to return to the previous bidder
*/
function _returnBid(address payable _destination, uint256 _amount) private {
// zero address means there was no previous bidder
if (_destination != address(0)) {
_destination.sendValue(_amount);
}
}
/**
* @dev Internal function to check if an auction started. By default startedAt is at 0
* @param _auction Reference to the auction struct to check
* @return bool Weather the auction has started
*/
function _isOnAuction(Auction storage _auction) internal view returns (bool) {
return (_auction.startedAt > 0 && _auction.startedAt <= block.timestamp);
}
/**
* @dev Internal function to implement the bid functionality
* @param _tokenId ID of the token to bid upon
* @param _bidAmount Amount to bid
*/
function _bid(uint _tokenId, uint _bidAmount) internal {
// get reference to the auction struct
Auction storage auction = tokenIdToAuction[_tokenId];
// check if the item is on auction
require(_isOnAuction(auction), "Item is not on auction");
// check if auction time has ended
uint256 secondsPassed = block.timestamp - auction.startedAt;
require(secondsPassed <= auction.duration, "Auction time has ended");
// check if bid is higher than the previous one
uint256 price = auction.currentPrice;
require(_bidAmount > price, "Bid is too low");
// return the previous bidder's bid amount
_returnBid(payable(auction.buyer), auction.currentPrice);
// update the current bid amount and the bidder address
auction.currentPrice = uint128(_bidAmount);
auction.buyer = msg.sender;
// if the bid is made in the last 15 minutes, increase the duration of the
// auction so that the timer resets to 15 minutes
uint256 timeRemaining = auction.duration - secondsPassed;
if (timeRemaining <= 15 minutes) {
uint256 timeToAdd = 15 minutes - timeRemaining;
auction.duration += uint64(timeToAdd);
}
}
/**
* @dev Internal function to finish the auction after the auction time has ended
* @param _tokenId ID of the token to finish auction of
*/
function _finishAuction(uint256 _tokenId) internal {
// using storage for _isOnAuction
Auction storage auction = tokenIdToAuction[_tokenId];
// check if token was on auction
require(_isOnAuction(auction), "Token was not on auction");
// check if auction time has ended
uint256 secondsPassed = block.timestamp - auction.startedAt;
require(secondsPassed > auction.duration, "Auction hasn't ended");
// using struct to avoid stack too deep error
Auction memory referenceAuction = auction;
// delete the auction
_removeAuction(_tokenId);
// if there was no successful bid, return token to the seller
if (referenceAuction.buyer == address(0)) {
_transfer(referenceAuction.seller, _tokenId);
emit AuctionSuccessful(
_tokenId,
0,
referenceAuction.seller
);
}
// if there was a successful bid, pay the seller and transfer the token to the buyer
else {
_payout(
payable(referenceAuction.seller),
payable(referenceAuction.creator),
payable(referenceAuction.gallery),
referenceAuction.creatorCut,
referenceAuction.platformCut,
referenceAuction.galleryCut,
referenceAuction.currentPrice,
_tokenId
);
_transfer(referenceAuction.buyer, _tokenId);
emit AuctionSuccessful(
_tokenId,
referenceAuction.currentPrice,
referenceAuction.buyer
);
}
}
/**
* @dev This is an internal function to end auction meant to only be used as a safety
* mechanism if an NFT got locked within the contract. Can only be called by the super admin
* after a period f 7 days has passed since the auction ended
* @param _tokenId Id of the token to end auction of
* @param _nftBeneficiary Address to send the NFT to
* @param _paymentBeneficiary Address to send the payment to
*/
function _forceFinishAuction(
uint256 _tokenId,
address _nftBeneficiary,
address _paymentBeneficiary
)
internal
{
// using storage for _isOnAuction
Auction storage auction = tokenIdToAuction[_tokenId];
// check if token was on auction
require(_isOnAuction(auction), "Token was not on auction");
// check if auction time has ended
uint256 secondsPassed = block.timestamp - auction.startedAt;
require(secondsPassed > auction.duration, "Auction hasn't ended");
// check if its been more than 7 days since auction ended
require(secondsPassed - auction.duration >= 7 days);
// using struct to avoid stack too deep error
Auction memory referenceAuction = auction;
// delete the auction
_removeAuction(_tokenId);
// transfer ether to the beneficiary
payable(_paymentBeneficiary).sendValue(referenceAuction.currentPrice);
// transfer nft to the nft beneficiary
_transfer(_nftBeneficiary, _tokenId);
}
}
/**
* @title Auction sale contract that provides external functions
* @dev Implements the external and public functions of the auction implementation
*/
contract AuctionSale is AuctionBase {
// sanity check for the nft contract
bool public isFarbeSaleAuction = true;
// ERC721 interface id
bytes4 constant InterfaceSignature_ERC721 = bytes4(0x80ac58cd);
constructor(address _nftAddress, address _platformAddress) {
// check NFT contract supports ERC721 interface
FarbeArtSale candidateContract = FarbeArtSale(_nftAddress);
require(candidateContract.supportsInterface(InterfaceSignature_ERC721));
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
platformWalletAddress = _platformAddress;
NFTContract = candidateContract;
}
/**
* @dev External function to create auction. Called by the Farbe NFT contract
* @param _tokenId ID of the token to create auction for
* @param _startingPrice Starting price of the auction in wei
* @param _duration Duration of the auction in seconds
* @param _creator Address of the original creator of the NFT
* @param _seller Address of the seller of the NFT
* @param _gallery Address of the gallery of this auction, will be 0 if no gallery is involved
* @param _creatorCut The cut that goes to the creator, as %age * 10
* @param _galleryCut The cut that goes to the gallery, as %age * 10
* @param _platformCut The cut that goes to the platform if it is a primary sale
*/
function createSale(
uint256 _tokenId,
uint128 _startingPrice,
uint64 _startingTime,
uint64 _duration,
address _creator,
address _seller,
address _gallery,
uint16 _creatorCut,
uint16 _galleryCut,
uint16 _platformCut
)
external
onlyFarbeContract
{
// create and add the auction
Auction memory auction = Auction(
_seller,
_creator,
_gallery,
address(0),
uint128(_startingPrice),
uint64(_duration),
_startingTime,
_creatorCut,
_platformCut,
_galleryCut
);
_addAuction(_tokenId, auction);
}
/**
* @dev External payable bid function. Sellers can not bid on their own artworks
* @param _tokenId ID of the token to bid on
*/
function bid(uint256 _tokenId) external payable {
// do not allow sellers and galleries to bid on their own artwork
require(tokenIdToAuction[_tokenId].seller != msg.sender && tokenIdToAuction[_tokenId].gallery != msg.sender,
"Sellers and Galleries not allowed");
_bid(_tokenId, msg.value);
}
/**
* @dev External function to finish the auction. Currently can be called by anyone TODO restrict access?
* @param _tokenId ID of the token to finish auction of
*/
function finishAuction(uint256 _tokenId) external {
_finishAuction(_tokenId);
}
/**
* @dev External view function to get the details of an auction
* @param _tokenId ID of the token to get the auction information of
* @return seller Address of the seller
* @return buyer Address of the buyer
* @return currentPrice Current Price of the auction in wei
* @return duration Duration of the auction in seconds
* @return startedAt Unix timestamp for when the auction started
*/
function getAuction(uint256 _tokenId)
external
view
returns
(
address seller,
address buyer,
uint256 currentPrice,
uint256 duration,
uint256 startedAt
) {
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
return (
auction.seller,
auction.buyer,
auction.currentPrice,
auction.duration,
auction.startedAt
);
}
/**
* @dev External view function to get the current price of an auction
* @param _tokenId ID of the token to get the current price of
* @return uint128 Current price of the auction in wei
*/
function getCurrentPrice(uint256 _tokenId)
external
view
returns (uint128)
{
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
return _currentPrice(auction);
}
/**
* @dev Helper function for testing with timers TODO Remove this before deploying live
* @param _tokenId ID of the token to get timers of
*/
function getTimers(uint256 _tokenId)
external
view returns (
uint256 saleStart,
uint256 blockTimestamp,
uint256 duration
) {
Auction memory auction = tokenIdToAuction[_tokenId];
return (auction.startedAt, block.timestamp, auction.duration);
}
/**
* @dev This is an internal function to end auction meant to only be used as a safety
* mechanism if an NFT got locked within the contract. Can only be called by the super admin
* after a period f 7 days has passed since the auction ended
* @param _tokenId Id of the token to end auction of
* @param _nftBeneficiary Address to send the NFT to
* @param _paymentBeneficiary Address to send the payment to
*/
function forceFinishAuction(
uint256 _tokenId,
address _nftBeneficiary,
address _paymentBeneficiary
)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
_forceFinishAuction(_tokenId, _nftBeneficiary, _paymentBeneficiary);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./SaleBase.sol";
/**
* @title Base fixed price contract
* @dev This is the base fixed price contract which implements the internal functionality
*/
contract FixedPriceBase is SaleBase {
using Address for address payable;
// fixed price sale struct to keep track of the sales
struct FixedPrice {
address seller;
address creator;
address gallery;
uint128 fixedPrice;
uint64 startedAt;
uint16 creatorCut;
uint16 platformCut;
uint16 galleryCut;
}
// mapping for tokenId to its sale
mapping(uint256 => FixedPrice) tokenIdToSale;
event FixedSaleCreated(uint256 tokenId, uint256 fixedPrice);
event FixedSaleSuccessful(uint256 tokenId, uint256 totalPrice, address winner);
/**
* @dev Add the sale to the mapping and emit the FixedSaleCreated event
* @param _tokenId ID of the token to sell
* @param _fixedSale Reference to the sale struct to add to the mapping
*/
function _addSale(uint256 _tokenId, FixedPrice memory _fixedSale) internal {
// update mapping
tokenIdToSale[_tokenId] = _fixedSale;
// emit event
emit FixedSaleCreated(
uint256(_tokenId),
uint256(_fixedSale.fixedPrice)
);
}
/**
* @dev Remove the sale from the mapping (sets everything to zero/false)
* @param _tokenId ID of the token to remove sale of
*/
function _removeSale(uint256 _tokenId) internal {
delete tokenIdToSale[_tokenId];
}
/**
* @dev Internal function to check if a sale started. By default startedAt is at 0
* @param _fixedSale Reference to the sale struct to check
* @return bool Weather the sale has started
*/
function _isOnSale(FixedPrice storage _fixedSale) internal view returns (bool) {
return (_fixedSale.startedAt > 0 && _fixedSale.startedAt <= block.timestamp);
}
/**
* @dev Internal function to buy a token on sale
* @param _tokenId Id of the token to buy
* @param _amount The amount in wei
*/
function _buy(uint256 _tokenId, uint256 _amount) internal {
// get reference to the fixed price sale struct
FixedPrice storage fixedSale = tokenIdToSale[_tokenId];
// check if the item is on sale
require(_isOnSale(fixedSale), "Item is not on sale");
// check if sent amount is equal or greater than the set price
require(_amount >= fixedSale.fixedPrice, "Amount sent is not enough to buy the token");
// using struct to avoid stack too deep error
FixedPrice memory referenceFixedSale = fixedSale;
// delete the sale
_removeSale(_tokenId);
// pay the seller, and distribute cuts
_payout(
payable(referenceFixedSale.seller),
payable(referenceFixedSale.creator),
payable(referenceFixedSale.gallery),
referenceFixedSale.creatorCut,
referenceFixedSale.platformCut,
referenceFixedSale.galleryCut,
_amount,
_tokenId
);
// transfer the token to the buyer
_transfer(msg.sender, _tokenId);
emit FixedSaleSuccessful(_tokenId, referenceFixedSale.fixedPrice, msg.sender);
}
/**
* @dev Function to finish the sale. Can be called manually if no one bought the NFT. If
* a gallery put the artwork on sale, only it can call this function. The super admin can
* also call the function, this is implemented as a safety mechanism for the seller in case
* the gallery becomes idle
* @param _tokenId Id of the token to end sale of
*/
function _finishSale(uint256 _tokenId) internal {
FixedPrice storage fixedSale = tokenIdToSale[_tokenId];
// only the gallery can finish the sale if it was the one to put it on auction
if(fixedSale.gallery != address(0)) {
require(fixedSale.gallery == msg.sender || hasRole(DEFAULT_ADMIN_ROLE, msg.sender));
} else {
require(fixedSale.seller == msg.sender || hasRole(DEFAULT_ADMIN_ROLE, msg.sender));
}
// check if token was on sale
require(_isOnSale(fixedSale));
address seller = fixedSale.seller;
// delete the sale
_removeSale(_tokenId);
// return the token to the seller
_transfer(seller, _tokenId);
}
}
/**
* @title Fixed Price sale contract that provides external functions
* @dev Implements the external and public functions of the Fixed price implementation
*/
contract FixedPriceSale is FixedPriceBase {
// sanity check for the nft contract
bool public isFarbeFixedSale = true;
// ERC721 interface id
bytes4 constant InterfaceSignature_ERC721 = bytes4(0x80ac58cd);
constructor(address _nftAddress, address _platformAddress) {
// check NFT contract supports ERC721 interface
FarbeArtSale candidateContract = FarbeArtSale(_nftAddress);
require(candidateContract.supportsInterface(InterfaceSignature_ERC721));
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
platformWalletAddress = _platformAddress;
NFTContract = candidateContract;
}
/**
* @dev External function to create fixed sale. Called by the Farbe NFT contract
* @param _tokenId ID of the token to create sale for
* @param _fixedPrice Starting price of the sale in wei
* @param _creator Address of the original creator of the NFT
* @param _seller Address of the seller of the NFT
* @param _gallery Address of the gallery of this sale, will be 0 if no gallery is involved
* @param _creatorCut The cut that goes to the creator, as %age * 10
* @param _galleryCut The cut that goes to the gallery, as %age * 10
* @param _platformCut The cut that goes to the platform if it is a primary sale
*/
function createSale(
uint256 _tokenId,
uint128 _fixedPrice,
uint64 _startingTime,
address _creator,
address _seller,
address _gallery,
uint16 _creatorCut,
uint16 _galleryCut,
uint16 _platformCut
)
external
onlyFarbeContract
{
// create and add the sale
FixedPrice memory fixedSale = FixedPrice(
_seller,
_creator,
_gallery,
_fixedPrice,
_startingTime,
_creatorCut,
_platformCut,
_galleryCut
);
_addSale(_tokenId, fixedSale);
}
/**
* @dev External payable function to buy the artwork
* @param _tokenId Id of the token to buy
*/
function buy(uint256 _tokenId) external payable {
// do not allow sellers and galleries to buy their own artwork
require(tokenIdToSale[_tokenId].seller != msg.sender && tokenIdToSale[_tokenId].gallery != msg.sender,
"Sellers and Galleries not allowed");
_buy(_tokenId, msg.value);
}
/**
* @dev External function to finish the sale if no one bought it. Can only be called by the owner or gallery
* @param _tokenId ID of the token to finish sale of
*/
function finishSale(uint256 _tokenId) external {
_finishSale(_tokenId);
}
/**
* @dev External view function to get the details of a sale
* @param _tokenId ID of the token to get the sale information of
* @return seller Address of the seller
* @return fixedPrice Fixed Price of the sale in wei
* @return startedAt Unix timestamp for when the sale started
*/
function getFixedSale(uint256 _tokenId)
external
view
returns
(
address seller,
uint256 fixedPrice,
uint256 startedAt
) {
FixedPrice storage fixedSale = tokenIdToSale[_tokenId];
require(_isOnSale(fixedSale), "Item is not on sale");
return (
fixedSale.seller,
fixedSale.fixedPrice,
fixedSale.startedAt
);
}
/**
* @dev Helper function for testing with timers TODO Remove this before deploying live
* @param _tokenId ID of the token to get timers of
*/
function getTimers(uint256 _tokenId)
external
view returns (
uint256 saleStart,
uint256 blockTimestamp
) {
FixedPrice memory fixedSale = tokenIdToSale[_tokenId];
return (fixedSale.startedAt, block.timestamp);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/security/PullPayment.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "./SaleBase.sol";
import "../EnumerableMap.sol";
/**
* @title Base open offers contract
* @dev This is the base contract which implements the open offers functionality
*/
contract OpenOffersBase is PullPayment, ReentrancyGuard, SaleBase {
using Address for address payable;
// Add the library methods
using EnumerableMap for EnumerableMap.AddressToUintMap;
struct OpenOffers {
address seller;
address creator;
address gallery;
uint64 startedAt;
uint16 creatorCut;
uint16 platformCut;
uint16 galleryCut;
EnumerableMap.AddressToUintMap offers;
}
// this struct is only used for referencing in memory. The OpenOffers struct can not
// be used because it is only valid in storage since it contains a nested mapping
struct OffersReference {
address seller;
address creator;
address gallery;
uint16 creatorCut;
uint16 platformCut;
uint16 galleryCut;
}
// mapping for tokenId to its sale
mapping(uint256 => OpenOffers) tokenIdToSale;
event OpenOffersSaleCreated(uint256 tokenId);
event OpenOffersSaleSuccessful(uint256 tokenId, uint256 totalPrice, address winner);
/**
* @dev Internal function to check if the sale started, by default startedAt will be 0
*
*/
function _isOnSale(OpenOffers storage _openSale) internal view returns (bool) {
return (_openSale.startedAt > 0 && _openSale.startedAt <= block.timestamp);
}
/**
* @dev Remove the sale from the mapping (sets everything to zero/false)
* @param _tokenId ID of the token to remove sale of
*/
function _removeSale(uint256 _tokenId) internal {
delete tokenIdToSale[_tokenId];
}
/**
* @dev Internal that updates the mapping when a new offer is made for a token on sale
* @param _tokenId Id of the token to make offer on
* @param _bidAmount The offer in wei
*/
function _makeOffer(uint _tokenId, uint _bidAmount) internal {
// get reference to the open offer struct
OpenOffers storage openSale = tokenIdToSale[_tokenId];
// check if the item is on sale
require(_isOnSale(openSale));
uint256 returnAmount;
bool offerExists;
// get reference to the amount to return
(offerExists, returnAmount) = openSale.offers.tryGet(msg.sender);
// update the mapping with the new offer
openSale.offers.set(msg.sender, _bidAmount);
// if there was a previous offer from this address, return the previous offer amount
if(offerExists){
payable(msg.sender).sendValue(returnAmount);
}
}
/**
* @dev Internal function to accept the offer of an address. Once an offer is accepted, all existing offers
* for the token are moved into the PullPayment contract and the mapping is deleted. Only gallery can accept
* offers if the sale involves a gallery
* @param _tokenId Id of the token to accept offer of
* @param _buyer The address of the buyer to accept offer from
*/
function _acceptOffer(uint256 _tokenId, address _buyer) internal nonReentrant {
OpenOffers storage openSale = tokenIdToSale[_tokenId];
// only the gallery can accept the offer if it was the one to put it on auction
if(openSale.gallery != address(0)) {
require(openSale.gallery == msg.sender);
} else {
require(openSale.seller == msg.sender);
}
// check if token was on sale
require(_isOnSale(openSale));
// check if the offer from the buyer exists
require(openSale.offers.contains(_buyer));
// get reference to the offer
uint256 _payoutAmount = openSale.offers.get(_buyer);
// remove the offer from the enumerable mapping
openSale.offers.remove(_buyer);
address returnAddress;
uint256 returnAmount;
// put the returns in the pull payments contract
for (uint i = 0; i < openSale.offers.length(); i++) {
(returnAddress, returnAmount) = openSale.offers.at(i);
// transfer the return amount into the pull payement contract
_asyncTransfer(returnAddress, returnAmount);
}
// using struct to avoid stack too deep error
OffersReference memory openSaleReference = OffersReference(
openSale.seller,
openSale.creator,
openSale.gallery,
openSale.creatorCut,
openSale.platformCut,
openSale.galleryCut
);
// delete the sale
_removeSale(_tokenId);
// pay the seller and distribute the cuts
_payout(
payable(openSaleReference.seller),
payable(openSaleReference.creator),
payable(openSaleReference.gallery),
openSaleReference.creatorCut,
openSaleReference.platformCut,
openSaleReference.galleryCut,
_payoutAmount,
_tokenId
);
// transfer the token to the buyer
_transfer(_buyer, _tokenId);
}
/**
* @dev Internal function to cancel an offer. This is used for both rejecting and revoking offers
* @param _tokenId Id of the token to cancel offer of
* @param _buyer The address to cancel bid of
*/
function _cancelOffer(uint256 _tokenId, address _buyer) internal {
OpenOffers storage openSale = tokenIdToSale[_tokenId];
// check if token was on sale
require(_isOnSale(openSale));
// get reference to the offer, will fail if mapping doesn't exist
uint256 _payoutAmount = openSale.offers.get(_buyer);
// remove the offer from the enumerable mapping
openSale.offers.remove(_buyer);
// return the ether
payable(_buyer).sendValue(_payoutAmount);
}
/**
* @dev Function to finish the sale. Can be called manually if there was no suitable offer
* for the NFT. If a gallery put the artwork on sale, only it can call this function.
* The super admin can also call the function, this is implemented as a safety mechanism for
* the seller in case the gallery becomes idle
* @param _tokenId Id of the token to end sale of
*/
function _finishSale(uint256 _tokenId) internal nonReentrant {
OpenOffers storage openSale = tokenIdToSale[_tokenId];
// only the gallery or admin can finish the sale if it was the one to put it on auction
if(openSale.gallery != address(0)) {
require(openSale.gallery == msg.sender || hasRole(DEFAULT_ADMIN_ROLE, msg.sender));
} else {
require(openSale.seller == msg.sender || hasRole(DEFAULT_ADMIN_ROLE, msg.sender));
}
// check if token was on sale
require(_isOnSale(openSale));
address seller = openSale.seller;
address returnAddress;
uint256 returnAmount;
// put all pending returns in the pull payments contract
for (uint i = 0; i < openSale.offers.length(); i++) {
(returnAddress, returnAmount) = openSale.offers.at(i);
// transfer the return amount into the pull payement contract
_asyncTransfer(returnAddress, returnAmount);
}
// delete the sale
_removeSale(_tokenId);
// return the token to the seller
_transfer(seller, _tokenId);
}
}
/**
* @title Open Offers sale contract that provides external functions
* @dev Implements the external and public functions of the open offers implementation
*/
contract OpenOffersSale is OpenOffersBase {
bool public isFarbeOpenOffersSale = true;
/**
* External function to create an Open Offers sale. Can only be called by the Farbe NFT contract
* @param _tokenId Id of the token to create sale for
* @param _startingTime Starting time of the sale
* @param _creator Address of the original creator of the artwork
* @param _seller Address of the owner of the artwork
* @param _gallery Address of the gallery of the artwork, 0 address if gallery is not involved
* @param _creatorCut Cut of the creator in %age * 10
* @param _galleryCut Cut of the gallery in %age * 10
* @param _platformCut Cut of the platform on primary sales in %age * 10
*/
function createSale(
uint256 _tokenId,
uint64 _startingTime,
address _creator,
address _seller,
address _gallery,
uint16 _creatorCut,
uint16 _galleryCut,
uint16 _platformCut
)
external
onlyFarbeContract
{
OpenOffers storage openOffers = tokenIdToSale[_tokenId];
openOffers.seller = _seller;
openOffers.creator = _creator;
openOffers.gallery = _gallery;
openOffers.startedAt = _startingTime;
openOffers.creatorCut = _creatorCut;
openOffers.platformCut = _platformCut;
openOffers.galleryCut = _galleryCut;
}
/**
* @dev External function that allows others to make offers for an artwork
* @param _tokenId Id of the token to make offer for
*/
function makeOffer(uint256 _tokenId) external payable {
// do not allow sellers and galleries to make offers on their own artwork
require(tokenIdToSale[_tokenId].seller != msg.sender && tokenIdToSale[_tokenId].gallery != msg.sender,
"Sellers and Galleries not allowed");
_makeOffer(_tokenId, msg.value);
}
/**
* @dev External function to allow a gallery or a seller to accept an offer
* @param _tokenId Id of the token to accept offer of
* @param _buyer Address of the buyer to accept offer of
*/
function acceptOffer(uint256 _tokenId, address _buyer) external {
_acceptOffer(_tokenId, _buyer);
}
/**
* @dev External function to reject a particular offer and return the ether
* @param _tokenId Id of the token to reject offer of
* @param _buyer Address of the buyer to reject offer of
*/
function rejectOffer(uint256 _tokenId, address _buyer) external {
// only owner or gallery can reject an offer
require(tokenIdToSale[_tokenId].seller == msg.sender || tokenIdToSale[_tokenId].gallery == msg.sender);
_cancelOffer(_tokenId, _buyer);
}
/**
* @dev External function to allow buyers to revoke their offers
* @param _tokenId Id of the token to revoke offer of
*/
function revokeOffer(uint256 _tokenId) external {
_cancelOffer(_tokenId, msg.sender);
}
/**
* @dev External function to finish the sale if no one bought it. Can only be called by the owner or gallery
* @param _tokenId ID of the token to finish sale of
*/
function finishSale(uint256 _tokenId) external {
_finishSale(_tokenId);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165Upgradeable.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721Upgradeable is IERC165Upgradeable {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721ReceiverUpgradeable {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721Upgradeable.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721MetadataUpgradeable is IERC721Upgradeable {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) private pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal initializer {
__ERC165_init_unchained();
}
function __ERC165_init_unchained() internal initializer {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721Upgradeable.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721EnumerableUpgradeable is IERC721Upgradeable {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "./OpenOffers.sol";
import "./Auction.sol";
import "./FixedPrice.sol";
/**
* @title ERC721 contract implementation
* @dev Implements the ERC721 interface for the Farbe artworks
*/
contract FarbeArt is ERC721, ERC721Enumerable, ERC721URIStorage, AccessControl {
// counter for tracking token IDs
using Counters for Counters.Counter;
Counters.Counter private _tokenIdCounter;
// details of the artwork
struct artworkDetails {
address tokenCreator;
uint16 creatorCut;
bool isSecondarySale;
}
// mapping of token id to original creator
mapping(uint256 => artworkDetails) tokenIdToDetails;
// platform cut on primary sales in %age * 10
uint16 public platformCutOnPrimarySales;
// constant for defining the minter role
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
// reference to auction contract
AuctionSale public auctionSale;
// reference to fixed price contract
FixedPriceSale public fixedPriceSale;
// reference to open offer contract
OpenOffersSale public openOffersSale;
event TokenUriChanged(uint256 tokenId, string uri);
/**
* @dev Constructor for the ERC721 contract
*/
constructor() ERC721("FarbeArt", "FBA") {
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
_setupRole(MINTER_ROLE, msg.sender);
}
/**
* @dev Function to mint an artwork as NFT. If no gallery is approved, the parameter is zero
* @param _to The address to send the minted NFT
* @param _creatorCut The cut that the original creator will take on secondary sales
*/
function safeMint(
address _to,
address _galleryAddress,
uint8 _numberOfCopies,
uint16 _creatorCut,
string[] memory _tokenURI
) public {
require(hasRole(MINTER_ROLE, msg.sender), "does not have minter role");
require(_tokenURI.length == _numberOfCopies, "Metadata URIs not equal to editions");
for(uint i = 0; i < _numberOfCopies; i++){
// mint the token
_safeMint(_to, _tokenIdCounter.current());
// approve the gallery (0 if no gallery authorized)
approve(_galleryAddress, _tokenIdCounter.current());
// set the token URI
_setTokenURI(_tokenIdCounter.current(), _tokenURI[i]);
// track token creator
tokenIdToDetails[_tokenIdCounter.current()].tokenCreator = _to;
// track creator's cut
tokenIdToDetails[_tokenIdCounter.current()].creatorCut = _creatorCut;
// increment tokenId
_tokenIdCounter.increment();
}
}
/**
* @dev Implementation of ERC721Enumerable
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal
override(ERC721, ERC721Enumerable) {
super._beforeTokenTransfer(from, to, tokenId);
}
/**
* @dev Destroy (burn) the NFT
* @param tokenId The ID of the token to burn
*/
function _burn(uint256 tokenId) internal override(ERC721, ERC721URIStorage) {
super._burn(tokenId);
}
/**
* @dev Returns the Uniform Resource Identifier (URI) for the token
* @param tokenId ID of the token to return URI of
* @return URI for the token
*/
function tokenURI(uint256 tokenId) public view
override(ERC721, ERC721URIStorage) returns (string memory) {
return super.tokenURI(tokenId);
}
/**
* @dev Implementation of the ERC165 interface
* @param interfaceId The Id of the interface to check support for
*/
function supportsInterface(bytes4 interfaceId) public view
override(ERC721, ERC721Enumerable, AccessControl) returns (bool) {
return super.supportsInterface(interfaceId);
}
}
/**
* @title Farbe NFT sale contract
* @dev Extension of the FarbeArt contract to add sale functionality
*/
contract FarbeArtSale is FarbeArt {
/**
* @dev Only allow owner to execute if no one (gallery) has been approved
* @param _tokenId Id of the token to check approval and ownership of
*/
modifier onlyOwnerOrApproved(uint256 _tokenId) {
if(getApproved(_tokenId) == address(0)){
require(ownerOf(_tokenId) == msg.sender, "Not owner or approved");
} else {
require(getApproved(_tokenId) == msg.sender, "Only approved can list, revoke approval to list yourself");
}
_;
}
/**
* @dev Make sure the starting time is not greater than 60 days
* @param _startingTime starting time of the sale in UNIX timestamp
*/
modifier onlyValidStartingTime(uint64 _startingTime) {
if(_startingTime > block.timestamp) {
require(_startingTime - block.timestamp <= 60 days, "Start time too far");
}
_;
}
/**
* @dev Set the primary platform cut on deployment
* @param _platformCut Cut that the platform will take on primary sales
*/
constructor(uint16 _platformCut) {
platformCutOnPrimarySales = _platformCut;
}
function burn(uint256 tokenId) external {
// must be owner
require(ownerOf(tokenId) == msg.sender);
_burn(tokenId);
}
/**
* @dev Change the tokenUri of the token. Can only be changed when the creator is the owner
* @param _tokenURI New Uri of the token
* @param _tokenId Id of the token to change Uri of
*/
function changeTokenUri(string memory _tokenURI, uint256 _tokenId) external {
// must be owner and creator
require(ownerOf(_tokenId) == msg.sender, "Not owner");
require(tokenIdToDetails[_tokenId].tokenCreator == msg.sender, "Not creator");
_setTokenURI(_tokenId, _tokenURI);
emit TokenUriChanged(
uint256(_tokenId),
string(_tokenURI)
);
}
/**
* @dev Set the address for the external auction contract. Can only be set by the admin
* @param _address Address of the external contract
*/
function setAuctionContractAddress(address _address) external onlyRole(DEFAULT_ADMIN_ROLE) {
AuctionSale auction = AuctionSale(_address);
require(auction.isFarbeSaleAuction());
auctionSale = auction;
}
/**
* @dev Set the address for the external auction contract. Can only be set by the admin
* @param _address Address of the external contract
*/
function setFixedSaleContractAddress(address _address) external onlyRole(DEFAULT_ADMIN_ROLE) {
FixedPriceSale fixedSale = FixedPriceSale(_address);
require(fixedSale.isFarbeFixedSale());
fixedPriceSale = fixedSale;
}
/**
* @dev Set the address for the external auction contract. Can only be set by the admin
* @param _address Address of the external contract
*/
function setOpenOffersContractAddress(address _address) external onlyRole(DEFAULT_ADMIN_ROLE) {
OpenOffersSale openOffers = OpenOffersSale(_address);
require(openOffers.isFarbeOpenOffersSale());
openOffersSale = openOffers;
}
/**
* @dev Set the percentage cut that the platform will take on all primary sales
* @param _platformCut The cut that the platform will take on primary sales as %age * 10 for values < 1%
*/
function setPlatformCut(uint16 _platformCut) external onlyRole(DEFAULT_ADMIN_ROLE) {
platformCutOnPrimarySales = _platformCut;
}
/**
* @dev Track artwork as sold before by updating the mapping. Can only be called by the sales contracts
* @param _tokenId The id of the token which was sold
*/
function setSecondarySale(uint256 _tokenId) external {
require(msg.sender != address(0));
require(msg.sender == address(auctionSale) || msg.sender == address(fixedPriceSale)
|| msg.sender == address(openOffersSale), "Caller is not a farbe sale contract");
tokenIdToDetails[_tokenId].isSecondarySale = true;
}
/**
* @dev Checks from the mapping if the token has been sold before
* @param _tokenId ID of the token to check
* @return bool Weather this is a secondary sale (token has been sold before)
*/
function getSecondarySale(uint256 _tokenId) public view returns (bool) {
return tokenIdToDetails[_tokenId].isSecondarySale;
}
/**
* @dev Creates the sale auction for the token by calling the external auction contract. Can only be called by owner,
* individual external contract calls are expensive so a single function is used to pass all parameters
* @param _tokenId ID of the token to put on auction
* @param _startingPrice Starting price of the auction
* @param _startingTime Starting time of the auction in UNIX timestamp
* @param _duration The duration in seconds for the auction
* @param _galleryCut The cut for the gallery, will be 0 if gallery is not involved
*/
function createSaleAuction(
uint256 _tokenId,
uint128 _startingPrice,
uint64 _startingTime,
uint64 _duration,
uint16 _galleryCut
)
external
onlyOwnerOrApproved(_tokenId)
onlyValidStartingTime(_startingTime)
{
// using struct to avoid 'stack too deep' error
artworkDetails memory _details = artworkDetails(
tokenIdToDetails[_tokenId].tokenCreator,
tokenIdToDetails[_tokenId].creatorCut,
false
);
require(_details.creatorCut + _galleryCut + platformCutOnPrimarySales < 1000, "Cuts greater than 100%");
// determine gallery address (0 if called by owner)
address _galleryAddress = ownerOf(_tokenId) == msg.sender ? address(0) : msg.sender;
// get reference to owner before transfer
address _seller = ownerOf(_tokenId);
// escrow the token into the auction smart contract
safeTransferFrom(_seller, address(auctionSale), _tokenId);
// call the external contract function to create the auction
auctionSale.createSale(
_tokenId,
_startingPrice,
_startingTime,
_duration,
_details.tokenCreator,
_seller,
_galleryAddress,
_details.creatorCut,
_galleryCut,
platformCutOnPrimarySales
);
}
/**
* @dev Creates the fixed price sale for the token by calling the external fixed sale contract. Can only be called by owner.
* Individual external contract calls are expensive so a single function is used to pass all parameters
* @param _tokenId ID of the token to put on auction
* @param _fixedPrice Fixed price of the auction
* @param _startingTime Starting time of the auction in UNIX timestamp
* @param _galleryCut The cut for the gallery, will be 0 if gallery is not involved
*/
function createSaleFixedPrice(
uint256 _tokenId,
uint128 _fixedPrice,
uint64 _startingTime,
uint16 _galleryCut
)
external
onlyOwnerOrApproved(_tokenId)
onlyValidStartingTime(_startingTime)
{
// using struct to avoid 'stack too deep' error
artworkDetails memory _details = artworkDetails(
tokenIdToDetails[_tokenId].tokenCreator,
tokenIdToDetails[_tokenId].creatorCut,
false
);
require(_details.creatorCut + _galleryCut + platformCutOnPrimarySales < 1000, "Cuts greater than 100%");
// determine gallery address (0 if called by owner)
address _galleryAddress = ownerOf(_tokenId) == msg.sender ? address(0) : msg.sender;
// get reference to owner before transfer
address _seller = ownerOf(_tokenId);
// escrow the token into the auction smart contract
safeTransferFrom(ownerOf(_tokenId), address(fixedPriceSale), _tokenId);
// call the external contract function to create the auction
fixedPriceSale.createSale(
_tokenId,
_fixedPrice,
_startingTime,
_details.tokenCreator,
_seller,
_galleryAddress,
_details.creatorCut,
_galleryCut,
platformCutOnPrimarySales
);
}
/**
* @dev Creates the open offer sale for the token by calling the external open offers contract. Can only be called by owner,
* individual external contract calls are expensive so a single function is used to pass all parameters
* @param _tokenId ID of the token to put on auction
* @param _startingTime Starting time of the auction in UNIX timestamp
* @param _galleryCut The cut for the gallery, will be 0 if gallery is not involved
*/
function createSaleOpenOffer(
uint256 _tokenId,
uint64 _startingTime,
uint16 _galleryCut
)
external
onlyOwnerOrApproved(_tokenId)
onlyValidStartingTime(_startingTime)
{
// using struct to avoid 'stack too deep' error
artworkDetails memory _details = artworkDetails(
tokenIdToDetails[_tokenId].tokenCreator,
tokenIdToDetails[_tokenId].creatorCut,
false
);
require(_details.creatorCut + _galleryCut + platformCutOnPrimarySales < 1000, "Cuts greater than 100%");
// get reference to owner before transfer
address _seller = ownerOf(_tokenId);
// determine gallery address (0 if called by owner)
address _galleryAddress = ownerOf(_tokenId) == msg.sender ? address(0) : msg.sender;
// escrow the token into the auction smart contract
safeTransferFrom(ownerOf(_tokenId), address(openOffersSale), _tokenId);
// call the external contract function to create the auction
openOffersSale.createSale(
_tokenId,
_startingTime,
_details.tokenCreator,
_seller,
_galleryAddress,
_details.creatorCut,
_galleryCut,
platformCutOnPrimarySales
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
import "./FarbeArt.sol";
contract SaleBase is IERC721Receiver, AccessControl {
using Address for address payable;
// reference to the NFT contract
FarbeArtSale public NFTContract;
// address of the platform wallet to which the platform cut will be sent
address internal platformWalletAddress;
modifier onlyFarbeContract() {
// check the caller is the FarbeNFT contract
require(msg.sender == address(NFTContract), "Caller is not the Farbe contract");
_;
}
/**
* @dev Implementation of ERC721Receiver
*/
function onERC721Received(
address _operator,
address _from,
uint256 _tokenId,
bytes memory _data
) public override virtual returns (bytes4) {
// This will fail if the received token is not a FarbeArt token
// _owns calls NFTContract
require(_owns(address(this), _tokenId), "owner is not the sender");
return this.onERC721Received.selector;
}
/**
* @dev Internal function to check if address owns a token
* @param _claimant The address to check
* @param _tokenId ID of the token to check for ownership
* @return bool Weather the _claimant owns the _tokenId
*/
function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) {
return (NFTContract.ownerOf(_tokenId) == _claimant);
}
/**
* @dev Internal function to transfer the NFT from this contract to another address
* @param _receiver The address to send the NFT to
* @param _tokenId ID of the token to transfer
*/
function _transfer(address _receiver, uint256 _tokenId) internal {
NFTContract.safeTransferFrom(address(this), _receiver, _tokenId);
}
/**
* @dev Internal function that calculates the cuts of all parties and distributes the payment among them
* @param _seller Address of the seller
* @param _creator Address of the original creator
* @param _gallery Address of the gallery, 0 address if gallery is not involved
* @param _creatorCut The cut of the original creator
* @param _platformCut The cut that goes to the Farbe platform
* @param _galleryCut The cut that goes to the gallery
* @param _amount The total amount to be split
* @param _tokenId The ID of the token that was sold
*/
function _payout(
address payable _seller,
address payable _creator,
address payable _gallery,
uint16 _creatorCut,
uint16 _platformCut,
uint16 _galleryCut,
uint256 _amount,
uint256 _tokenId
) internal {
// if this is a secondary sale
if (NFTContract.getSecondarySale(_tokenId)) {
// initialize amount to send to gallery, defaults to 0
uint256 galleryAmount;
// calculate gallery cut if this is a gallery sale, wrapped in an if statement in case owner
// accidentally sets a gallery cut
if(_gallery != address(0)){
galleryAmount = (_galleryCut * _amount) / 1000;
}
// platform gets 2.5% on secondary sales (hard-coded)
uint256 platformAmount = (25 * _amount) / 1000;
// calculate amount to send to creator
uint256 creatorAmount = (_creatorCut * _amount) / 1000;
// calculate amount to send to the seller
uint256 sellerAmount = _amount - (platformAmount + creatorAmount + galleryAmount);
// repeating if statement to follow check-effect-interaction pattern
if(_gallery != address(0)) {
_gallery.sendValue(galleryAmount);
}
payable(platformWalletAddress).sendValue(platformAmount);
_creator.sendValue(creatorAmount);
_seller.sendValue(sellerAmount);
}
// if this is a primary sale
else {
require(_seller == _creator, "Seller is not the creator");
// dividing by 1000 because percentages are multiplied by 10 for values < 1%
uint256 platformAmount = (_platformCut * _amount) / 1000;
// initialize amount to be sent to gallery, defaults to 0
uint256 galleryAmount;
// calculate gallery cut if this is a gallery sale wrapped in an if statement in case owner
// accidentally sets a gallery cut
if(_gallery != address(0)) {
galleryAmount = (_galleryCut * _amount) / 1000;
}
// calculate the amount to send to the seller
uint256 sellerAmount = _amount - (platformAmount + galleryAmount);
// repeating if statement to follow check-effect-interaction pattern
if(_gallery != address(0)) {
_gallery.sendValue(galleryAmount);
}
_seller.sendValue(sellerAmount);
payable(platformWalletAddress).sendValue(platformAmount);
// set secondary sale to true
NFTContract.setSecondarySale(_tokenId);
}
}
/**
* @dev External function to allow admin to change the address of the platform wallet
* @param _address Address of the new wallet
*/
function setPlatformWalletAddress(address _address) external onlyRole(DEFAULT_ADMIN_ROLE) {
platformWalletAddress = _address;
}
}
// SPDX-License-Identifier: MIT
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}. Empty by default, can be overriden
* in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(address from, address to, uint256 tokenId) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual {
_mint(to, tokenId);
require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(address from, address to, uint256 tokenId) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
private returns (bool)
{
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
// solhint-disable-next-line no-inline-assembly
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { }
}
// SPDX-License-Identifier: MIT
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
pragma solidity ^0.8.0;
import "../ERC721.sol";
/**
* @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];
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library 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;
}
}
}
// 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;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../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;
// 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.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant alphabet = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = alphabet[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
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
pragma solidity ^0.8.0;
import "../utils/escrow/Escrow.sol";
/**
* @dev Simple implementation of a
* https://consensys.github.io/smart-contract-best-practices/recommendations/#favor-pull-over-push-for-external-calls[pull-payment]
* strategy, where the paying contract doesn't interact directly with the
* receiver account, which must withdraw its payments itself.
*
* Pull-payments are often considered the best practice when it comes to sending
* Ether, security-wise. It prevents recipients from blocking execution, and
* eliminates reentrancy concerns.
*
* 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].
*
* To use, derive from the `PullPayment` contract, and use {_asyncTransfer}
* instead of Solidity's `transfer` function. Payees can query their due
* payments with {payments}, and retrieve them with {withdrawPayments}.
*/
abstract contract PullPayment {
Escrow immutable private _escrow;
constructor () {
_escrow = new Escrow();
}
/**
* @dev Withdraw accumulated payments, forwarding all gas to the recipient.
*
* Note that _any_ account can call this function, not just the `payee`.
* This means that contracts unaware of the `PullPayment` protocol can still
* receive funds this way, by having a separate account call
* {withdrawPayments}.
*
* WARNING: Forwarding all gas opens the door to reentrancy vulnerabilities.
* Make sure you trust the recipient, or are either following the
* checks-effects-interactions pattern or using {ReentrancyGuard}.
*
* @param payee Whose payments will be withdrawn.
*/
function withdrawPayments(address payable payee) public virtual {
_escrow.withdraw(payee);
}
/**
* @dev Returns the payments owed to an address.
* @param dest The creditor's address.
*/
function payments(address dest) public view returns (uint256) {
return _escrow.depositsOf(dest);
}
/**
* @dev Called by the payer to store the sent amount as credit to be pulled.
* Funds sent in this way are stored in an intermediate {Escrow} contract, so
* there is no danger of them being spent before withdrawal.
*
* @param dest The destination address of the funds.
* @param amount The amount to transfer.
*/
function _asyncTransfer(address dest, uint256 amount) internal virtual {
_escrow.deposit{ value: amount }(dest);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
/**
* @dev Library for managing an enumerable variant of Solidity's
* https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`]
* type.
*
* Maps have the following properties:
*
* - Entries are added, removed, and checked for existence in constant time
* (O(1)).
* - Entries are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableMap for EnumerableMap.AddressToUintMap;
*
* // Declare a set state variable
* EnumerableMap.AddressToUintMap private myMap;
* }
* ```
*
* As of v3.0.0, only maps of type `address -> uint256` (`AddressToUintMap`) are
* supported.
*/
library EnumerableMap {
using EnumerableSet for EnumerableSet.Bytes32Set;
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// The Map implementation uses private functions, and user-facing
// implementations (such as Uint256ToAddressMap) are just wrappers around
// the underlying Map.
// This means that we can only create new EnumerableMaps for types that fit
// in bytes32.
struct Map {
// Storage of keys
EnumerableSet.Bytes32Set _keys;
mapping(bytes32 => bytes32) _values;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function _set(
Map storage map,
bytes32 key,
bytes32 value
) private returns (bool) {
map._values[key] = value;
return map._keys.add(key);
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function _remove(Map storage map, bytes32 key) private returns (bool) {
delete map._values[key];
return map._keys.remove(key);
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function _contains(Map storage map, bytes32 key) private view returns (bool) {
return map._keys.contains(key);
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._keys.length();
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) {
bytes32 key = map._keys.at(index);
return (key, map._values[key]);
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/
function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) {
bytes32 value = map._values[key];
if (value == bytes32(0)) {
return (_contains(map, key), bytes32(0));
} else {
return (true, value);
}
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
bytes32 value = map._values[key];
require(value != 0 || _contains(map, key), "EnumerableMap: nonexistent key");
return value;
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {_tryGet}.
*/
function _get(
Map storage map,
bytes32 key,
string memory errorMessage
) private view returns (bytes32) {
bytes32 value = map._values[key];
require(value != 0 || _contains(map, key), errorMessage);
return value;
}
// AddressToUintMap
struct AddressToUintMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(
AddressToUintMap storage map,
address key,
uint256 value
) internal returns (bool) {
return _set(map._inner, bytes32(uint256(uint160(key))), bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(AddressToUintMap storage map, address key) internal returns (bool) {
return _remove(map._inner, bytes32(uint256(uint160(key))));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(AddressToUintMap storage map, address key) internal view returns (bool) {
return _contains(map._inner, bytes32(uint256(uint160(key))));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(AddressToUintMap storage map) internal view returns (uint256) {
return _length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressToUintMap storage map, uint256 index) internal view returns (address, uint256) {
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (address(uint160(uint256(key))), uint256(value));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*
* _Available since v3.4._
*/
function tryGet(AddressToUintMap storage map, address key) internal view returns (bool, uint256) {
(bool success, bytes32 value) = _tryGet(map._inner, bytes32(uint256(uint160(key))));
return (success, uint256(value));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(AddressToUintMap storage map, address key) internal view returns (uint256) {
return uint256(_get(map._inner, bytes32(uint256(uint160(key)))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryGet}.
*/
function get(
AddressToUintMap storage map,
address key,
string memory errorMessage
) internal view returns (uint256) {
return uint256(_get(map._inner, bytes32(uint256(uint160(key))), errorMessage));
}
// UintToAddressMap
struct UintToAddressMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) {
return _remove(map._inner, bytes32(key));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) {
return _contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(UintToAddressMap storage map) internal view returns (uint256) {
return _length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) {
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint256(key), address(uint160(uint256(value))));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*
* _Available since v3.4._
*/
function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) {
(bool success, bytes32 value) = _tryGet(map._inner, bytes32(key));
return (success, address(uint160(uint256(value))));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(UintToAddressMap storage map, uint256 key) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key)))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryGet}.
*/
function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage))));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../access/Ownable.sol";
import "../Address.sol";
/**
* @title Escrow
* @dev Base escrow contract, holds funds designated for a payee until they
* withdraw them.
*
* Intended usage: This contract (and derived escrow contracts) should be a
* standalone contract, that only interacts with the contract that instantiated
* it. That way, it is guaranteed that all Ether will be handled according to
* the `Escrow` rules, and there is no need to check for payable functions or
* transfers in the inheritance tree. The contract that uses the escrow as its
* payment method should be its owner, and provide public methods redirecting
* to the escrow's deposit and withdraw.
*/
contract Escrow is Ownable {
using Address for address payable;
event Deposited(address indexed payee, uint256 weiAmount);
event Withdrawn(address indexed payee, uint256 weiAmount);
mapping(address => uint256) private _deposits;
function depositsOf(address payee) public view returns (uint256) {
return _deposits[payee];
}
/**
* @dev Stores the sent amount as credit to be withdrawn.
* @param payee The destination address of the funds.
*/
function deposit(address payee) public payable virtual onlyOwner {
uint256 amount = msg.value;
_deposits[payee] = _deposits[payee] + amount;
emit Deposited(payee, amount);
}
/**
* @dev Withdraw accumulated balance for a payee, forwarding all gas to the
* recipient.
*
* WARNING: Forwarding all gas opens the door to reentrancy vulnerabilities.
* Make sure you trust the recipient, or are either following the
* checks-effects-interactions pattern or using {ReentrancyGuard}.
*
* @param payee The address whose funds will be withdrawn and transferred to.
*/
function withdraw(address payable payee) public virtual onlyOwner {
uint256 payment = _deposits[payee];
_deposits[payee] = 0;
payee.sendValue(payment);
emit Withdrawn(payee, payment);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
import "../utils/Strings.sol";
import "../utils/introspection/ERC165.sol";
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
function hasRole(bytes32 role, address account) external view returns (bool);
function getRoleAdmin(bytes32 role) external view returns (bytes32);
function grantRole(bytes32 role, address account) external;
function revokeRole(bytes32 role, address account) external;
function renounceRole(bytes32 role, address account) external;
}
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping (address => bool) members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId
|| super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if(!hasRole(role, account)) {
revert(string(abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(uint160(account), 20),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)));
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, getRoleAdmin(role), adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
|
External function to reject a particular offer and return the ether _tokenId Id of the token to reject offer of _buyer Address of the buyer to reject offer of/ only owner or gallery can reject an offer
|
function rejectOffer(uint256 _tokenId, address _buyer) external {
require(tokenIdToSale[_tokenId].seller == msg.sender || tokenIdToSale[_tokenId].gallery == msg.sender);
_cancelOffer(_tokenId, _buyer);
}
| 60,879 |
pragma solidity ^0.5.0;
pragma experimental ABIEncoderV2;
import "../node_modules/iexec-solidity/contracts/ERC725_IdentityProxy/IERC725.sol";
import "../node_modules/iexec-solidity/contracts/ERC1154_OracleInterface/IERC1154.sol";
import "../node_modules/iexec-solidity/contracts/Libs/SafeMath.sol";
import "../node_modules/iexec-solidity/contracts/Libs/ECDSA.sol";
import "./libs/IexecODBLibCore.sol";
import "./libs/IexecODBLibOrders.sol";
import "./registries/RegistryBase.sol";
import "./CategoryManager.sol";
import "./IexecClerk.sol";
contract IexecHub is CategoryManager, IOracle, ECDSA
{
using SafeMath for uint256;
using IexecODBLibOrders for *;
/***************************************************************************
* Constants *
***************************************************************************/
uint256 public constant CONTRIBUTION_DEADLINE_RATIO = 7;
uint256 public constant REVEAL_DEADLINE_RATIO = 2;
uint256 public constant FINAL_DEADLINE_RATIO = 10;
/***************************************************************************
* Other contracts *
***************************************************************************/
IexecClerk public iexecclerk;
RegistryBase public appregistry;
RegistryBase public datasetregistry;
RegistryBase public workerpoolregistry;
/***************************************************************************
* Consensuses & Workers *
***************************************************************************/
mapping(bytes32 => IexecODBLibCore.Task ) m_tasks;
mapping(bytes32 => mapping(address => IexecODBLibCore.Contribution)) m_contributions;
mapping(address => uint256 ) m_workerScores;
mapping(bytes32 => mapping(address => uint256 )) m_logweight;
mapping(bytes32 => mapping(bytes32 => uint256 )) m_groupweight;
mapping(bytes32 => uint256 ) m_totalweight;
/***************************************************************************
* Events *
***************************************************************************/
event TaskInitialize(bytes32 indexed taskid, address indexed workerpool);
event TaskContribute(bytes32 indexed taskid, address indexed worker, bytes32 hash);
event TaskConsensus (bytes32 indexed taskid, bytes32 consensus);
event TaskReveal (bytes32 indexed taskid, address indexed worker, bytes32 digest);
event TaskReopen (bytes32 indexed taskid);
event TaskFinalize (bytes32 indexed taskid, bytes results);
event TaskClaimed (bytes32 indexed taskid);
event AccurateContribution(address indexed worker, bytes32 indexed taskid);
event FaultyContribution (address indexed worker, bytes32 indexed taskid);
/***************************************************************************
* Modifiers *
***************************************************************************/
modifier onlyScheduler(bytes32 _taskid)
{
require(msg.sender == iexecclerk.viewDeal(m_tasks[_taskid].dealid).workerpool.owner);
_;
}
/***************************************************************************
* Constructor *
***************************************************************************/
constructor()
public
{
}
function attachContracts(
address _iexecclerkAddress,
address _appregistryAddress,
address _datasetregistryAddress,
address _workerpoolregistryAddress)
external onlyOwner
{
require(address(iexecclerk) == address(0));
iexecclerk = IexecClerk (_iexecclerkAddress );
appregistry = RegistryBase(_appregistryAddress);
datasetregistry = RegistryBase(_datasetregistryAddress);
workerpoolregistry = RegistryBase(_workerpoolregistryAddress);
}
/***************************************************************************
* Accessors *
***************************************************************************/
function viewTask(bytes32 _taskid)
external view returns (IexecODBLibCore.Task memory)
{
return m_tasks[_taskid];
}
function viewContribution(bytes32 _taskid, address _worker)
external view returns (IexecODBLibCore.Contribution memory)
{
return m_contributions[_taskid][_worker];
}
function viewScore(address _worker)
external view returns (uint256)
{
return m_workerScores[_worker];
}
function checkResources(address app, address dataset, address workerpool)
external view returns (bool)
{
require( appregistry.isRegistered(app));
require(dataset == address(0) || datasetregistry.isRegistered(dataset));
require( workerpoolregistry.isRegistered(workerpool));
return true;
}
/***************************************************************************
* EIP 1154 PULL INTERFACE *
***************************************************************************/
function resultFor(bytes32 id)
external view returns (bytes memory)
{
IexecODBLibCore.Task storage task = m_tasks[id];
require(task.status == IexecODBLibCore.TaskStatusEnum.COMPLETED);
return task.results;
}
/***************************************************************************
* Hashing and signature tools *
***************************************************************************/
function checkIdentity(address _identity, address _candidate, uint256 _purpose)
internal view returns (bool valid)
{
return _identity == _candidate || IERC725(_identity).keyHasPurpose(keccak256(abi.encode(_candidate)), _purpose); // Simple address || Identity contract
}
/***************************************************************************
* Consensus methods *
***************************************************************************/
function initialize(bytes32 _dealid, uint256 idx)
public returns (bytes32)
{
IexecODBLibCore.Deal memory deal = iexecclerk.viewDeal(_dealid);
require(idx >= deal.botFirst );
require(idx < deal.botFirst.add(deal.botSize));
bytes32 taskid = keccak256(abi.encodePacked(_dealid, idx));
IexecODBLibCore.Task storage task = m_tasks[taskid];
require(task.status == IexecODBLibCore.TaskStatusEnum.UNSET);
task.status = IexecODBLibCore.TaskStatusEnum.ACTIVE;
task.dealid = _dealid;
task.idx = idx;
task.timeref = m_categories[deal.category].workClockTimeRef;
task.contributionDeadline = task.timeref.mul(CONTRIBUTION_DEADLINE_RATIO).add(deal.startTime);
task.finalDeadline = task.timeref.mul( FINAL_DEADLINE_RATIO).add(deal.startTime);
// setup denominator
m_totalweight[taskid] = 1;
emit TaskInitialize(taskid, iexecclerk.viewDeal(_dealid).workerpool.pointer);
return taskid;
}
// TODO: make external w/ calldata
function contribute(
bytes32 _taskid,
bytes32 _resultHash,
bytes32 _resultSeal,
address _enclaveChallenge,
ECDSA.signature memory _enclaveSign,
ECDSA.signature memory _workerpoolSign)
public
{
IexecODBLibCore.Task storage task = m_tasks[_taskid];
IexecODBLibCore.Contribution storage contribution = m_contributions[_taskid][msg.sender];
IexecODBLibCore.Deal memory deal = iexecclerk.viewDeal(task.dealid);
require(task.status == IexecODBLibCore.TaskStatusEnum.ACTIVE );
require(task.contributionDeadline > now );
require(contribution.status == IexecODBLibCore.ContributionStatusEnum.UNSET);
// Check that the worker + taskid + enclave combo is authorized to contribute (scheduler signature)
require(checkIdentity(
deal.workerpool.owner,
recover(
toEthSignedMessageHash(
keccak256(abi.encodePacked(
msg.sender,
_taskid,
_enclaveChallenge
))
),
_workerpoolSign
),
4
));
// need enclave challenge if tag is set
require(_enclaveChallenge != address(0) || (deal.tag[31] & 0x01 == 0));
// Check enclave signature
require(_enclaveChallenge == address(0) || checkIdentity(
_enclaveChallenge,
recover(
toEthSignedMessageHash(
keccak256(abi.encodePacked(
_resultHash,
_resultSeal
))
),
_enclaveSign
),
4
));
// Update contribution entry
contribution.status = IexecODBLibCore.ContributionStatusEnum.CONTRIBUTED;
contribution.resultHash = _resultHash;
contribution.resultSeal = _resultSeal;
contribution.enclaveChallenge = _enclaveChallenge;
task.contributors.push(msg.sender);
iexecclerk.lockContribution(task.dealid, msg.sender);
emit TaskContribute(_taskid, msg.sender, _resultHash);
// Contribution done → updating and checking concensus
/*************************************************************************
* SCORE POLICY 1/3 *
* *
* see documentation! *
*************************************************************************/
// k = 3
uint256 weight = m_workerScores[msg.sender].div(3).max(3).sub(1);
uint256 group = m_groupweight[_taskid][_resultHash];
uint256 delta = group.max(1).mul(weight).sub(group);
m_logweight [_taskid][msg.sender ] = weight.log();
m_groupweight[_taskid][_resultHash] = m_groupweight[_taskid][_resultHash].add(delta);
m_totalweight[_taskid] = m_totalweight[_taskid].add(delta);
// Check consensus
checkConsensus(_taskid, _resultHash);
}
function checkConsensus(
bytes32 _taskid,
bytes32 _consensus)
private
{
uint256 trust = iexecclerk.viewDeal(m_tasks[_taskid].dealid).trust;
if (m_groupweight[_taskid][_consensus].mul(trust) > m_totalweight[_taskid].mul(trust.sub(1)))
{
// Preliminary checks done in "contribute()"
IexecODBLibCore.Task storage task = m_tasks[_taskid];
uint256 winnerCounter = 0;
for (uint256 i = 0; i < task.contributors.length; ++i)
{
address w = task.contributors[i];
if
(
m_contributions[_taskid][w].resultHash == _consensus
&&
m_contributions[_taskid][w].status == IexecODBLibCore.ContributionStatusEnum.CONTRIBUTED // REJECTED contribution must not be count
)
{
winnerCounter = winnerCounter.add(1);
}
}
// msg.sender is a contributor: no need to check
// require(winnerCounter > 0);
task.status = IexecODBLibCore.TaskStatusEnum.REVEALING;
task.consensusValue = _consensus;
task.revealDeadline = task.timeref.mul(REVEAL_DEADLINE_RATIO).add(now);
task.revealCounter = 0;
task.winnerCounter = winnerCounter;
emit TaskConsensus(_taskid, _consensus);
}
}
function reveal(
bytes32 _taskid,
bytes32 _resultDigest)
external // worker
{
IexecODBLibCore.Task storage task = m_tasks[_taskid];
IexecODBLibCore.Contribution storage contribution = m_contributions[_taskid][msg.sender];
require(task.status == IexecODBLibCore.TaskStatusEnum.REVEALING );
require(task.revealDeadline > now );
require(contribution.status == IexecODBLibCore.ContributionStatusEnum.CONTRIBUTED );
require(contribution.resultHash == task.consensusValue );
require(contribution.resultHash == keccak256(abi.encodePacked( _taskid, _resultDigest)));
require(contribution.resultSeal == keccak256(abi.encodePacked(msg.sender, _taskid, _resultDigest)));
contribution.status = IexecODBLibCore.ContributionStatusEnum.PROVED;
task.revealCounter = task.revealCounter.add(1);
emit TaskReveal(_taskid, msg.sender, _resultDigest);
}
function reopen(
bytes32 _taskid)
external onlyScheduler(_taskid)
{
IexecODBLibCore.Task storage task = m_tasks[_taskid];
require(task.status == IexecODBLibCore.TaskStatusEnum.REVEALING);
require(task.finalDeadline > now );
require(task.revealDeadline <= now
&& task.revealCounter == 0 );
for (uint256 i = 0; i < task.contributors.length; ++i)
{
address worker = task.contributors[i];
if (m_contributions[_taskid][worker].resultHash == task.consensusValue)
{
m_contributions[_taskid][worker].status = IexecODBLibCore.ContributionStatusEnum.REJECTED;
}
}
m_totalweight[_taskid] = m_totalweight[_taskid].sub(m_groupweight[_taskid][task.consensusValue]);
m_groupweight[_taskid][task.consensusValue] = 0;
task.status = IexecODBLibCore.TaskStatusEnum.ACTIVE;
task.consensusValue = 0x0;
task.revealDeadline = 0;
task.winnerCounter = 0;
emit TaskReopen(_taskid);
}
function finalize(
bytes32 _taskid,
bytes calldata _results)
external onlyScheduler(_taskid)
{
IexecODBLibCore.Task storage task = m_tasks[_taskid];
require(task.status == IexecODBLibCore.TaskStatusEnum.REVEALING);
require(task.finalDeadline > now );
require(task.revealCounter == task.winnerCounter
|| (task.revealCounter > 0 && task.revealDeadline <= now) );
task.status = IexecODBLibCore.TaskStatusEnum.COMPLETED;
task.results = _results;
/**
* Stake and reward management
*/
iexecclerk.successWork(task.dealid);
distributeRewards(_taskid);
/**
* Event
*/
emit TaskFinalize(_taskid, _results);
/**
* Callback for smartcontracts using EIP1154
*/
address callbackTarget = iexecclerk.viewDeal(task.dealid).callback;
if (callbackTarget != address(0))
{
/**
* Call does not revert if the target smart contract is incompatible or reverts
*
* ATTENTION!
* This call is dangerous and target smart contract can charge the stack.
* Assume invalid state after the call.
* See: https://solidity.readthedocs.io/en/develop/types.html#members-of-addresses
*
* TODO: gas provided?
*/
require(gasleft() > 100000);
callbackTarget.call.gas(100000)(abi.encodeWithSignature(
"receiveResult(bytes32,bytes)",
_taskid,
_results
));
}
}
function distributeRewards(bytes32 _taskid)
private
{
IexecODBLibCore.Task storage task = m_tasks[_taskid];
IexecODBLibCore.Deal memory deal = iexecclerk.viewDeal(task.dealid);
uint256 i;
address worker;
uint256 totalLogWeight = 0;
uint256 totalReward = iexecclerk.viewDeal(task.dealid).workerpool.price;
for (i = 0; i < task.contributors.length; ++i)
{
worker = task.contributors[i];
if (m_contributions[_taskid][worker].status == IexecODBLibCore.ContributionStatusEnum.PROVED)
{
totalLogWeight = totalLogWeight.add(m_logweight[_taskid][worker]);
}
else // ContributionStatusEnum.REJECT or ContributionStatusEnum.CONTRIBUTED (not revealed)
{
totalReward = totalReward.add(deal.workerStake);
}
}
require(totalLogWeight > 0);
// compute how much is going to the workers
uint256 workersReward = totalReward.percentage(uint256(100).sub(deal.schedulerRewardRatio));
for (i = 0; i < task.contributors.length; ++i)
{
worker = task.contributors[i];
if (m_contributions[_taskid][worker].status == IexecODBLibCore.ContributionStatusEnum.PROVED)
{
uint256 workerReward = workersReward.mulByFraction(m_logweight[_taskid][worker], totalLogWeight);
totalReward = totalReward.sub(workerReward);
iexecclerk.unlockAndRewardForContribution(task.dealid, worker, workerReward);
// Only reward if replication happened
if (task.contributors.length > 1)
{
/*******************************************************************
* SCORE POLICY 2/3 *
* *
* see documentation! *
*******************************************************************/
m_workerScores[worker] = m_workerScores[worker].add(1);
emit AccurateContribution(worker, _taskid);
}
}
else // WorkStatusEnum.POCO_REJECT or ContributionStatusEnum.CONTRIBUTED (not revealed)
{
// No Reward
iexecclerk.seizeContribution(task.dealid, worker);
// Always punish bad contributors
{
/*******************************************************************
* SCORE POLICY 3/3 *
* *
* see documentation! *
*******************************************************************/
// k = 3
m_workerScores[worker] = m_workerScores[worker].mulByFraction(2,3);
emit FaultyContribution(worker, _taskid);
}
}
}
// totalReward now contains the scheduler share
iexecclerk.rewardForScheduling(task.dealid, totalReward);
}
function claim(
bytes32 _taskid)
public
{
IexecODBLibCore.Task storage task = m_tasks[_taskid];
require(task.status == IexecODBLibCore.TaskStatusEnum.ACTIVE
|| task.status == IexecODBLibCore.TaskStatusEnum.REVEALING);
require(task.finalDeadline <= now);
task.status = IexecODBLibCore.TaskStatusEnum.FAILLED;
/**
* Stake management
*/
iexecclerk.failedWork(task.dealid);
for (uint256 i = 0; i < task.contributors.length; ++i)
{
address worker = task.contributors[i];
iexecclerk.unlockContribution(task.dealid, worker);
}
emit TaskClaimed(_taskid);
}
/***************************************************************************
* Array operations *
***************************************************************************/
function initializeArray(
bytes32[] calldata _dealid,
uint256[] calldata _idx)
external returns (bool)
{
require(_dealid.length == _idx.length);
for (uint i = 0; i < _dealid.length; ++i)
{
initialize(_dealid[i], _idx[i]);
}
return true;
}
function claimArray(
bytes32[] calldata _taskid)
external returns (bool)
{
for (uint i = 0; i < _taskid.length; ++i)
{
claim(_taskid[i]);
}
return true;
}
function initializeAndClaimArray(
bytes32[] calldata _dealid,
uint256[] calldata _idx)
external returns (bool)
{
require(_dealid.length == _idx.length);
for (uint i = 0; i < _dealid.length; ++i)
{
claim(initialize(_dealid[i], _idx[i]));
}
return true;
}
}
|
Array operations /
|
function initializeArray(
bytes32[] calldata _dealid,
uint256[] calldata _idx)
external returns (bool)
{
require(_dealid.length == _idx.length);
for (uint i = 0; i < _dealid.length; ++i)
{
initialize(_dealid[i], _idx[i]);
}
return true;
}
| 13,096,224 |
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
abstract contract IDSProxy {
// function execute(bytes memory _code, bytes memory _data)
// public
// payable
// virtual
// returns (address, bytes32);
function execute(address _target, bytes memory _data) public payable virtual returns (bytes32);
function setCache(address _cacheAddr) public payable virtual returns (bool);
function owner() public view virtual returns (address);
}
contract DSMath {
function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x + y) >= x, "");
}
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x - y) <= x, "");
}
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(y == 0 || (z = x * y) / y == x, "");
}
function div(uint256 x, uint256 y) internal pure returns (uint256 z) {
return x / y;
}
function min(uint256 x, uint256 y) internal pure returns (uint256 z) {
return x <= y ? x : y;
}
function max(uint256 x, uint256 y) internal pure returns (uint256 z) {
return x >= y ? x : y;
}
function imin(int256 x, int256 y) internal pure returns (int256 z) {
return x <= y ? x : y;
}
function imax(int256 x, int256 y) internal pure returns (int256 z) {
return x >= y ? x : y;
}
uint256 constant WAD = 10**18;
uint256 constant RAY = 10**27;
function wmul(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = add(mul(x, y), WAD / 2) / WAD;
}
function rmul(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = add(mul(x, y), RAY / 2) / RAY;
}
function wdiv(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = add(mul(x, WAD), y / 2) / y;
}
function rdiv(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = add(mul(x, RAY), y / 2) / y;
}
// This famous algorithm is called "exponentiation by squaring"
// and calculates x^n with x as fixed-point and n as regular unsigned.
//
// It's O(log n), instead of O(n) for naive repeated multiplication.
//
// These facts are why it works:
//
// If n is even, then x^n = (x^2)^(n/2).
// If n is odd, then x^n = x * x^(n-1),
// and applying the equation for even x gives
// x^n = x * (x^2)^((n-1) / 2).
//
// Also, EVM division is flooring and
// floor[(n-1) / 2] = floor[n / 2].
//
function rpow(uint256 x, uint256 n) internal pure returns (uint256 z) {
z = n % 2 != 0 ? x : RAY;
for (n /= 2; n != 0; n /= 2) {
x = rmul(x, x);
if (n % 2 != 0) {
z = rmul(z, x);
}
}
}
}
interface IERC20 {
function totalSupply() external view returns (uint256 supply);
function balanceOf(address _owner) external view returns (uint256 balance);
function transfer(address _to, uint256 _value) external returns (bool success);
function transferFrom(
address _from,
address _to,
uint256 _value
) external returns (bool success);
function approve(address _spender, uint256 _value) external returns (bool success);
function allowance(address _owner, address _spender) external view returns (uint256 remaining);
function decimals() external view returns (uint256 digits);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
abstract contract IWETH {
function allowance(address, address) public virtual returns (uint256);
function balanceOf(address) public virtual returns (uint256);
function approve(address, uint256) public virtual;
function transfer(address, uint256) public virtual returns (bool);
function transferFrom(
address,
address,
uint256
) public virtual returns (bool);
function deposit() public payable virtual;
function withdraw(uint256) public virtual;
}
interface IExchangeV3 {
function sell(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external payable returns (uint);
function buy(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) external payable returns(uint);
function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external view returns (uint);
function getBuyRate(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external view returns (uint);
}
abstract contract IDFSRegistry {
function getAddr(bytes32 _id) public view virtual returns (address);
function addNewContract(
bytes32 _id,
address _contractAddr,
uint256 _waitPeriod
) public virtual;
function startContractChange(bytes32 _id, address _newContractAddr) public virtual;
function approveContractChange(bytes32 _id) public virtual;
function cancelContractChange(bytes32 _id) public virtual;
function changeWaitPeriod(bytes32 _id, uint256 _newWaitPeriod) public virtual;
}
library Address {
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);
}
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");
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
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");
}
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(
address target,
bytes memory data,
uint256 weiValue,
string memory errorMessage
) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{value: weiValue}(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// 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;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
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
* {ERC20-approve}, and its usage is discouraged.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));
_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)
);
}
function _callOptionalReturn(IERC20 token, bytes memory data) private {
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");
}
}
}
contract AdminVault {
address public owner;
address public admin;
constructor() {
owner = msg.sender;
admin = 0x25eFA336886C74eA8E282ac466BdCd0199f85BB9;
}
/// @notice Admin is able to change owner
/// @param _owner Address of new owner
function changeOwner(address _owner) public {
require(admin == msg.sender, "msg.sender not admin");
owner = _owner;
}
/// @notice Admin is able to set new admin
/// @param _admin Address of multisig that becomes new admin
function changeAdmin(address _admin) public {
require(admin == msg.sender, "msg.sender not admin");
admin = _admin;
}
}
/// @title AdminAuth Handles owner/admin priviligies over smart contracts
contract AdminAuth {
using SafeERC20 for IERC20;
AdminVault public adminVault = AdminVault(0xCCf3d848e08b94478Ed8f46fFead3008faF581fD);
modifier onlyOwner() {
require(adminVault.owner() == msg.sender, "msg.sender not owner");
_;
}
modifier onlyAdmin() {
require(adminVault.admin() == msg.sender, "msg.sender not admin");
_;
}
/// @notice withdraw stuck funds
function withdrawStuckFunds(address _token, address _receiver, uint256 _amount) public onlyOwner {
if (_token == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) {
payable(_receiver).transfer(_amount);
} else {
IERC20(_token).safeTransfer(_receiver, _amount);
}
}
/// @notice Destroy the contract
function kill() public onlyAdmin {
selfdestruct(payable(msg.sender));
}
/// @notice Changes the admin vault that is currently used
/// @param _newAdminVault Address of the new Admin Vault contract
function changeAdminVault(address _newAdminVault) public onlyAdmin {
adminVault = AdminVault(_newAdminVault);
}
}
contract ZrxAllowlist is AdminAuth {
mapping(address => bool) public zrxAllowlist;
mapping(address => bool) private nonPayableAddrs;
constructor() {
zrxAllowlist[0x6958F5e95332D93D21af0D7B9Ca85B8212fEE0A5] = true;
zrxAllowlist[0x61935CbDd02287B511119DDb11Aeb42F1593b7Ef] = true;
zrxAllowlist[0xDef1C0ded9bec7F1a1670819833240f027b25EfF] = true;
zrxAllowlist[0x080bf510FCbF18b91105470639e9561022937712] = true;
nonPayableAddrs[0x080bf510FCbF18b91105470639e9561022937712] = true;
}
function setAllowlistAddr(address _zrxAddr, bool _state) public onlyOwner {
zrxAllowlist[_zrxAddr] = _state;
}
function isZrxAddr(address _zrxAddr) public view returns (bool) {
return zrxAllowlist[_zrxAddr];
}
function addNonPayableAddr(address _nonPayableAddr) public onlyOwner {
nonPayableAddrs[_nonPayableAddr] = true;
}
function removeNonPayableAddr(address _nonPayableAddr) public onlyOwner {
nonPayableAddrs[_nonPayableAddr] = false;
}
function isNonPayableAddr(address _addr) public view returns (bool) {
return nonPayableAddrs[_addr];
}
}
contract DFSExchangeData {
// first is empty to keep the legacy order in place
enum ExchangeType { _, OASIS, KYBER, UNISWAP, ZEROX }
enum ExchangeActionType { SELL, BUY }
struct OffchainData {
address wrapper;
address exchangeAddr;
address allowanceTarget;
uint256 price;
uint256 protocolFee;
bytes callData;
}
struct ExchangeData {
address srcAddr;
address destAddr;
uint256 srcAmount;
uint256 destAmount;
uint256 minPrice;
uint256 dfsFeeDivider; // service fee divider
address user; // user to check special fee
address wrapper;
bytes wrapperData;
OffchainData offchainData;
}
function packExchangeData(ExchangeData memory _exData) public pure returns(bytes memory) {
return abi.encode(_exData);
}
function unpackExchangeData(bytes memory _data) public pure returns(ExchangeData memory _exData) {
_exData = abi.decode(_data, (ExchangeData));
}
}
contract Discount {
address public owner;
mapping(address => CustomServiceFee) public serviceFees;
uint256 constant MAX_SERVICE_FEE = 400;
struct CustomServiceFee {
bool active;
uint256 amount;
}
constructor() {
owner = msg.sender;
}
function isCustomFeeSet(address _user) public view returns (bool) {
return serviceFees[_user].active;
}
function getCustomServiceFee(address _user) public view returns (uint256) {
return serviceFees[_user].amount;
}
function setServiceFee(address _user, uint256 _fee) public {
require(msg.sender == owner, "Only owner");
require(_fee >= MAX_SERVICE_FEE || _fee == 0, "Wrong fee value");
serviceFees[_user] = CustomServiceFee({active: true, amount: _fee});
}
function disableServiceFee(address _user) public {
require(msg.sender == owner, "Only owner");
serviceFees[_user] = CustomServiceFee({active: false, amount: 0});
}
}
/// @title Stores the fee recipient address and allows the owner to change it
contract FeeRecipient is AdminAuth {
address public wallet;
constructor(address _newWallet) {
wallet = _newWallet;
}
function getFeeAddr() public view returns (address) {
return wallet;
}
function changeWalletAddr(address _newWallet) public onlyOwner {
wallet = _newWallet;
}
}
contract TokenUtils {
using SafeERC20 for IERC20;
address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // mainnet
address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
function approveToken(address _tokenAddr, address _to, uint _amount) internal {
if (_tokenAddr == ETH_ADDR) return;
if (IERC20(_tokenAddr).allowance(address(this), _to) < _amount) {
IERC20(_tokenAddr).safeApprove(_to, _amount);
}
}
function pullTokens(address _token, address _from, uint256 _amount) internal returns (uint) {
// handle max uint amount
if (_amount == uint(-1)) {
uint allowance = uint (-1);
if (_token == ETH_ADDR) {
allowance = IERC20(_token).allowance(address(this), _from);
}
uint balance = getBalance(_token, _from);
_amount = (balance > allowance) ? allowance : balance;
}
if (_from != address(0) && _from != address(this) && _token != ETH_ADDR && _amount != 0) {
IERC20(_token).safeTransferFrom(_from, address(this), _amount);
}
return _amount;
}
function withdrawTokens(
address _token,
address _to,
uint256 _amount
) internal returns (uint) {
if (_amount == uint(-1)) {
_amount = getBalance(_token, address(this));
}
if (_to != address(0) && _to != address(this) && _amount != 0) {
if (_token != ETH_ADDR) {
IERC20(_token).safeTransfer(_to, _amount);
} else {
payable(_to).transfer(_amount);
}
}
return _amount;
}
function convertAndDepositToWeth(address _tokenAddr, uint _amount) internal returns (address) {
if (_tokenAddr == ETH_ADDR) {
IWETH(WETH_ADDR).deposit{value: _amount}();
return WETH_ADDR;
} else {
return _tokenAddr;
}
}
function withdrawWeth(uint _amount) internal {
IWETH(WETH_ADDR).withdraw(_amount);
}
function getBalance(address _tokenAddr, address _acc) internal view returns (uint) {
if (_tokenAddr == ETH_ADDR) {
return _acc.balance;
} else {
return IERC20(_tokenAddr).balanceOf(_acc);
}
}
function convertToWeth(address _tokenAddr) internal pure returns (address){
return _tokenAddr == ETH_ADDR ? WETH_ADDR : _tokenAddr;
}
function convertToEth(address _tokenAddr) internal pure returns (address){
return _tokenAddr == WETH_ADDR ? ETH_ADDR : _tokenAddr;
}
function getTokenDecimals(address _token) internal view returns (uint256) {
if (_token == ETH_ADDR) return 18;
return IERC20(_token).decimals();
}
}
contract DFSExchangeHelper is TokenUtils {
string public constant ERR_OFFCHAIN_DATA_INVALID = "Offchain data invalid";
using SafeERC20 for IERC20;
function sendLeftover(
address _srcAddr,
address _destAddr,
address payable _to
) internal {
// clean out any eth leftover
withdrawTokens(ETH_ADDR, _to, uint256(-1));
withdrawTokens(_srcAddr, _to, uint256(-1));
withdrawTokens(_destAddr, _to, uint256(-1));
}
function sliceUint(bytes memory bs, uint256 start) internal pure returns (uint256) {
require(bs.length >= start + 32, "slicing out of range");
uint256 x;
assembly {
x := mload(add(bs, add(0x20, start)))
}
return x;
}
function writeUint256(
bytes memory _b,
uint256 _index,
uint256 _input
) internal pure {
if (_b.length < _index + 32) {
revert(ERR_OFFCHAIN_DATA_INVALID);
}
bytes32 input = bytes32(_input);
_index += 32;
// Read the bytes32 from array memory
assembly {
mstore(add(_b, _index), input)
}
}
}
contract SaverExchangeRegistry is AdminAuth {
mapping(address => bool) private wrappers;
constructor() {
wrappers[0x880A845A85F843a5c67DB2061623c6Fc3bB4c511] = true;
wrappers[0x4c9B55f2083629A1F7aDa257ae984E03096eCD25] = true;
wrappers[0x42A9237b872368E1bec4Ca8D26A928D7d39d338C] = true;
}
function addWrapper(address _wrapper) public onlyOwner {
wrappers[_wrapper] = true;
}
function removeWrapper(address _wrapper) public onlyOwner {
wrappers[_wrapper] = false;
}
function isWrapper(address _wrapper) public view returns(bool) {
return wrappers[_wrapper];
}
}
abstract contract IOffchainWrapper is DFSExchangeData {
function takeOrder(
ExchangeData memory _exData,
ExchangeActionType _type
) virtual public payable returns (bool success, uint256);
}
contract DFSExchangeCore is DFSExchangeHelper, DSMath, DFSExchangeData {
using SafeERC20 for IERC20;
string public constant ERR_SLIPPAGE_HIT = "Slippage hit";
string public constant ERR_DEST_AMOUNT_MISSING = "Dest amount missing";
string public constant ERR_WRAPPER_INVALID = "Wrapper invalid";
string public constant ERR_NOT_ZEROX_EXCHANGE = "Zerox exchange invalid";
address public constant DISCOUNT_ADDRESS = 0x1b14E8D511c9A4395425314f849bD737BAF8208F;
address public constant SAVER_EXCHANGE_REGISTRY = 0x25dd3F51e0C3c3Ff164DDC02A8E4D65Bb9cBB12D;
address public constant ZRX_ALLOWLIST_ADDR = 0x4BA1f38427b33B8ab7Bb0490200dAE1F1C36823F;
FeeRecipient public constant feeRecipient =
FeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A);
/// @notice Internal method that preforms a sell on 0x/on-chain
/// @dev Usefull for other DFS contract to integrate for exchanging
/// @param exData Exchange data struct
/// @return (address, uint) Address of the wrapper used and destAmount
function _sell(ExchangeData memory exData) internal returns (address, uint256) {
uint256 amountWithoutFee = exData.srcAmount;
address wrapper = exData.offchainData.wrapper;
address originalSrcAddr = exData.srcAddr;
bool offChainSwapSuccess;
uint256 destBalanceBefore = getBalance(convertToEth(exData.destAddr), address(this));
// Takes DFS exchange fee
exData.srcAmount -= getFee(
exData.srcAmount,
exData.user,
exData.srcAddr,
exData.dfsFeeDivider
);
// converts from ETH -> WETH if needed
exData.srcAddr = convertAndDepositToWeth(exData.srcAddr, exData.srcAmount);
// Try 0x first and then fallback on specific wrapper
if (exData.offchainData.price > 0) {
(offChainSwapSuccess, ) = offChainSwap(exData, ExchangeActionType.SELL);
}
// fallback to desired wrapper if 0x failed
if (!offChainSwapSuccess) {
onChainSwap(exData, ExchangeActionType.SELL);
wrapper = exData.wrapper;
}
// if anything is left in weth, pull it to user as eth
withdrawAllWeth();
uint256 destBalanceAfter = getBalance(convertToEth(exData.destAddr), address(this));
uint256 amountBought = sub(destBalanceAfter, destBalanceBefore);
// check slippage
require(amountBought >= wmul(exData.minPrice, exData.srcAmount), ERR_SLIPPAGE_HIT);
// revert back exData changes to keep it consistent
exData.srcAddr = originalSrcAddr;
exData.srcAmount = amountWithoutFee;
return (wrapper, amountBought);
}
/// @notice Internal method that preforms a buy on 0x/on-chain
/// @dev Usefull for other DFS contract to integrate for exchanging
/// @param exData Exchange data struct
/// @return (address, uint) Address of the wrapper used and srcAmount
function _buy(ExchangeData memory exData) internal returns (address, uint256) {
require(exData.destAmount != 0, ERR_DEST_AMOUNT_MISSING);
uint256 amountWithoutFee = exData.srcAmount;
address wrapper = exData.offchainData.wrapper;
address originalSrcAddr = exData.srcAddr;
uint256 amountSold;
bool offChainSwapSuccess;
uint256 destBalanceBefore = getBalance(convertToEth(exData.destAddr), address(this));
// Takes DFS exchange fee
exData.srcAmount -= getFee(
exData.srcAmount,
exData.user,
exData.srcAddr,
exData.dfsFeeDivider
);
// converts from ETH -> WETH if needed
exData.srcAddr = convertAndDepositToWeth(exData.srcAddr, exData.srcAmount);
// Try 0x first and then fallback on specific wrapper
if (exData.offchainData.price > 0) {
(offChainSwapSuccess, amountSold) = offChainSwap(exData, ExchangeActionType.BUY);
}
// fallback to desired wrapper if 0x failed
if (!offChainSwapSuccess) {
amountSold = onChainSwap(exData, ExchangeActionType.BUY);
wrapper = exData.wrapper;
}
// if anything is left in weth, pull it to user as eth
withdrawAllWeth();
uint256 destBalanceAfter = getBalance(convertToEth(exData.destAddr), address(this));
uint256 amountBought = sub(destBalanceAfter, destBalanceBefore);
// check slippage
require(amountBought >= exData.destAmount, ERR_SLIPPAGE_HIT);
// revert back exData changes to keep it consistent
exData.srcAddr = originalSrcAddr;
exData.srcAmount = amountWithoutFee;
return (wrapper, amountSold);
}
/// @notice Takes order from 0x and returns bool indicating if it is successful
/// @param _exData Exchange data
function offChainSwap(ExchangeData memory _exData, ExchangeActionType _type)
private
returns (bool success, uint256)
{
if (!ZrxAllowlist(ZRX_ALLOWLIST_ADDR).isZrxAddr(_exData.offchainData.exchangeAddr)) {
return (false, 0);
}
if (
!SaverExchangeRegistry(SAVER_EXCHANGE_REGISTRY).isWrapper(_exData.offchainData.wrapper)
) {
return (false, 0);
}
// send src amount
IERC20(_exData.srcAddr).safeTransfer(_exData.offchainData.wrapper, _exData.srcAmount);
return
IOffchainWrapper(_exData.offchainData.wrapper).takeOrder{
value: _exData.offchainData.protocolFee
}(_exData, _type);
}
/// @notice Calls wraper contract for exchage to preform an on-chain swap
/// @param _exData Exchange data struct
/// @param _type Type of action SELL|BUY
/// @return swapedTokens For Sell that the destAmount, for Buy thats the srcAmount
function onChainSwap(ExchangeData memory _exData, ExchangeActionType _type)
internal
returns (uint256 swapedTokens)
{
require(
SaverExchangeRegistry(SAVER_EXCHANGE_REGISTRY).isWrapper(_exData.wrapper),
ERR_WRAPPER_INVALID
);
IERC20(_exData.srcAddr).safeTransfer(_exData.wrapper, _exData.srcAmount);
if (_type == ExchangeActionType.SELL) {
swapedTokens = IExchangeV3(_exData.wrapper).sell(
_exData.srcAddr,
_exData.destAddr,
_exData.srcAmount,
_exData.wrapperData
);
} else {
swapedTokens = IExchangeV3(_exData.wrapper).buy(
_exData.srcAddr,
_exData.destAddr,
_exData.destAmount,
_exData.wrapperData
);
}
}
function withdrawAllWeth() internal {
uint256 wethBalance = getBalance(WETH_ADDR, address(this));
if (wethBalance > 0) {
withdrawWeth(wethBalance);
}
}
/// @notice Takes a feePercentage and sends it to wallet
/// @param _amount Dai amount of the whole trade
/// @param _user Address of the user
/// @param _token Address of the token
/// @param _dfsFeeDivider Dfs fee divider
/// @return feeAmount Amount in Dai owner earned on the fee
function getFee(
uint256 _amount,
address _user,
address _token,
uint256 _dfsFeeDivider
) internal returns (uint256 feeAmount) {
if (_dfsFeeDivider != 0 && Discount(DISCOUNT_ADDRESS).isCustomFeeSet(_user)) {
_dfsFeeDivider = Discount(DISCOUNT_ADDRESS).getCustomServiceFee(_user);
}
if (_dfsFeeDivider == 0) {
feeAmount = 0;
} else {
feeAmount = _amount / _dfsFeeDivider;
// fee can't go over 10% of the whole amount
if (feeAmount > (_amount / 10)) {
feeAmount = _amount / 10;
}
address walletAddr = feeRecipient.getFeeAddr();
withdrawTokens(_token, walletAddr, feeAmount);
}
}
// solhint-disable-next-line no-empty-blocks
receive() external payable {}
}
abstract contract IGasToken is IERC20 {
function free(uint256 value) public virtual returns (bool success);
function freeUpTo(uint256 value) public virtual returns (uint256 freed);
function freeFrom(address from, uint256 value) public virtual returns (bool success);
function freeFromUpTo(address from, uint256 value) public virtual returns (uint256 freed);
}
contract GasBurner {
IGasToken public constant gasToken = IGasToken(0x0000000000b3F879cb30FE243b4Dfee438691c04);
IGasToken public constant chiToken = IGasToken(0x0000000000004946c0e9F43F4Dee607b0eF1fA1c);
modifier burnGas {
uint gasBefore = gasleft();
_;
uint gasSpent = 21000 + gasBefore - gasleft() + 16 * msg.data.length;
uint gasTokenAmount = (gasSpent + 14154) / 41130;
if (gasToken.balanceOf(address(this)) >= gasTokenAmount) {
gasToken.free(gasTokenAmount);
} else if (chiToken.balanceOf(address(this)) >= gasTokenAmount) {
chiToken.free(gasTokenAmount);
}
}
}
contract DefisaverLogger {
event LogEvent(
address indexed contractAddress,
address indexed caller,
string indexed logName,
bytes data
);
// solhint-disable-next-line func-name-mixedcase
function Log(
address _contract,
address _caller,
string memory _logName,
bytes memory _data
) public {
emit LogEvent(_contract, _caller, _logName, _data);
}
}
/// @title Stores all the important DFS addresses and can be changed (timelock)
contract DFSRegistry is AdminAuth {
DefisaverLogger public constant logger = DefisaverLogger(
0x5c55B921f590a89C1Ebe84dF170E655a82b62126
);
string public constant ERR_ENTRY_ALREADY_EXISTS = "Entry id already exists";
string public constant ERR_ENTRY_NON_EXISTENT = "Entry id doesn't exists";
string public constant ERR_ENTRY_NOT_IN_CHANGE = "Entry not in change process";
string public constant ERR_WAIT_PERIOD_SHORTER = "New wait period must be bigger";
string public constant ERR_CHANGE_NOT_READY = "Change not ready yet";
string public constant ERR_EMPTY_PREV_ADDR = "Previous addr is 0";
string public constant ERR_ALREADY_IN_CONTRACT_CHANGE = "Already in contract change";
string public constant ERR_ALREADY_IN_WAIT_PERIOD_CHANGE = "Already in wait period change";
struct Entry {
address contractAddr;
uint256 waitPeriod;
uint256 changeStartTime;
bool inContractChange;
bool inWaitPeriodChange;
bool exists;
}
mapping(bytes32 => Entry) public entries;
mapping(bytes32 => address) public previousAddresses;
mapping(bytes32 => address) public pendingAddresses;
mapping(bytes32 => uint256) public pendingWaitTimes;
/// @notice Given an contract id returns the registred address
/// @dev Id is keccak256 of the contract name
/// @param _id Id of contract
function getAddr(bytes32 _id) public view returns (address) {
return entries[_id].contractAddr;
}
/// @notice Helper function to easily query if id is registred
/// @param _id Id of contract
function isRegistered(bytes32 _id) public view returns (bool) {
return entries[_id].exists;
}
/////////////////////////// OWNER ONLY FUNCTIONS ///////////////////////////
/// @notice Adds a new contract to the registry
/// @param _id Id of contract
/// @param _contractAddr Address of the contract
/// @param _waitPeriod Amount of time to wait before a contract address can be changed
function addNewContract(
bytes32 _id,
address _contractAddr,
uint256 _waitPeriod
) public onlyOwner {
require(!entries[_id].exists, ERR_ENTRY_ALREADY_EXISTS);
entries[_id] = Entry({
contractAddr: _contractAddr,
waitPeriod: _waitPeriod,
changeStartTime: 0,
inContractChange: false,
inWaitPeriodChange: false,
exists: true
});
// Remember tha address so we can revert back to old addr if needed
previousAddresses[_id] = _contractAddr;
logger.Log(
address(this),
msg.sender,
"AddNewContract",
abi.encode(_id, _contractAddr, _waitPeriod)
);
}
/// @notice Revertes to the previous address immediately
/// @dev In case the new version has a fault, a quick way to fallback to the old contract
/// @param _id Id of contract
function revertToPreviousAddress(bytes32 _id) public onlyOwner {
require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT);
require(previousAddresses[_id] != address(0), ERR_EMPTY_PREV_ADDR);
address currentAddr = entries[_id].contractAddr;
entries[_id].contractAddr = previousAddresses[_id];
logger.Log(
address(this),
msg.sender,
"RevertToPreviousAddress",
abi.encode(_id, currentAddr, previousAddresses[_id])
);
}
/// @notice Starts an address change for an existing entry
/// @dev Can override a change that is currently in progress
/// @param _id Id of contract
/// @param _newContractAddr Address of the new contract
function startContractChange(bytes32 _id, address _newContractAddr) public onlyOwner {
require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT);
require(!entries[_id].inWaitPeriodChange, ERR_ALREADY_IN_WAIT_PERIOD_CHANGE);
entries[_id].changeStartTime = block.timestamp; // solhint-disable-line
entries[_id].inContractChange = true;
pendingAddresses[_id] = _newContractAddr;
logger.Log(
address(this),
msg.sender,
"StartContractChange",
abi.encode(_id, entries[_id].contractAddr, _newContractAddr)
);
}
/// @notice Changes new contract address, correct time must have passed
/// @param _id Id of contract
function approveContractChange(bytes32 _id) public onlyOwner {
require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT);
require(entries[_id].inContractChange, ERR_ENTRY_NOT_IN_CHANGE);
require(
block.timestamp >= (entries[_id].changeStartTime + entries[_id].waitPeriod), // solhint-disable-line
ERR_CHANGE_NOT_READY
);
address oldContractAddr = entries[_id].contractAddr;
entries[_id].contractAddr = pendingAddresses[_id];
entries[_id].inContractChange = false;
entries[_id].changeStartTime = 0;
pendingAddresses[_id] = address(0);
previousAddresses[_id] = oldContractAddr;
logger.Log(
address(this),
msg.sender,
"ApproveContractChange",
abi.encode(_id, oldContractAddr, entries[_id].contractAddr)
);
}
/// @notice Cancel pending change
/// @param _id Id of contract
function cancelContractChange(bytes32 _id) public onlyOwner {
require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT);
require(entries[_id].inContractChange, ERR_ENTRY_NOT_IN_CHANGE);
address oldContractAddr = pendingAddresses[_id];
pendingAddresses[_id] = address(0);
entries[_id].inContractChange = false;
entries[_id].changeStartTime = 0;
logger.Log(
address(this),
msg.sender,
"CancelContractChange",
abi.encode(_id, oldContractAddr, entries[_id].contractAddr)
);
}
/// @notice Starts the change for waitPeriod
/// @param _id Id of contract
/// @param _newWaitPeriod New wait time
function startWaitPeriodChange(bytes32 _id, uint256 _newWaitPeriod) public onlyOwner {
require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT);
require(!entries[_id].inContractChange, ERR_ALREADY_IN_CONTRACT_CHANGE);
pendingWaitTimes[_id] = _newWaitPeriod;
entries[_id].changeStartTime = block.timestamp; // solhint-disable-line
entries[_id].inWaitPeriodChange = true;
logger.Log(
address(this),
msg.sender,
"StartWaitPeriodChange",
abi.encode(_id, _newWaitPeriod)
);
}
/// @notice Changes new wait period, correct time must have passed
/// @param _id Id of contract
function approveWaitPeriodChange(bytes32 _id) public onlyOwner {
require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT);
require(entries[_id].inWaitPeriodChange, ERR_ENTRY_NOT_IN_CHANGE);
require(
block.timestamp >= (entries[_id].changeStartTime + entries[_id].waitPeriod), // solhint-disable-line
ERR_CHANGE_NOT_READY
);
uint256 oldWaitTime = entries[_id].waitPeriod;
entries[_id].waitPeriod = pendingWaitTimes[_id];
entries[_id].inWaitPeriodChange = false;
entries[_id].changeStartTime = 0;
pendingWaitTimes[_id] = 0;
logger.Log(
address(this),
msg.sender,
"ApproveWaitPeriodChange",
abi.encode(_id, oldWaitTime, entries[_id].waitPeriod)
);
}
/// @notice Cancel wait period change
/// @param _id Id of contract
function cancelWaitPeriodChange(bytes32 _id) public onlyOwner {
require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT);
require(entries[_id].inWaitPeriodChange, ERR_ENTRY_NOT_IN_CHANGE);
uint256 oldWaitPeriod = pendingWaitTimes[_id];
pendingWaitTimes[_id] = 0;
entries[_id].inWaitPeriodChange = false;
entries[_id].changeStartTime = 0;
logger.Log(
address(this),
msg.sender,
"CancelWaitPeriodChange",
abi.encode(_id, oldWaitPeriod, entries[_id].waitPeriod)
);
}
}
/// @title Implements Action interface and common helpers for pasing inputs
abstract contract ActionBase {
address public constant REGISTRY_ADDR = 0xB0e1682D17A96E8551191c089673346dF7e1D467;
DFSRegistry public constant registry = DFSRegistry(REGISTRY_ADDR);
DefisaverLogger public constant logger = DefisaverLogger(
0x5c55B921f590a89C1Ebe84dF170E655a82b62126
);
string public constant ERR_SUB_INDEX_VALUE = "Wrong sub index value";
string public constant ERR_RETURN_INDEX_VALUE = "Wrong return index value";
/// @dev Subscription params index range [128, 255]
uint8 public constant SUB_MIN_INDEX_VALUE = 128;
uint8 public constant SUB_MAX_INDEX_VALUE = 255;
/// @dev Return params index range [1, 127]
uint8 public constant RETURN_MIN_INDEX_VALUE = 1;
uint8 public constant RETURN_MAX_INDEX_VALUE = 127;
/// @dev If the input value should not be replaced
uint8 public constant NO_PARAM_MAPPING = 0;
/// @dev We need to parse Flash loan actions in a different way
enum ActionType { FL_ACTION, STANDARD_ACTION, CUSTOM_ACTION }
/// @notice Parses inputs and runs the implemented action through a proxy
/// @dev Is called by the TaskExecutor chaining actions together
/// @param _callData Array of input values each value encoded as bytes
/// @param _subData Array of subscribed vales, replaces input values if specified
/// @param _paramMapping Array that specifies how return and subscribed values are mapped in input
/// @param _returnValues Returns values from actions before, which can be injected in inputs
/// @return Returns a bytes32 value through DSProxy, each actions implements what that value is
function executeAction(
bytes[] memory _callData,
bytes[] memory _subData,
uint8[] memory _paramMapping,
bytes32[] memory _returnValues
) public payable virtual returns (bytes32);
/// @notice Parses inputs and runs the single implemented action through a proxy
/// @dev Used to save gas when executing a single action directly
function executeActionDirect(bytes[] memory _callData) public virtual payable;
/// @notice Returns the type of action we are implementing
function actionType() public pure virtual returns (uint8);
//////////////////////////// HELPER METHODS ////////////////////////////
/// @notice Given an uint256 input, injects return/sub values if specified
/// @param _param The original input value
/// @param _mapType Indicated the type of the input in paramMapping
/// @param _subData Array of subscription data we can repacle the input value with
/// @param _returnValues Array of subscription data we can repacle the input value with
function _parseParamUint(
uint _param,
uint8 _mapType,
bytes[] memory _subData,
bytes32[] memory _returnValues
) internal pure returns (uint) {
if (isReplacable(_mapType)) {
if (isReturnInjection(_mapType)) {
_param = uint(_returnValues[getReturnIndex(_mapType)]);
} else {
_param = abi.decode(_subData[getSubIndex(_mapType)], (uint));
}
}
return _param;
}
/// @notice Given an addr input, injects return/sub values if specified
/// @param _param The original input value
/// @param _mapType Indicated the type of the input in paramMapping
/// @param _subData Array of subscription data we can repacle the input value with
/// @param _returnValues Array of subscription data we can repacle the input value with
function _parseParamAddr(
address _param,
uint8 _mapType,
bytes[] memory _subData,
bytes32[] memory _returnValues
) internal pure returns (address) {
if (isReplacable(_mapType)) {
if (isReturnInjection(_mapType)) {
_param = address(bytes20((_returnValues[getReturnIndex(_mapType)])));
} else {
_param = abi.decode(_subData[getSubIndex(_mapType)], (address));
}
}
return _param;
}
/// @notice Given an bytes32 input, injects return/sub values if specified
/// @param _param The original input value
/// @param _mapType Indicated the type of the input in paramMapping
/// @param _subData Array of subscription data we can repacle the input value with
/// @param _returnValues Array of subscription data we can repacle the input value with
function _parseParamABytes32(
bytes32 _param,
uint8 _mapType,
bytes[] memory _subData,
bytes32[] memory _returnValues
) internal pure returns (bytes32) {
if (isReplacable(_mapType)) {
if (isReturnInjection(_mapType)) {
_param = (_returnValues[getReturnIndex(_mapType)]);
} else {
_param = abi.decode(_subData[getSubIndex(_mapType)], (bytes32));
}
}
return _param;
}
/// @notice Checks if the paramMapping value indicated that we need to inject values
/// @param _type Indicated the type of the input
function isReplacable(uint8 _type) internal pure returns (bool) {
return _type != NO_PARAM_MAPPING;
}
/// @notice Checks if the paramMapping value is in the return value range
/// @param _type Indicated the type of the input
function isReturnInjection(uint8 _type) internal pure returns (bool) {
return (_type >= RETURN_MIN_INDEX_VALUE) && (_type <= RETURN_MAX_INDEX_VALUE);
}
/// @notice Transforms the paramMapping value to the index in return array value
/// @param _type Indicated the type of the input
function getReturnIndex(uint8 _type) internal pure returns (uint8) {
require(isReturnInjection(_type), ERR_SUB_INDEX_VALUE);
return (_type - RETURN_MIN_INDEX_VALUE);
}
/// @notice Transforms the paramMapping value to the index in sub array value
/// @param _type Indicated the type of the input
function getSubIndex(uint8 _type) internal pure returns (uint8) {
require(_type >= SUB_MIN_INDEX_VALUE, ERR_RETURN_INDEX_VALUE);
return (_type - SUB_MIN_INDEX_VALUE);
}
}
/// @title A exchange sell action through the dfs exchange
contract DFSBuy is ActionBase, DFSExchangeCore, GasBurner {
uint256 internal constant RECIPIE_FEE = 400;
uint256 internal constant DIRECT_FEE = 800;
/// @inheritdoc ActionBase
function executeAction(
bytes[] memory _callData,
bytes[] memory _subData,
uint8[] memory _paramMapping,
bytes32[] memory _returnValues
) public payable override returns (bytes32) {
(ExchangeData memory exchangeData, address from, address to) = parseInputs(_callData);
exchangeData.srcAddr = _parseParamAddr(
exchangeData.srcAddr,
_paramMapping[0],
_subData,
_returnValues
);
exchangeData.destAddr = _parseParamAddr(
exchangeData.destAddr,
_paramMapping[1],
_subData,
_returnValues
);
exchangeData.destAmount = _parseParamUint(
exchangeData.destAmount,
_paramMapping[2],
_subData,
_returnValues
);
from = _parseParamAddr(from, _paramMapping[3], _subData, _returnValues);
to = _parseParamAddr(to, _paramMapping[4], _subData, _returnValues);
uint256 exchangedAmount = _dfsBuy(exchangeData, from, to, RECIPIE_FEE);
return bytes32(exchangedAmount);
}
/// @inheritdoc ActionBase
function executeActionDirect(bytes[] memory _callData) public payable override burnGas {
(ExchangeData memory exchangeData, address from, address to) = parseInputs(_callData);
_dfsBuy(exchangeData, from, to, DIRECT_FEE);
}
/// @inheritdoc ActionBase
function actionType() public pure override returns (uint8) {
return uint8(ActionType.STANDARD_ACTION);
}
//////////////////////////// ACTION LOGIC ////////////////////////////
function _dfsBuy(
ExchangeData memory exchangeData,
address _from,
address _to,
uint256 _fee
) internal returns (uint256) {
pullTokens(exchangeData.srcAddr, _from, exchangeData.srcAmount);
uint256 balanceBefore =
getBalance(exchangeData.srcAddr, address(this)) - exchangeData.srcAmount;
exchangeData.user = getUserAddress();
exchangeData.dfsFeeDivider = _fee;
(address wrapper, uint256 amountSold) = _buy(exchangeData);
withdrawTokens(exchangeData.destAddr, _to, exchangeData.destAmount);
withdrawTokens(
exchangeData.srcAddr,
_from,
getBalance(exchangeData.srcAddr, address(this)) - balanceBefore
);
logger.Log(
address(this),
msg.sender,
"DfsBuy",
abi.encode(
wrapper,
exchangeData.srcAddr,
exchangeData.destAddr,
amountSold,
exchangeData.destAmount
)
);
return amountSold;
}
function parseInputs(bytes[] memory _callData)
public
pure
returns (
ExchangeData memory exchangeData,
address from,
address to
)
{
exchangeData = unpackExchangeData(_callData[0]);
from = abi.decode(_callData[1], (address));
to = abi.decode(_callData[2], (address));
}
/// @notice Returns the owner of the DSProxy that called the contract
function getUserAddress() internal view returns (address) {
IDSProxy proxy = IDSProxy(payable(address(this)));
return proxy.owner();
}
}
|
Internal method that preforms a sell on 0x/on-chain Usefull for other DFS contract to integrate for exchanging exData Exchange data struct return (address, uint) Address of the wrapper used and destAmount Takes DFS exchange fee converts from ETH -> WETH if needed Try 0x first and then fallback on specific wrapper fallback to desired wrapper if 0x failed
|
function _sell(ExchangeData memory exData) internal returns (address, uint256) {
uint256 amountWithoutFee = exData.srcAmount;
address wrapper = exData.offchainData.wrapper;
address originalSrcAddr = exData.srcAddr;
bool offChainSwapSuccess;
uint256 destBalanceBefore = getBalance(convertToEth(exData.destAddr), address(this));
exData.srcAmount -= getFee(
exData.srcAmount,
exData.user,
exData.srcAddr,
exData.dfsFeeDivider
);
exData.srcAddr = convertAndDepositToWeth(exData.srcAddr, exData.srcAmount);
if (exData.offchainData.price > 0) {
(offChainSwapSuccess, ) = offChainSwap(exData, ExchangeActionType.SELL);
}
if (!offChainSwapSuccess) {
onChainSwap(exData, ExchangeActionType.SELL);
wrapper = exData.wrapper;
}
uint256 destBalanceAfter = getBalance(convertToEth(exData.destAddr), address(this));
uint256 amountBought = sub(destBalanceAfter, destBalanceBefore);
exData.srcAmount = amountWithoutFee;
return (wrapper, amountBought);
}
| 5,823,247 |
pragma solidity ^0.4.16;
contract WEAToken {
using SetLibrary for SetLibrary.Set;
string public name;
string public symbol;
uint8 public decimals = 0;
uint256 public totalSupply;
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
SetLibrary.Set private allOwners;
function amountOfOwners() public view returns (uint256)
{
return allOwners.size();
}
function ownerAtIndex(uint256 _index) public view returns (address)
{
return address(allOwners.values[_index]);
}
function getAllOwners() public view returns (uint256[])
{
return allOwners.values;
}
event Transfer(address indexed from, address indexed to, uint256 value);
event Burn(address indexed from, uint256 value);
function WEAToken() public {
totalSupply = 18000 * 10 ** uint256(decimals);
balanceOf[msg.sender] = totalSupply;
Transfer(0x0, msg.sender, totalSupply);
allOwners.add(msg.sender);
name = "Weaste Coin";
symbol = "WEA";
}
function _transfer(address _from, address _to, uint _value) internal {
require(_to != 0x0);
require(balanceOf[_from] >= _value);
require(balanceOf[_to] + _value > balanceOf[_to]);
uint previousBalances = balanceOf[_from] + balanceOf[_to];
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
Transfer(_from, _to, _value);
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
// Update the owner tracking
if (balanceOf[_from] == 0)
{
allOwners.remove(_from);
}
if (_value > 0)
{
allOwners.add(_to);
}
}
function transfer(address _to, uint256 _value) public {
_transfer(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]);
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value);
balanceOf[msg.sender] -= _value;
totalSupply -= _value;
Burn(msg.sender, _value);
return true;
}
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value);
require(_value <= allowance[_from][msg.sender]);
balanceOf[_from] -= _value;
allowance[_from][msg.sender] -= _value;
totalSupply -= _value;
Burn(_from, _value);
return true;
}
}
/*
* Written by Jesse Busman ([email protected]) on 2017-11-30.
* This software is provided as-is without warranty of any kind, express or implied.
* This software is provided without any limitation to use, copy modify or distribute.
* The user takes sole and complete responsibility for the consequences of this software's use.
* Github repository: https://github.com/JesseBusman/SoliditySet
* Please note that this container does not preserve the order of its contents!
*/
pragma solidity ^0.4.18;
library SetLibrary
{
struct ArrayIndexAndExistsFlag
{
uint256 index;
bool exists;
}
struct Set
{
mapping(uint256 => ArrayIndexAndExistsFlag) valuesMapping;
uint256[] values;
}
function add(Set storage self, uint256 value) public returns (bool added)
{
// If the value is already in the set, we don't need to do anything
if (self.valuesMapping[value].exists == true) return false;
// Remember that the value is in the set, and remember the value's array index
self.valuesMapping[value] = ArrayIndexAndExistsFlag({index: self.values.length, exists: true});
// Add the value to the array of unique values
self.values.push(value);
return true;
}
function contains(Set storage self, uint256 value) public view returns (bool contained)
{
return self.valuesMapping[value].exists;
}
function remove(Set storage self, uint256 value) public returns (bool removed)
{
// If the value is not in the set, we don't need to do anything
if (self.valuesMapping[value].exists == false) return false;
// Remember that the value is not in the set
self.valuesMapping[value].exists = false;
// Now we need to remove the value from the array. To prevent leaking
// storage space, we move the last value in the array into the spot that
// contains the element we're removing.
if (self.valuesMapping[value].index < self.values.length-1)
{
uint256 valueToMove = self.values[self.values.length-1];
uint256 indexToMoveItTo = self.valuesMapping[value].index;
self.values[indexToMoveItTo] = valueToMove;
self.valuesMapping[valueToMove].index = indexToMoveItTo;
}
// Now we remove the last element from the array, because we just duplicated it.
// We don't free the storage allocation of the removed last element,
// because it will most likely be used again by a call to add().
// De-allocating and re-allocating storage space costs more gas than
// just keeping it allocated and unused.
// Uncomment this line to save gas if your use case does not call add() after remove():
// delete self.values[self.values.length-1];
self.values.length--;
// We do free the storage allocation in the mapping, because it is
// less likely that the exact same value will added again.
delete self.valuesMapping[value];
return true;
}
function size(Set storage self) public view returns (uint256 amountOfValues)
{
return self.values.length;
}
// Also accept address and bytes32 types, so the user doesn't have to cast.
function add(Set storage self, address value) public returns (bool added) { return add(self, uint256(value)); }
function add(Set storage self, bytes32 value) public returns (bool added) { return add(self, uint256(value)); }
function contains(Set storage self, address value) public view returns (bool contained) { return contains(self, uint256(value)); }
function contains(Set storage self, bytes32 value) public view returns (bool contained) { return contains(self, uint256(value)); }
function remove(Set storage self, address value) public returns (bool removed) { return remove(self, uint256(value)); }
function remove(Set storage self, bytes32 value) public returns (bool removed) { return remove(self, uint256(value)); }
}
|
Also accept address and bytes32 types, so the user doesn't have to cast.
|
function add(Set storage self, address value) public returns (bool added) { return add(self, uint256(value)); }
| 1,002,988 |
/*
Copyright 2018 Virtual Rehab (http://virtualrehab.co)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.4.24;
import "openzeppelin-solidity/contracts/token/ERC20/StandardToken.sol";
import "openzeppelin-solidity/contracts/token/ERC20/BurnableToken.sol";
import "./CustomPausable.sol";
///@title Virtual Rehab Token (VRH) ERC20 Token Contract
///@author Binod Nirvan, Subramanian Venkatesan (http://virtualrehab.co)
///@notice The Virtual Rehab Token (VRH) has been created as a centralized currency
///to be used within the Virtual Rehab network. Users will be able to purchase and sell
///VRH tokens in exchanges. The token follows the standards of Ethereum ERC20 Standard token.
///Its design follows the widely adopted token implementation standards.
///This allows token holders to easily store and manage their VRH tokens using existing solutions
///including ERC20-compatible Ethereum wallets. The VRH Token is a utility token
///and is core to Virtual Rehab’s end-to-end operations.
///
///VRH utility use cases include:
///1. Order & Download Virtual Rehab programs through the Virtual Rehab Online Portal
///2. Request further analysis, conducted by Virtual Rehab's unique expert system (which leverages Artificial Intelligence), of the executed programs
///3. Receive incentives (VRH rewards) for seeking help and counselling from psychologists, therapists, or medical doctors
///4. Allows users to pay for services received at the Virtual Rehab Therapy Center
contract VRHToken is StandardToken, CustomPausable, BurnableToken {
uint8 public constant decimals = 18;
string public constant name = "VirtualRehab";
string public constant symbol = "VRH";
uint public constant MAX_SUPPLY = 400000000 * (10 ** uint256(decimals));
uint public constant INITIAL_SUPPLY = (400000000 - 1650000 - 2085000 - 60000000) * (10 ** uint256(decimals));
bool public released = false;
uint public ICOEndDate;
mapping(bytes32 => bool) private mintingList;
event Mint(address indexed to, uint256 amount);
event BulkTransferPerformed(address[] _destinations, uint256[] _amounts);
event TokenReleased(bool _state);
event ICOEndDateSet(uint256 _date);
///@notice Checks if the supplied address is able to perform transfers.
///@param _from The address to check against if the transfer is allowed.
modifier canTransfer(address _from) {
if(paused || !released) {
if(!isAdmin(_from)) {
revert();
}
}
_;
}
///@notice Computes keccak256 hash of the supplied value.
///@param _key The string value to compute hash from.
function computeHash(string _key) private pure returns(bytes32){
return keccak256(abi.encodePacked(_key));
}
///@notice Checks if the minting for the supplied key was already performed.
///@param _key The key or category name of minting.
modifier whenNotMinted(string _key) {
if(mintingList[computeHash(_key)]) {
revert();
}
_;
}
constructor() public {
mintTokens(msg.sender, INITIAL_SUPPLY);
}
///@notice This function enables token transfers for everyone.
///Can only be enabled after the end of the ICO.
function releaseTokenForTransfer() public onlyAdmin whenNotPaused {
require(!released);
released = true;
emit TokenReleased(released);
}
///@notice This function disables token transfers for everyone.
function disableTokenTransfers() public onlyAdmin whenNotPaused {
require(released);
released = false;
emit TokenReleased(released);
}
///@notice This function enables the whitelisted application (internal application) to set the ICO end date and can only be used once.
///@param _date The date to set as the ICO end date.
function setICOEndDate(uint _date) public onlyAdmin {
require(ICOEndDate == 0);
require(_date > now);
ICOEndDate = _date;
emit ICOEndDateSet(_date);
}
///@notice Mints the supplied value of the tokens to the destination address.
//Minting cannot be performed any further once the maximum supply is reached.
//This function is private and cannot be used by anyone except for this contract.
///@param _to The address which will receive the minted tokens.
///@param _value The amount of tokens to mint.
function mintTokens(address _to, uint _value) private {
require(_to != address(0));
require(totalSupply_.add(_value) <= MAX_SUPPLY);
balances[_to] = balances[_to].add(_value);
totalSupply_ = totalSupply_.add(_value);
emit Mint(_to, _value);
emit Transfer(address(0), _to, _value);
}
///@notice Mints the tokens only once against the supplied key (category).
///@param _key The key or the category of the allocation to mint the tokens for.
///@param _to The address receiving the minted tokens.
///@param _amount The amount of tokens to mint.
function mintOnce(string _key, address _to, uint256 _amount) private whenNotPaused whenNotMinted(_key) {
_amount = _amount * (10 ** uint256(decimals));
mintTokens(_to, _amount);
mintingList[computeHash(_key)] = true;
}
///@notice Mints the below-mentioned amount of tokens allocated to the Virtual Rehab advisors.
//The tokens are only available to the advisors after 1 year of the ICO end.
function mintTokensForAdvisors() public onlyAdmin {
require(ICOEndDate != 0);
require(now > (ICOEndDate + 365 days));
mintOnce("advisors", msg.sender, 1650000);
}
///@notice Mints the below-mentioned amount of tokens allocated to the Virtual Rehab founders.
//The tokens are only available to the founders after 2 year of the ICO end.
function mintTokensForFounders() public onlyAdmin {
require(ICOEndDate != 0);
require(now > (ICOEndDate + 720 days));
mintOnce("founders", msg.sender, 60000000);
}
///@notice Mints the below-mentioned amount of tokens allocated to Virtual Rehab services.
//The tokens are only available to the services after 1 year of the ICO end.
function mintTokensForServices() public onlyAdmin {
require(ICOEndDate != 0);
require(now > (ICOEndDate + 60 days));
mintOnce("services", msg.sender, 2085000);
}
///@notice Transfers the specified value of VRH tokens to the destination address.
//Transfers can only happen when the tranfer state is enabled.
//Transfer state can only be enabled after the end of the crowdsale.
///@param _to The destination wallet address to transfer funds to.
///@param _value The amount of tokens to send to the destination address.
function transfer(address _to, uint256 _value) public canTransfer(msg.sender) returns (bool) {
require(_to != address(0));
return super.transfer(_to, _value);
}
///@notice Transfers tokens from a specified wallet address.
///@dev This function is overriden to leverage transfer state feature.
///@param _from The address to transfer funds from.
///@param _to The address to transfer funds to.
///@param _value The amount of tokens to transfer.
function transferFrom(address _from, address _to, uint256 _value) canTransfer(_from) public returns (bool) {
require(_to != address(0));
return super.transferFrom(_from, _to, _value);
}
///@notice Approves a wallet address to spend on behalf of the sender.
///@dev This function is overriden to leverage transfer state feature.
///@param _spender The address which is approved to spend on behalf of the sender.
///@param _value The amount of tokens approve to spend.
function approve(address _spender, uint256 _value) public canTransfer(msg.sender) returns (bool) {
require(_spender != address(0));
return super.approve(_spender, _value);
}
///@notice Increases the approval of the spender.
///@dev This function is overriden to leverage transfer state feature.
///@param _spender The address which is approved to spend on behalf of the sender.
///@param _addedValue The added amount of tokens approved to spend.
function increaseApproval(address _spender, uint256 _addedValue) public canTransfer(msg.sender) returns(bool) {
require(_spender != address(0));
return super.increaseApproval(_spender, _addedValue);
}
///@notice Decreases the approval of the spender.
///@dev This function is overriden to leverage transfer state feature.
///@param _spender The address of the spender to decrease the allocation from.
///@param _subtractedValue The amount of tokens to subtract from the approved allocation.
function decreaseApproval(address _spender, uint256 _subtractedValue) public canTransfer(msg.sender) returns (bool) {
require(_spender != address(0));
return super.decreaseApproval(_spender, _subtractedValue);
}
///@notice Returns the sum of supplied values.
///@param _values The collection of values to create the sum from.
function sumOf(uint256[] _values) private pure returns(uint256) {
uint256 total = 0;
for (uint256 i = 0; i < _values.length; i++) {
total = total.add(_values[i]);
}
return total;
}
///@notice Allows only the admins and/or whitelisted applications to perform bulk transfer operation.
///@param _destinations The destination wallet addresses to send funds to.
///@param _amounts The respective amount of fund to send to the specified addresses.
function bulkTransfer(address[] _destinations, uint256[] _amounts) public onlyAdmin {
require(_destinations.length == _amounts.length);
//Saving gas by determining if the sender has enough balance
//to post this transaction.
uint256 requiredBalance = sumOf(_amounts);
require(balances[msg.sender] >= requiredBalance);
for (uint256 i = 0; i < _destinations.length; i++) {
transfer(_destinations[i], _amounts[i]);
}
emit BulkTransferPerformed(_destinations, _amounts);
}
///@notice Burns the coins held by the sender.
///@param _value The amount of coins to burn.
///@dev This function is overriden to leverage Pausable feature.
function burn(uint256 _value) public whenNotPaused {
super.burn(_value);
}
}
|
Decreases the approval of the spender. This function is overriden to leverage transfer state feature. _spender The address of the spender to decrease the allocation from. _subtractedValue The amount of tokens to subtract from the approved allocation.
|
function decreaseApproval(address _spender, uint256 _subtractedValue) public canTransfer(msg.sender) returns (bool) {
require(_spender != address(0));
return super.decreaseApproval(_spender, _subtractedValue);
}
| 5,525,067 |
./full_match/4/0x6Ee1f92c18182A905009405baDbcBac32B125883/sources/src/utils/MixedDecimal.sol
|
multiple a SignedDecimal.signedDecimal by a uint256
|
function mulScalar(SignedDecimal.signedDecimal memory x, uint256 y)
internal
pure
returns (SignedDecimal.signedDecimal memory)
{
require(_INT256_MAX >= y, ERROR_NON_CONVERTIBLE);
SignedDecimal.signedDecimal memory t;
t = x.mulScalar(int256(y));
return t;
}
| 760,606 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "./abstract/AbstractLeveragePortfolio.sol";
import "./interfaces/IReinsurancePool.sol";
import "./interfaces/IBMIStaking.sol";
contract ReinsurancePool is AbstractLeveragePortfolio, IReinsurancePool, OwnableUpgradeable {
using SafeERC20 for ERC20;
IERC20 public bmiToken;
ERC20 public stblToken;
IBMIStaking public bmiStaking;
address public claimVotingAddress;
uint256 public stblDecimals;
address public aaveProtocol;
address public compoundProtocol;
address public yearnProtocol;
event Recovered(address tokenAddress, uint256 tokenAmount);
event STBLWithdrawn(address user, uint256 amount);
event DefiInterestAdded(uint256 interestAmount);
modifier onlyClaimVoting() {
require(claimVotingAddress == _msgSender(), "RP: Caller is not a ClaimVoting contract");
_;
}
modifier onlyDefiProtocols() {
require(
aaveProtocol == _msgSender() ||
compoundProtocol == _msgSender() ||
yearnProtocol == _msgSender(),
"RP: Caller is not a defi protocols contract"
);
_;
}
function __ReinsurancePool_init() external initializer {
__LeveragePortfolio_init();
__Ownable_init();
}
function setDependencies(IContractsRegistry _contractsRegistry)
external
override
onlyInjectorOrZero
{
stblToken = ERC20(_contractsRegistry.getUSDTContract());
bmiStaking = IBMIStaking(_contractsRegistry.getBMIStakingContract());
bmiToken = IERC20(_contractsRegistry.getBMIContract());
capitalPool = ICapitalPool(_contractsRegistry.getCapitalPoolContract());
claimVotingAddress = _contractsRegistry.getClaimVotingContract();
policyBookRegistry = IPolicyBookRegistry(
_contractsRegistry.getPolicyBookRegistryContract()
);
compoundProtocol = _contractsRegistry.getCompoundProtocolContract();
aaveProtocol = _contractsRegistry.getAaveProtocolContract();
yearnProtocol = _contractsRegistry.getYearnProtocolContract();
leveragePortfolioView = ILeveragePortfolioView(
_contractsRegistry.getLeveragePortfolioViewContract()
);
policyBookAdmin = _contractsRegistry.getPolicyBookAdminContract();
stblDecimals = stblToken.decimals();
// _transferOwnership("0xc97773e1df2cc54e51a005dff7cbbb6480ae2767");
}
function withdrawBMITo(address to, uint256 amount) external override onlyClaimVoting {
bmiToken.transfer(to, amount);
}
function withdrawSTBLTo(address to, uint256 amount) external override onlyClaimVoting {
stblToken.safeTransfer(to, DecimalsConverter.convertFrom18(amount, stblDecimals));
emit STBLWithdrawn(to, amount);
}
function recoverERC20(address tokenAddress, uint256 tokenAmount) external {
//fixing bugs of storage break , owner address is gone
require(_msgSender() == address(0xc97773E1Df2cC54e51a005DFF7cBBb6480aE2767),"RP: Not an owner");
IERC20(tokenAddress).transfer(owner(), tokenAmount);
emit Recovered(tokenAddress, tokenAmount);
}
/// @notice add the 20% of premium + portion of 80% of premium where reisnurance pool participate in coverage pools (vStable)
/// @dev access CapitalPool
/// @param premiumAmount uint256 the premium amount which is 20% of premium + portion of 80%
function addPolicyPremium(uint256, uint256 premiumAmount) external override onlyCapitalPool {
totalLiquidity += premiumAmount;
emit PremiumAdded(premiumAmount);
}
/// @notice add the interest amount from defi protocol : access defi protocols
/// @param interestAmount uint256 the interest amount from defi protocols
function addInterestFromDefiProtocols(uint256 interestAmount)
external
override
onlyDefiProtocols
{
uint256 amount = DecimalsConverter.convertTo18(interestAmount, stblDecimals);
totalLiquidity += amount;
capitalPool.addReinsurancePoolHardSTBL(interestAmount);
_reevaluateProvidedLeverageStable(LeveragePortfolio.REINSURANCEPOOL, amount);
emit DefiInterestAdded(amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256`
* (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.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) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.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.7.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.7.0;
import "../../GSN/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.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);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// 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 "../GSN/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 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;
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.7.4;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
/// @notice the intention of this library is to be able to easily convert
/// one amount of tokens with N decimal places
/// to another amount with M decimal places
library DecimalsConverter {
using SafeMath for uint256;
function convert(
uint256 amount,
uint256 baseDecimals,
uint256 destinationDecimals
) internal pure returns (uint256) {
if (baseDecimals > destinationDecimals) {
amount = amount.div(10**(baseDecimals - destinationDecimals));
} else if (baseDecimals < destinationDecimals) {
amount = amount.mul(10**(destinationDecimals - baseDecimals));
}
return amount;
}
function convertTo18(uint256 amount, uint256 baseDecimals) internal pure returns (uint256) {
return convert(amount, baseDecimals, 18);
}
function convertFrom18(uint256 amount, uint256 destinationDecimals)
internal
pure
returns (uint256)
{
return convert(amount, 18, destinationDecimals);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
interface ISTKBMIToken is IERC20Upgradeable {
function mint(address account, uint256 amount) external;
function burn(address account, uint256 amount) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
import "./IPolicyBookFabric.sol";
import "./IClaimingRegistry.sol";
import "./IPolicyBookFacade.sol";
interface IUserLeveragePool {
enum WithdrawalStatus {NONE, PENDING, READY, EXPIRED}
struct WithdrawalInfo {
uint256 withdrawalAmount;
uint256 readyToWithdrawDate;
bool withdrawalAllowed;
}
struct BMIMultiplierFactors {
uint256 poolMultiplier;
uint256 leverageProvided;
uint256 multiplier;
}
/// @notice Returns type of contract this PolicyBook covers, access: ANY
/// @return _type is type of contract
function contractType() external view returns (IPolicyBookFabric.ContractType _type);
function userLiquidity(address account) external view returns (uint256);
function a2_ProtocolConstant() external view returns (uint256);
function EPOCH_DURATION() external view returns (uint256);
function READY_TO_WITHDRAW_PERIOD() external view returns (uint256);
function epochStartTime() external view returns (uint256);
function withdrawalsInfo(address _userAddr)
external
view
returns (
uint256 _withdrawalAmount,
uint256 _readyToWithdrawDate,
bool _withdrawalAllowed
);
function __UserLeveragePool_init(
IPolicyBookFabric.ContractType _contractType,
string calldata _description,
string calldata _projectSymbol
) external;
function getEpoch(uint256 time) external view returns (uint256);
/// @notice get STBL equivalent
function convertBMIXToSTBL(uint256 _amount) external view returns (uint256);
/// @notice get BMIX equivalent
function convertSTBLToBMIX(uint256 _amount) external view returns (uint256);
/// @notice forces an update of RewardsGenerator multiplier
function forceUpdateBMICoverStakingRewardMultiplier() external;
/// @notice function to get precise current cover and liquidity
function getNewCoverAndLiquidity()
external
view
returns (uint256 newTotalCoverTokens, uint256 newTotalLiquidity);
function updateEpochsInfo() external;
function secondsToEndCurrentEpoch() external view returns (uint256);
/// @notice Let user to add liquidity by supplying stable coin, access: ANY
/// @param _liqudityAmount is amount of stable coin tokens to secure
function addLiquidity(uint256 _liqudityAmount) external;
// /// @notice Let eligible contracts add liqiudity for another user by supplying stable coin
// /// @param _liquidityHolderAddr is address of address to assign cover
// /// @param _liqudityAmount is amount of stable coin tokens to secure
// function addLiquidityFor(address _liquidityHolderAddr, uint256 _liqudityAmount) external;
function addLiquidityAndStake(uint256 _liquidityAmount, uint256 _stakeSTBLAmount) external;
function getAvailableBMIXWithdrawableAmount(address _userAddr) external view returns (uint256);
function getWithdrawalStatus(address _userAddr) external view returns (WithdrawalStatus);
function requestWithdrawal(uint256 _tokensToWithdraw) external;
// function requestWithdrawalWithPermit(
// uint256 _tokensToWithdraw,
// uint8 _v,
// bytes32 _r,
// bytes32 _s
// ) external;
function unlockTokens() external;
/// @notice Let user to withdraw deposited liqiudity, access: ANY
function withdrawLiquidity() external;
///@notice for doing defi hard rebalancing, access: CapitalPool
function updateLiquidity(uint256 _newLiquidity) external;
function getAPY() external view returns (uint256);
function whitelisted() external view returns (bool);
function whitelist(bool _whitelisted) external;
/// @notice set max total liquidity for the pool
/// @param _maxCapacities uint256 the max total liquidity
function setMaxCapacities(uint256 _maxCapacities) external;
function setA2_ProtocolConstant(uint256 _a2_ProtocolConstant) external;
/// @notice Getting number stats, access: ANY
/// @return _maxCapacities is a max liquidity of the pool
/// @return _totalSTBLLiquidity is PolicyBook's liquidity
/// @return _totalLeveragedLiquidity is becuase to follow the same function in policy book
/// @return _stakedSTBL is how much stable coin are staked on this PolicyBook
/// @return _annualProfitYields is its APY
/// @return _annualInsuranceCost is becuase to follow the same function in policy book
/// @return _bmiXRatio is multiplied by 10**18. To get STBL representation
function numberStats()
external
view
returns (
uint256 _maxCapacities,
uint256 _totalSTBLLiquidity,
uint256 _totalLeveragedLiquidity,
uint256 _stakedSTBL,
uint256 _annualProfitYields,
uint256 _annualInsuranceCost,
uint256 _bmiXRatio
);
/// @notice Getting info, access: ANY
/// @return _symbol is the symbol of PolicyBook (bmiXCover)
/// @return _insuredContract is an addres of insured contract
/// @return _contractType is becuase to follow the same function in policy book
/// @return _whitelisted is a state of whitelisting
function info()
external
view
returns (
string memory _symbol,
address _insuredContract,
IPolicyBookFabric.ContractType _contractType,
bool _whitelisted
);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
interface IReinsurancePool {
function withdrawBMITo(address to, uint256 amount) external;
function withdrawSTBLTo(address to, uint256 amount) external;
/// @notice add the interest amount from defi protocol : access defi protocols
/// @param intrestAmount uint256 the interest amount from defi protocols
function addInterestFromDefiProtocols(uint256 intrestAmount) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
import "./IPolicyBookFabric.sol";
interface IPolicyBookRegistry {
struct PolicyBookStats {
string symbol;
address insuredContract;
IPolicyBookFabric.ContractType contractType;
uint256 maxCapacity;
uint256 totalSTBLLiquidity;
uint256 totalLeveragedLiquidity;
uint256 stakedSTBL;
uint256 APY;
uint256 annualInsuranceCost;
uint256 bmiXRatio;
bool whitelisted;
}
function policyBooksByInsuredAddress(address insuredContract) external view returns (address);
function policyBookFacades(address facadeAddress) external view returns (address);
/// @notice Adds PolicyBook to registry, access: PolicyFabric
function add(
address insuredContract,
IPolicyBookFabric.ContractType contractType,
address policyBook,
address facadeAddress
) external;
function whitelist(address policyBookAddress, bool whitelisted) external;
/// @notice returns required allowances for the policybooks
function getPoliciesPrices(
address[] calldata policyBooks,
uint256[] calldata epochsNumbers,
uint256[] calldata coversTokens
) external view returns (uint256[] memory _durations, uint256[] memory _allowances);
/// @notice Buys a batch of policies
function buyPolicyBatch(
address[] calldata policyBooks,
uint256[] calldata epochsNumbers,
uint256[] calldata coversTokens
) external;
/// @notice Checks if provided address is a PolicyBook
function isPolicyBook(address policyBook) external view returns (bool);
/// @notice Checks if provided address is a policyBookFacade
function isPolicyBookFacade(address _facadeAddress) external view returns (bool);
/// @notice Checks if provided address is a user leverage pool
function isUserLeveragePool(address policyBookAddress) external view returns (bool);
/// @notice Returns number of registered PolicyBooks with certain contract type
function countByType(IPolicyBookFabric.ContractType contractType)
external
view
returns (uint256);
/// @notice Returns number of registered PolicyBooks, access: ANY
function count() external view returns (uint256);
function countByTypeWhitelisted(IPolicyBookFabric.ContractType contractType)
external
view
returns (uint256);
function countWhitelisted() external view returns (uint256);
/// @notice Listing registered PolicyBooks with certain contract type, access: ANY
/// @return _policyBooksArr is array of registered PolicyBook addresses with certain contract type
function listByType(
IPolicyBookFabric.ContractType contractType,
uint256 offset,
uint256 limit
) external view returns (address[] memory _policyBooksArr);
/// @notice Listing registered PolicyBooks, access: ANY
/// @return _policyBooksArr is array of registered PolicyBook addresses
function list(uint256 offset, uint256 limit)
external
view
returns (address[] memory _policyBooksArr);
function listByTypeWhitelisted(
IPolicyBookFabric.ContractType contractType,
uint256 offset,
uint256 limit
) external view returns (address[] memory _policyBooksArr);
function listWhitelisted(uint256 offset, uint256 limit)
external
view
returns (address[] memory _policyBooksArr);
/// @notice Listing registered PolicyBooks with stats and certain contract type, access: ANY
function listWithStatsByType(
IPolicyBookFabric.ContractType contractType,
uint256 offset,
uint256 limit
) external view returns (address[] memory _policyBooksArr, PolicyBookStats[] memory _stats);
/// @notice Listing registered PolicyBooks with stats, access: ANY
function listWithStats(uint256 offset, uint256 limit)
external
view
returns (address[] memory _policyBooksArr, PolicyBookStats[] memory _stats);
function listWithStatsByTypeWhitelisted(
IPolicyBookFabric.ContractType contractType,
uint256 offset,
uint256 limit
) external view returns (address[] memory _policyBooksArr, PolicyBookStats[] memory _stats);
function listWithStatsWhitelisted(uint256 offset, uint256 limit)
external
view
returns (address[] memory _policyBooksArr, PolicyBookStats[] memory _stats);
/// @notice Getting stats from policy books, access: ANY
/// @param policyBooks is list of PolicyBooks addresses
function stats(address[] calldata policyBooks)
external
view
returns (PolicyBookStats[] memory _stats);
/// @notice Return existing Policy Book contract, access: ANY
/// @param insuredContract is contract address to lookup for created IPolicyBook
function policyBookFor(address insuredContract) external view returns (address);
/// @notice Getting stats from policy books, access: ANY
/// @param insuredContracts is list of insuredContracts in registry
function statsByInsuredContracts(address[] calldata insuredContracts)
external
view
returns (PolicyBookStats[] memory _stats);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
import "./IPolicyBook.sol";
import "./ILeveragePortfolio.sol";
interface IPolicyBookFacade {
/// @notice Let user to buy policy by supplying stable coin, access: ANY
/// @param _epochsNumber period policy will cover
/// @param _coverTokens amount paid for the coverage
function buyPolicy(uint256 _epochsNumber, uint256 _coverTokens) external;
/// @param _holder who owns coverage
/// @param _epochsNumber period policy will cover
/// @param _coverTokens amount paid for the coverage
function buyPolicyFor(
address _holder,
uint256 _epochsNumber,
uint256 _coverTokens
) external;
function policyBook() external view returns (IPolicyBook);
function userLiquidity(address account) external view returns (uint256);
/// @notice virtual funds deployed by reinsurance pool
function VUreinsurnacePool() external view returns (uint256);
/// @notice leverage funds deployed by reinsurance pool
function LUreinsurnacePool() external view returns (uint256);
/// @notice leverage funds deployed by user leverage pool
function LUuserLeveragePool(address userLeveragePool) external view returns (uint256);
/// @notice total leverage funds deployed to the pool sum of (VUreinsurnacePool,LUreinsurnacePool,LUuserLeveragePool)
function totalLeveragedLiquidity() external view returns (uint256);
function userleveragedMPL() external view returns (uint256);
function reinsurancePoolMPL() external view returns (uint256);
function rebalancingThreshold() external view returns (uint256);
function safePricingModel() external view returns (bool);
/// @notice policyBookFacade initializer
/// @param pbProxy polciybook address upgreadable cotnract.
function __PolicyBookFacade_init(
address pbProxy,
address liquidityProvider,
uint256 initialDeposit
) external;
/// @param _epochsNumber period policy will cover
/// @param _coverTokens amount paid for the coverage
/// @param _distributor if it was sold buy a whitelisted distributor, it is distributor address to receive fee (commission)
function buyPolicyFromDistributor(
uint256 _epochsNumber,
uint256 _coverTokens,
address _distributor
) external;
/// @param _buyer who is buying the coverage
/// @param _epochsNumber period policy will cover
/// @param _coverTokens amount paid for the coverage
/// @param _distributor if it was sold buy a whitelisted distributor, it is distributor address to receive fee (commission)
function buyPolicyFromDistributorFor(
address _buyer,
uint256 _epochsNumber,
uint256 _coverTokens,
address _distributor
) external;
/// @notice Let user to add liquidity by supplying stable coin, access: ANY
/// @param _liquidityAmount is amount of stable coin tokens to secure
function addLiquidity(uint256 _liquidityAmount) external;
/// @notice Let user to add liquidity by supplying stable coin, access: ANY
/// @param _user the one taht add liquidity
/// @param _liquidityAmount is amount of stable coin tokens to secure
function addLiquidityFromDistributorFor(address _user, uint256 _liquidityAmount) external;
/// @notice Let user to add liquidity by supplying stable coin and stake it,
/// @dev access: ANY
function addLiquidityAndStake(uint256 _liquidityAmount, uint256 _stakeSTBLAmount) external;
/// @notice Let user to withdraw deposited liqiudity, access: ANY
function withdrawLiquidity() external;
/// @notice fetches all the pools data
/// @return uint256 VUreinsurnacePool
/// @return uint256 LUreinsurnacePool
/// @return uint256 LUleveragePool
/// @return uint256 user leverage pool address
function getPoolsData()
external
view
returns (
uint256,
uint256,
uint256,
address
);
/// @notice deploy leverage funds (RP lStable, ULP lStable)
/// @param deployedAmount uint256 the deployed amount to be added or substracted from the total liquidity
/// @param leveragePool whether user leverage or reinsurance leverage
function deployLeverageFundsAfterRebalance(
uint256 deployedAmount,
ILeveragePortfolio.LeveragePortfolio leveragePool
) external;
/// @notice deploy virtual funds (RP vStable)
/// @param deployedAmount uint256 the deployed amount to be added to the liquidity
function deployVirtualFundsAfterRebalance(uint256 deployedAmount) external;
/// @notice set the MPL for the user leverage and the reinsurance leverage
/// @param _userLeverageMPL uint256 value of the user leverage MPL
/// @param _reinsuranceLeverageMPL uint256 value of the reinsurance leverage MPL
function setMPLs(uint256 _userLeverageMPL, uint256 _reinsuranceLeverageMPL) external;
/// @notice sets the rebalancing threshold value
/// @param _newRebalancingThreshold uint256 rebalancing threshhold value
function setRebalancingThreshold(uint256 _newRebalancingThreshold) external;
/// @notice sets the rebalancing threshold value
/// @param _safePricingModel bool is pricing model safe (true) or not (false)
function setSafePricingModel(bool _safePricingModel) external;
/// @notice returns how many BMI tokens needs to approve in order to submit a claim
function getClaimApprovalAmount(address user) external view returns (uint256);
/// @notice upserts a withdraw request
/// @dev prevents adding a request if an already pending or ready request is open.
/// @param _tokensToWithdraw uint256 amount of tokens to withdraw
function requestWithdrawal(uint256 _tokensToWithdraw) external;
function listUserLeveragePools(uint256 offset, uint256 limit)
external
view
returns (address[] memory _userLeveragePools);
function countUserLeveragePools() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
interface IPolicyBookFabric {
enum ContractType {CONTRACT, STABLECOIN, SERVICE, EXCHANGE, VARIOUS}
/// @notice Create new Policy Book contract, access: ANY
/// @param _contract is Contract to create policy book for
/// @param _contractType is Contract to create policy book for
/// @param _description is bmiXCover token desription for this policy book
/// @param _projectSymbol replaces x in bmiXCover token symbol
/// @param _initialDeposit is an amount user deposits on creation (addLiquidity())
/// @return _policyBook is address of created contract
function create(
address _contract,
ContractType _contractType,
string calldata _description,
string calldata _projectSymbol,
uint256 _initialDeposit,
address _shieldMiningToken
) external returns (address);
function createLeveragePools(
ContractType _contractType,
string calldata _description,
string calldata _projectSymbol
) external returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
import "./IPolicyBookFabric.sol";
import "./IClaimingRegistry.sol";
import "./IPolicyBookFacade.sol";
interface IPolicyBook {
enum WithdrawalStatus {NONE, PENDING, READY, EXPIRED}
struct PolicyHolder {
uint256 coverTokens;
uint256 startEpochNumber;
uint256 endEpochNumber;
uint256 paid;
uint256 reinsurancePrice;
}
struct WithdrawalInfo {
uint256 withdrawalAmount;
uint256 readyToWithdrawDate;
bool withdrawalAllowed;
}
struct BuyPolicyParameters {
address buyer;
address holder;
uint256 epochsNumber;
uint256 coverTokens;
uint256 distributorFee;
address distributor;
}
function policyHolders(address _holder)
external
view
returns (
uint256,
uint256,
uint256,
uint256,
uint256
);
function policyBookFacade() external view returns (IPolicyBookFacade);
function setPolicyBookFacade(address _policyBookFacade) external;
function EPOCH_DURATION() external view returns (uint256);
function stblDecimals() external view returns (uint256);
function READY_TO_WITHDRAW_PERIOD() external view returns (uint256);
function whitelisted() external view returns (bool);
function epochStartTime() external view returns (uint256);
// @TODO: should we let DAO to change contract address?
/// @notice Returns address of contract this PolicyBook covers, access: ANY
/// @return _contract is address of covered contract
function insuranceContractAddress() external view returns (address _contract);
/// @notice Returns type of contract this PolicyBook covers, access: ANY
/// @return _type is type of contract
function contractType() external view returns (IPolicyBookFabric.ContractType _type);
function totalLiquidity() external view returns (uint256);
function totalCoverTokens() external view returns (uint256);
// /// @notice return MPL for user leverage pool
// function userleveragedMPL() external view returns (uint256);
// /// @notice return MPL for reinsurance pool
// function reinsurancePoolMPL() external view returns (uint256);
// function bmiRewardMultiplier() external view returns (uint256);
function withdrawalsInfo(address _userAddr)
external
view
returns (
uint256 _withdrawalAmount,
uint256 _readyToWithdrawDate,
bool _withdrawalAllowed
);
function __PolicyBook_init(
address _insuranceContract,
IPolicyBookFabric.ContractType _contractType,
string calldata _description,
string calldata _projectSymbol
) external;
function whitelist(bool _whitelisted) external;
function getEpoch(uint256 time) external view returns (uint256);
/// @notice get STBL equivalent
function convertBMIXToSTBL(uint256 _amount) external view returns (uint256);
/// @notice get BMIX equivalent
function convertSTBLToBMIX(uint256 _amount) external view returns (uint256);
/// @notice submits new claim of the policy book
function submitClaimAndInitializeVoting(string calldata evidenceURI) external;
/// @notice submits new appeal claim of the policy book
function submitAppealAndInitializeVoting(string calldata evidenceURI) external;
/// @notice updates info on claim acceptance
function commitClaim(
address claimer,
uint256 claimAmount,
uint256 claimEndTime,
IClaimingRegistry.ClaimStatus status
) external;
/// @notice forces an update of RewardsGenerator multiplier
function forceUpdateBMICoverStakingRewardMultiplier() external;
/// @notice function to get precise current cover and liquidity
function getNewCoverAndLiquidity()
external
view
returns (uint256 newTotalCoverTokens, uint256 newTotalLiquidity);
/// @notice view function to get precise policy price
/// @param _epochsNumber is number of epochs to cover
/// @param _coverTokens is number of tokens to cover
/// @param _buyer address of the user who buy the policy
/// @return totalSeconds is number of seconds to cover
/// @return totalPrice is the policy price which will pay by the buyer
function getPolicyPrice(
uint256 _epochsNumber,
uint256 _coverTokens,
address _buyer
)
external
view
returns (
uint256 totalSeconds,
uint256 totalPrice,
uint256 pricePercentage
);
/// @notice Let user to buy policy by supplying stable coin, access: ANY
/// @param _buyer who is transferring funds
/// @param _holder who owns coverage
/// @param _epochsNumber period policy will cover
/// @param _coverTokens amount paid for the coverage
/// @param _distributorFee distributor fee (commission). It can't be greater than PROTOCOL_PERCENTAGE
/// @param _distributor if it was sold buy a whitelisted distributor, it is distributor address to receive fee (commission)
function buyPolicy(
address _buyer,
address _holder,
uint256 _epochsNumber,
uint256 _coverTokens,
uint256 _distributorFee,
address _distributor
) external returns (uint256, uint256);
function updateEpochsInfo() external;
function secondsToEndCurrentEpoch() external view returns (uint256);
/// @notice Let eligible contracts add liqiudity for another user by supplying stable coin
/// @param _liquidityHolderAddr is address of address to assign cover
/// @param _liqudityAmount is amount of stable coin tokens to secure
function addLiquidityFor(address _liquidityHolderAddr, uint256 _liqudityAmount) external;
/// @notice Let user to add liquidity by supplying stable coin, access: ANY
/// @param _liquidityBuyerAddr address the one that transfer funds
/// @param _liquidityHolderAddr address the one that owns liquidity
/// @param _liquidityAmount uint256 amount to be added on behalf the sender
/// @param _stakeSTBLAmount uint256 the staked amount if add liq and stake
function addLiquidity(
address _liquidityBuyerAddr,
address _liquidityHolderAddr,
uint256 _liquidityAmount,
uint256 _stakeSTBLAmount
) external returns (uint256);
function getAvailableBMIXWithdrawableAmount(address _userAddr) external view returns (uint256);
function getWithdrawalStatus(address _userAddr) external view returns (WithdrawalStatus);
function requestWithdrawal(uint256 _tokensToWithdraw, address _user) external;
// function requestWithdrawalWithPermit(
// uint256 _tokensToWithdraw,
// uint8 _v,
// bytes32 _r,
// bytes32 _s
// ) external;
function unlockTokens() external;
/// @notice Let user to withdraw deposited liqiudity, access: ANY
function withdrawLiquidity(address sender) external returns (uint256);
///@notice for doing defi hard rebalancing, access: policyBookFacade
function updateLiquidity(uint256 _newLiquidity) external;
function getAPY() external view returns (uint256);
/// @notice Getting user stats, access: ANY
function userStats(address _user) external view returns (PolicyHolder memory);
/// @notice Getting number stats, access: ANY
/// @return _maxCapacities is a max token amount that a user can buy
/// @return _totalSTBLLiquidity is PolicyBook's liquidity
/// @return _totalLeveragedLiquidity is PolicyBook's leveraged liquidity
/// @return _stakedSTBL is how much stable coin are staked on this PolicyBook
/// @return _annualProfitYields is its APY
/// @return _annualInsuranceCost is percentage of cover tokens that is required to be paid for 1 year of insurance
function numberStats()
external
view
returns (
uint256 _maxCapacities,
uint256 _totalSTBLLiquidity,
uint256 _totalLeveragedLiquidity,
uint256 _stakedSTBL,
uint256 _annualProfitYields,
uint256 _annualInsuranceCost,
uint256 _bmiXRatio
);
/// @notice Getting info, access: ANY
/// @return _symbol is the symbol of PolicyBook (bmiXCover)
/// @return _insuredContract is an addres of insured contract
/// @return _contractType is a type of insured contract
/// @return _whitelisted is a state of whitelisting
function info()
external
view
returns (
string memory _symbol,
address _insuredContract,
IPolicyBookFabric.ContractType _contractType,
bool _whitelisted
);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
import "./ILeveragePortfolio.sol";
import "./IUserLeveragePool.sol";
interface ILeveragePortfolioView {
function calcM(uint256 poolUR, address leveragePoolAddress) external view returns (uint256);
function calcMaxLevFunds(ILeveragePortfolio.LevFundsFactors memory factors)
external
view
returns (uint256);
function calcBMIMultiplier(IUserLeveragePool.BMIMultiplierFactors memory factors)
external
view
returns (uint256);
function getPolicyBookFacade(address _policybookAddress)
external
view
returns (IPolicyBookFacade _coveragePool);
function calcNetMPLn(
ILeveragePortfolio.LeveragePortfolio leveragePoolType,
address _policyBookFacade
) external view returns (uint256 _netMPLn);
function calcMaxVirtualFunds(address policyBookAddress)
external
returns (uint256 _amountToDeploy, uint256 _maxAmount);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
interface ILeveragePortfolio {
enum LeveragePortfolio {USERLEVERAGEPOOL, REINSURANCEPOOL}
struct LevFundsFactors {
uint256 netMPL;
uint256 netMPLn;
address policyBookAddr;
}
function targetUR() external view returns (uint256);
function d_ProtocolConstant() external view returns (uint256);
function a_ProtocolConstant() external view returns (uint256);
function max_ProtocolConstant() external view returns (uint256);
/// @notice deploy lStable from user leverage pool or reinsurance pool using 2 formulas: access by policybook.
/// @param leveragePoolType LeveragePortfolio is determine the pool which call the function
function deployLeverageStableToCoveragePools(LeveragePortfolio leveragePoolType)
external
returns (uint256);
/// @notice deploy the vStable from RP in v2 and for next versions it will be from RP and LP : access by policybook.
function deployVirtualStableToCoveragePools() external returns (uint256);
/// @notice set the threshold % for re-evaluation of the lStable provided across all Coverage pools : access by owner
/// @param threshold uint256 is the reevaluatation threshold
function setRebalancingThreshold(uint256 threshold) external;
/// @notice set the protocol constant : access by owner
/// @param _targetUR uint256 target utitlization ration
/// @param _d_ProtocolConstant uint256 D protocol constant
/// @param _a1_ProtocolConstant uint256 A1 protocol constant
/// @param _max_ProtocolConstant uint256 the max % included
function setProtocolConstant(
uint256 _targetUR,
uint256 _d_ProtocolConstant,
uint256 _a1_ProtocolConstant,
uint256 _max_ProtocolConstant
) external;
/// @notice calc M factor by formual M = min( abs((1/ (Tur-UR))*d) /a, max)
/// @param poolUR uint256 utitilization ratio for a coverage pool
/// @return uint256 M facotr
//function calcM(uint256 poolUR) external returns (uint256);
/// @return uint256 the amount of vStable stored in the pool
function totalLiquidity() external view returns (uint256);
/// @notice add the portion of 80% of premium to user leverage pool where the leverage provide lstable : access policybook
/// add the 20% of premium + portion of 80% of premium where reisnurance pool participate in coverage pools (vStable) : access policybook
/// @param epochsNumber uint256 the number of epochs which the policy holder will pay a premium for
/// @param premiumAmount uint256 the premium amount which is a portion of 80% of the premium
function addPolicyPremium(uint256 epochsNumber, uint256 premiumAmount) external;
/// @notice Used to get a list of coverage pools which get leveraged , use with count()
/// @return _coveragePools a list containing policybook addresses
function listleveragedCoveragePools(uint256 offset, uint256 limit)
external
view
returns (address[] memory _coveragePools);
/// @notice get count of coverage pools which get leveraged
function countleveragedCoveragePools() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
interface IContractsRegistry {
function getUniswapRouterContract() external view returns (address);
function getUniswapBMIToETHPairContract() external view returns (address);
function getUniswapBMIToUSDTPairContract() external view returns (address);
function getSushiswapRouterContract() external view returns (address);
function getSushiswapBMIToETHPairContract() external view returns (address);
function getSushiswapBMIToUSDTPairContract() external view returns (address);
function getSushiSwapMasterChefV2Contract() external view returns (address);
function getWETHContract() external view returns (address);
function getUSDTContract() external view returns (address);
function getBMIContract() external view returns (address);
function getPriceFeedContract() external view returns (address);
function getPolicyBookRegistryContract() external view returns (address);
function getPolicyBookFabricContract() external view returns (address);
function getBMICoverStakingContract() external view returns (address);
function getBMICoverStakingViewContract() external view returns (address);
function getLegacyRewardsGeneratorContract() external view returns (address);
function getRewardsGeneratorContract() external view returns (address);
function getBMIUtilityNFTContract() external view returns (address);
function getNFTStakingContract() external view returns (address);
function getLiquidityMiningContract() external view returns (address);
function getClaimingRegistryContract() external view returns (address);
function getPolicyRegistryContract() external view returns (address);
function getLiquidityRegistryContract() external view returns (address);
function getClaimVotingContract() external view returns (address);
function getReinsurancePoolContract() external view returns (address);
function getLeveragePortfolioViewContract() external view returns (address);
function getCapitalPoolContract() external view returns (address);
function getPolicyBookAdminContract() external view returns (address);
function getPolicyQuoteContract() external view returns (address);
function getLegacyBMIStakingContract() external view returns (address);
function getBMIStakingContract() external view returns (address);
function getSTKBMIContract() external view returns (address);
function getVBMIContract() external view returns (address);
function getLegacyLiquidityMiningStakingContract() external view returns (address);
function getLiquidityMiningStakingETHContract() external view returns (address);
function getLiquidityMiningStakingUSDTContract() external view returns (address);
function getReputationSystemContract() external view returns (address);
function getAaveProtocolContract() external view returns (address);
function getAaveLendPoolAddressProvdierContract() external view returns (address);
function getAaveATokenContract() external view returns (address);
function getCompoundProtocolContract() external view returns (address);
function getCompoundCTokenContract() external view returns (address);
function getCompoundComptrollerContract() external view returns (address);
function getYearnProtocolContract() external view returns (address);
function getYearnVaultContract() external view returns (address);
function getYieldGeneratorContract() external view returns (address);
function getShieldMiningContract() external view returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
import "./IPolicyBookFabric.sol";
interface IClaimingRegistry {
enum ClaimStatus {
CAN_CLAIM,
UNCLAIMABLE,
PENDING,
AWAITING_CALCULATION,
REJECTED_CAN_APPEAL,
REJECTED,
ACCEPTED
}
struct ClaimInfo {
address claimer;
address policyBookAddress;
string evidenceURI;
uint256 dateSubmitted;
uint256 dateEnded;
bool appeal;
ClaimStatus status;
uint256 claimAmount;
}
/// @notice returns anonymous voting duration
function anonymousVotingDuration(uint256 index) external view returns (uint256);
/// @notice returns the whole voting duration
function votingDuration(uint256 index) external view returns (uint256);
/// @notice returns how many time should pass before anyone could calculate a claim result
function anyoneCanCalculateClaimResultAfter(uint256 index) external view returns (uint256);
/// @notice returns true if a user can buy new policy of specified PolicyBook
function canBuyNewPolicy(address buyer, address policyBookAddress)
external
view
returns (bool);
/// @notice submits new PolicyBook claim for the user
function submitClaim(
address user,
address policyBookAddress,
string calldata evidenceURI,
uint256 cover,
bool appeal
) external returns (uint256);
/// @notice returns true if the claim with this index exists
function claimExists(uint256 index) external view returns (bool);
/// @notice returns claim submition time
function claimSubmittedTime(uint256 index) external view returns (uint256);
/// @notice returns claim end time or zero in case it is pending
function claimEndTime(uint256 index) external view returns (uint256);
/// @notice returns true if the claim is anonymously votable
function isClaimAnonymouslyVotable(uint256 index) external view returns (bool);
/// @notice returns true if the claim is exposably votable
function isClaimExposablyVotable(uint256 index) external view returns (bool);
/// @notice returns true if claim is anonymously votable or exposably votable
function isClaimVotable(uint256 index) external view returns (bool);
/// @notice returns true if a claim can be calculated by anyone
function canClaimBeCalculatedByAnyone(uint256 index) external view returns (bool);
/// @notice returns true if this claim is pending or awaiting
function isClaimPending(uint256 index) external view returns (bool);
/// @notice returns how many claims the holder has
function countPolicyClaimerClaims(address user) external view returns (uint256);
/// @notice returns how many pending claims are there
function countPendingClaims() external view returns (uint256);
/// @notice returns how many claims are there
function countClaims() external view returns (uint256);
/// @notice returns a claim index of it's claimer and an ordinal number
function claimOfOwnerIndexAt(address claimer, uint256 orderIndex)
external
view
returns (uint256);
/// @notice returns pending claim index by its ordinal index
function pendingClaimIndexAt(uint256 orderIndex) external view returns (uint256);
/// @notice returns claim index by its ordinal index
function claimIndexAt(uint256 orderIndex) external view returns (uint256);
/// @notice returns current active claim index by policybook and claimer
function claimIndex(address claimer, address policyBookAddress)
external
view
returns (uint256);
/// @notice returns true if the claim is appealed
function isClaimAppeal(uint256 index) external view returns (bool);
/// @notice returns current status of a claim
function policyStatus(address claimer, address policyBookAddress)
external
view
returns (ClaimStatus);
/// @notice returns current status of a claim
function claimStatus(uint256 index) external view returns (ClaimStatus);
/// @notice returns the claim owner (claimer)
function claimOwner(uint256 index) external view returns (address);
/// @notice returns the claim PolicyBook
function claimPolicyBook(uint256 index) external view returns (address);
/// @notice returns claim info by its index
function claimInfo(uint256 index) external view returns (ClaimInfo memory _claimInfo);
function getAllPendingClaimsAmount() external view returns (uint256 _totalClaimsAmount);
function getClaimableAmounts(uint256[] memory _claimIndexes) external view returns (uint256);
/// @notice marks the user's claim as Accepted
function acceptClaim(uint256 index) external;
/// @notice marks the user's claim as Rejected
function rejectClaim(uint256 index) external;
/// @notice Update Image Uri in case it contains material that is ilegal
/// or offensive.
/// @dev Only the owner of the PolicyBookAdmin can erase/update evidenceUri.
/// @param _claimIndex Claim Index that is going to be updated
/// @param _newEvidenceURI New evidence uri. It can be blank.
function updateImageUriOfClaim(uint256 _claimIndex, string calldata _newEvidenceURI) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
interface ICapitalPool {
struct PremiumFactors {
uint256 stblAmount;
uint256 premiumDurationInDays;
uint256 premiumPrice;
uint256 lStblDeployedByLP;
uint256 vStblDeployedByRP;
uint256 vStblOfCP;
uint256 premiumPerDeployment;
uint256 participatedlStblDeployedByLP;
address userLeveragePoolAddress;
}
function virtualUsdtAccumulatedBalance() external view returns (uint256);
function liquidityCushionBalance() external view returns (uint256);
/// @notice distributes the policybook premiums into pools (CP, ULP , RP)
/// @dev distributes the balances acording to the established percentages
/// @param _stblAmount amount hardSTBL ingressed into the system
/// @param _epochsNumber uint256 the number of epochs which the policy holder will pay a premium for
/// @param _protocolFee uint256 the amount of protocol fee earned by premium
function addPolicyHoldersHardSTBL(
uint256 _stblAmount,
uint256 _epochsNumber,
uint256 _protocolFee
) external returns (uint256);
/// @notice distributes the hardSTBL from the coverage providers
/// @dev emits PoolBalancedUpdated event
/// @param _stblAmount amount hardSTBL ingressed into the system
function addCoverageProvidersHardSTBL(uint256 _stblAmount) external;
/// @notice distributes the hardSTBL from the leverage providers
/// @dev emits PoolBalancedUpdated event
/// @param _stblAmount amount hardSTBL ingressed into the system
function addLeverageProvidersHardSTBL(uint256 _stblAmount) external;
/// @notice distributes the hardSTBL from the reinsurance pool
/// @dev emits PoolBalancedUpdated event
/// @param _stblAmount amount hardSTBL ingressed into the system
function addReinsurancePoolHardSTBL(uint256 _stblAmount) external;
/// @notice rebalances pools acording to v2 specification and dao enforced policies
/// @dev emits PoolBalancesUpdated
function rebalanceLiquidityCushion() external;
/// @notice Fullfils policybook claims by transfering the balance to claimer
/// @param _claimer, address of the claimer recieving the withdraw
/// @param _stblAmount uint256 amount to be withdrawn
function fundClaim(address _claimer, uint256 _stblAmount) external;
/// @notice Withdraws liquidity from a specific policbybook to the user
/// @param _sender, address of the user beneficiary of the withdraw
/// @param _stblAmount uint256 amount to be withdrawn
/// @param _isLeveragePool bool wether the pool is ULP or CP(policybook)
function withdrawLiquidity(
address _sender,
uint256 _stblAmount,
bool _isLeveragePool
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
import "./tokens/ISTKBMIToken.sol";
interface IBMIStaking {
event StakedBMI(uint256 stakedBMI, uint256 mintedStkBMI, address indexed recipient);
event BMIWithdrawn(uint256 amountBMI, uint256 burnedStkBMI, address indexed recipient);
event UnusedRewardPoolRevoked(address recipient, uint256 amount);
event RewardPoolRevoked(address recipient, uint256 amount);
struct WithdrawalInfo {
uint256 coolDownTimeEnd;
uint256 amountBMIRequested;
}
function stakeWithPermit(
uint256 _amountBMI,
uint8 _v,
bytes32 _r,
bytes32 _s
) external;
function stakeFor(address _user, uint256 _amountBMI) external;
function stake(uint256 _amountBMI) external;
function maturityAt() external view returns (uint256);
function isBMIRewardUnlocked() external view returns (bool);
function whenCanWithdrawBMIReward(address _address) external view returns (uint256);
function unlockTokensToWithdraw(uint256 _amountBMIUnlock) external;
function withdraw() external;
/// @notice Getting withdraw information
/// @return _amountBMIRequested is amount of bmi tokens requested to unlock
/// @return _amountStkBMI is amount of stkBMI that will burn
/// @return _unlockPeriod is its timestamp when user can withdraw
/// returns 0 if it didn't unlocked yet. User has 48hs to withdraw
/// @return _availableFor is the end date if withdraw period has already begun
/// or 0 if it is expired or didn't start
function getWithdrawalInfo(address _userAddr)
external
view
returns (
uint256 _amountBMIRequested,
uint256 _amountStkBMI,
uint256 _unlockPeriod,
uint256 _availableFor
);
function addToPool(uint256 _amount) external;
function stakingReward(uint256 _amount) external view returns (uint256);
function getStakedBMI(address _address) external view returns (uint256);
function getAPY() external view returns (uint256);
function setRewardPerBlock(uint256 _amount) external;
function revokeRewardPool(uint256 _amount) external;
function revokeUnusedRewardPool() external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
import "@openzeppelin/contracts/math/Math.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
import "../libraries/DecimalsConverter.sol";
import "../interfaces/IPolicyBookRegistry.sol";
import "../interfaces/ILeveragePortfolio.sol";
import "../interfaces/IPolicyBookFabric.sol";
import "../interfaces/IPolicyBook.sol";
import "../interfaces/ICapitalPool.sol";
import "../interfaces/ILeveragePortfolioView.sol";
import "./AbstractDependant.sol";
import "../Globals.sol";
abstract contract AbstractLeveragePortfolio is
ILeveragePortfolio,
Initializable,
AbstractDependant
{
using SafeMath for uint256;
using Math for uint256;
using EnumerableSet for EnumerableSet.AddressSet;
ICapitalPool public capitalPool;
IPolicyBookRegistry public policyBookRegistry;
ILeveragePortfolioView public leveragePortfolioView;
address public policyBookAdmin;
address public reinsurancePoolAddress;
uint256 public override targetUR;
uint256 public override d_ProtocolConstant;
uint256 public override a_ProtocolConstant;
uint256 public override max_ProtocolConstant;
uint256 public override totalLiquidity;
uint256 public rebalancingThreshold;
mapping(address => uint256) public poolsLDeployedAmount;
mapping(address => uint256) public poolsVDeployedAmount;
EnumerableSet.AddressSet internal leveragedCoveragePools;
event LeverageStableDeployed(address policyBook, uint256 deployedAmount);
event VirtualStableDeployed(address policyBook, uint256 deployedAmount);
event ProvidedLeverageReevaluated(LeveragePortfolio leveragePool);
event PremiumAdded(uint256 premiumAmount);
modifier onlyPolicyBookFacade() {
require(policyBookRegistry.isPolicyBookFacade(msg.sender), "LP: No access");
_;
}
modifier onlyCapitalPool() {
require(msg.sender == address(capitalPool), "LP: No access");
_;
}
modifier onlyPolicyBookAdmin() {
require(msg.sender == policyBookAdmin, "LP: Not a PBA");
_;
}
function __LeveragePortfolio_init() internal initializer {
a_ProtocolConstant = 100 * PRECISION;
d_ProtocolConstant = 5 * PRECISION;
targetUR = 45 * PRECISION;
max_ProtocolConstant = PERCENTAGE_100;
rebalancingThreshold = DEFAULT_REBALANCING_THRESHOLD;
}
/// @notice deploy lStable from user leverage pool or reinsurance pool using 2 formulas: access by policybook.
/// @param leveragePoolType LeveragePortfolio is determine the pool which call the function
function deployLeverageStableToCoveragePools(LeveragePortfolio leveragePoolType)
external
override
onlyPolicyBookFacade
returns (uint256)
{
return
_deployLeverageStableToCoveragePools(
leveragePoolType,
address((IPolicyBookFacade(msg.sender)).policyBook())
);
}
/// @notice deploy the vStable from RP in v2 and for next versions it will be from RP and LP : access by policybook.
/// @return the amount of vstable to deploy
function deployVirtualStableToCoveragePools()
external
override
onlyPolicyBookFacade
returns (uint256)
{
address policyBookAddr = address((IPolicyBookFacade(msg.sender)).policyBook());
return _deployVirtualStableToCoveragePools(policyBookAddr);
}
/// @notice add the portion of 80% of premium to user leverage pool where the leverage provide lstable : access policybook
/// add the 20% of premium + portion of 80% of premium where reisnurance pool participate in coverage pools (vStable) : access policybook
/// @param epochsNumber uint256 the number of epochs which the policy holder will pay a premium for , zero for RP
/// @param premiumAmount uint256 the premium amount which is a portion of 80% of the premium
function addPolicyPremium(uint256 epochsNumber, uint256 premiumAmount)
external
virtual
override;
/// @notice set the threshold % for re-evaluation of the lStable provided across all Coverage pools
/// @param _threshold uint256 is the reevaluatation threshold
function setRebalancingThreshold(uint256 _threshold) external override onlyPolicyBookAdmin {
rebalancingThreshold = _threshold;
}
/// @notice set the protocol constant
/// @notice set the protocol constant : access by owner
/// @param _targetUR uint256 target utitlization ration
/// @param _d_ProtocolConstant uint256 D protocol constant
/// @param _a1_ProtocolConstant uint256 A1 protocol constant
/// @param _max_ProtocolConstant uint256 the max % included
function setProtocolConstant(
uint256 _targetUR,
uint256 _d_ProtocolConstant,
uint256 _a1_ProtocolConstant,
uint256 _max_ProtocolConstant
) external override onlyPolicyBookAdmin {
targetUR = _targetUR;
d_ProtocolConstant = _d_ProtocolConstant;
a_ProtocolConstant = _a1_ProtocolConstant;
max_ProtocolConstant = _max_ProtocolConstant;
}
/// @notice Used to get a list of coverage pools which get leveraged , use with count()
/// @return _coveragePools a list containing policybook addresses
function listleveragedCoveragePools(uint256 offset, uint256 limit)
external
view
override
returns (address[] memory _coveragePools)
{
uint256 to = (offset.add(limit)).min(leveragedCoveragePools.length()).max(offset);
_coveragePools = new address[](to - offset);
for (uint256 i = offset; i < to; i++) {
_coveragePools[i - offset] = leveragedCoveragePools.at(i);
}
}
/// @notice get count of coverage pools which get leveraged
function countleveragedCoveragePools() external view override returns (uint256) {
return leveragedCoveragePools.length();
}
function _deployVirtualStableToCoveragePools(address policyBookAddress)
internal
returns (uint256 deployedAmount)
{
(uint256 _amountToDeploy, uint256 _maxAmount) =
leveragePortfolioView.calcMaxVirtualFunds(policyBookAddress);
if (_amountToDeploy > _maxAmount) {
deployedAmount = _maxAmount;
} else {
deployedAmount = _amountToDeploy;
}
if (deployedAmount > 0) {
poolsVDeployedAmount[policyBookAddress] = deployedAmount;
leveragedCoveragePools.add(policyBookAddress);
}
emit VirtualStableDeployed(policyBookAddress, deployedAmount);
}
/// @dev using two formulas , if formula 1 get zero then use the formula 2
/// otherwise get the min value of both
/// calculate the net mpl for the other pool RP or LP
function _deployLeverageStableToCoveragePools(
LeveragePortfolio leveragePoolType,
address policyBookAddress
) internal returns (uint256 deployedAmount) {
IPolicyBookFacade _policyBookFacade =
leveragePortfolioView.getPolicyBookFacade(policyBookAddress);
uint256 _netMPL;
uint256 _netMPLn;
if (leveragePoolType == LeveragePortfolio.USERLEVERAGEPOOL) {
_netMPL = totalLiquidity.mul(_policyBookFacade.userleveragedMPL()).div(PERCENTAGE_100);
_netMPLn += ILeveragePortfolio(reinsurancePoolAddress)
.totalLiquidity()
.mul(_policyBookFacade.reinsurancePoolMPL())
.div(PERCENTAGE_100);
} else {
_netMPL = totalLiquidity.mul(_policyBookFacade.reinsurancePoolMPL()).div(
PERCENTAGE_100
);
}
_netMPLn += leveragePortfolioView.calcNetMPLn(
leveragePoolType,
address(_policyBookFacade)
);
deployedAmount = leveragePortfolioView.calcMaxLevFunds(
LevFundsFactors(_netMPL, _netMPLn, policyBookAddress)
);
if (deployedAmount > 0) {
if (deployedAmount >= poolsVDeployedAmount[policyBookAddress]) {
deployedAmount = deployedAmount.sub(poolsVDeployedAmount[policyBookAddress]);
}
leveragedCoveragePools.add(policyBookAddress);
} else {
leveragedCoveragePools.remove(policyBookAddress);
}
poolsLDeployedAmount[policyBookAddress] = deployedAmount.add(
poolsVDeployedAmount[policyBookAddress]
);
emit LeverageStableDeployed(policyBookAddress, deployedAmount);
}
/// @notice reevaluate all pools provided by the leverage stable upon threshold
/// @param leveragePool LeveragePortfolio is determine the pool which call the function
/// @param newAmount the new amount added or subtracted from the pool
function _reevaluateProvidedLeverageStable(LeveragePortfolio leveragePool, uint256 newAmount)
internal
{
uint256 _newAmountPercentage;
if (totalLiquidity > 0) {
_newAmountPercentage = newAmount.mul(PERCENTAGE_100).div(totalLiquidity);
}
if (
(totalLiquidity > 0 && _newAmountPercentage > rebalancingThreshold) ||
totalLiquidity == 0
) {
if (leveragePool == LeveragePortfolio.REINSURANCEPOOL) {
_rebalanceAllPools(leveragePool, false);
}
_rebalanceAllPools(leveragePool, true);
emit ProvidedLeverageReevaluated(leveragePool);
}
}
/// @notice rebalance all pools provided by the leverage stable or virtual stable
/// @param leveragePool LeveragePortfolio is determine the pool which call the function
/// @param _deployLeverage wether deploy leverage or virtual
function _rebalanceAllPools(LeveragePortfolio leveragePool, bool _deployLeverage) internal {
uint256 _coveragePoolCount = policyBookRegistry.count();
address[] memory _policyBooksArr = policyBookRegistry.list(0, _coveragePoolCount);
for (uint256 i = 0; i < _policyBooksArr.length; i++) {
if (policyBookRegistry.isUserLeveragePool(_policyBooksArr[i])) continue;
IPolicyBookFacade _policyBookFacade =
leveragePortfolioView.getPolicyBookFacade(_policyBooksArr[i]);
uint256 deployedAmount;
if (_deployLeverage) {
deployedAmount = _deployLeverageStableToCoveragePools(
leveragePool,
_policyBooksArr[i]
);
_policyBookFacade.deployLeverageFundsAfterRebalance(deployedAmount, leveragePool);
} else {
deployedAmount = _deployVirtualStableToCoveragePools(_policyBooksArr[i]);
_policyBookFacade.deployVirtualFundsAfterRebalance(deployedAmount);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
import "../interfaces/IContractsRegistry.sol";
abstract contract AbstractDependant {
/// @dev keccak256(AbstractDependant.setInjector(address)) - 1
bytes32 private constant _INJECTOR_SLOT =
0xd6b8f2e074594ceb05d47c27386969754b6ad0c15e5eb8f691399cd0be980e76;
modifier onlyInjectorOrZero() {
address _injector = injector();
require(_injector == address(0) || _injector == msg.sender, "Dependant: Not an injector");
_;
}
function setInjector(address _injector) external onlyInjectorOrZero {
bytes32 slot = _INJECTOR_SLOT;
assembly {
sstore(slot, _injector)
}
}
/// @dev has to apply onlyInjectorOrZero() modifier
function setDependencies(IContractsRegistry) external virtual;
function injector() public view returns (address _injector) {
bytes32 slot = _INJECTOR_SLOT;
assembly {
_injector := sload(slot)
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
uint256 constant SECONDS_IN_THE_YEAR = 365 * 24 * 60 * 60; // 365 days * 24 hours * 60 minutes * 60 seconds
uint256 constant DAYS_IN_THE_YEAR = 365;
uint256 constant MAX_INT = type(uint256).max;
uint256 constant DECIMALS18 = 10**18;
uint256 constant PRECISION = 10**25;
uint256 constant PERCENTAGE_100 = 100 * PRECISION;
uint256 constant BLOCKS_PER_DAY = 6450;
uint256 constant BLOCKS_PER_YEAR = BLOCKS_PER_DAY * 365;
uint256 constant APY_TOKENS = DECIMALS18;
uint256 constant PROTOCOL_PERCENTAGE = 20 * PRECISION;
uint256 constant DEFAULT_REBALANCING_THRESHOLD = 10**23;
uint256 constant REBALANCE_DURATION = 1 days;
uint256 constant EPOCH_DAYS_AMOUNT = 7;
|
fixing bugs of storage break , owner address is gone
|
function recoverERC20(address tokenAddress, uint256 tokenAmount) external {
require(_msgSender() == address(0xc97773E1Df2cC54e51a005DFF7cBBb6480aE2767),"RP: Not an owner");
IERC20(tokenAddress).transfer(owner(), tokenAmount);
emit Recovered(tokenAddress, tokenAmount);
}
| 9,949,378 |
pragma solidity ^0.6.6;
import "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol";
import "@chainlink/contracts/src/v0.6/ChainlinkClient.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
contract LandPriceOracle is ChainlinkClient, Ownable {
AggregatorV3Interface internal priceFeedMANAETH;
AggregatorV3Interface internal priceFeedEthUSD;
uint256 public landPriceInMana;
address private oracle;
bytes32 private jobId;
uint256 private fee;
constructor() public {
// On Kovan displaying the USD price instead although chainlink has ETH/MANA
// https://market.link/feeds/a2bd0cee-8150-4298-8290-ae45ea29e88c?network=42
// MainNet - https://market.link/feeds/a572e5a5-6c2a-4f56-80a6-bd976a5de845?network=1 and https://data.chain.link/mana-eth
priceFeedMANAETH = AggregatorV3Interface(
0x1b93D8E109cfeDcBb3Cc74eD761DE286d5771511
);
// Since we can't get the price from chainlink with one feed, we will have to calculate it.
priceFeedEthUSD = AggregatorV3Interface(
0x9326BFA02ADD2366b30bacB125260Af641031331
);
setPublicChainlinkToken();
oracle = 0x2f90A6D021db21e1B2A077c5a37B3C7E75D15b7e;
jobId = 0x3239666139616131336266313436383738386237636334613530306134356238;
fee = 0.1 * 10**18; // 0.1 LINK
}
mapping(address => bool) public oracleWhitelisted;
// List of addresses who can update prices.
modifier oracleWhitelist() {
require(
oracleWhitelisted[msg.sender] == true,
"Reason: No permission to update."
);
_;
}
// Set contracts that are able to make request to update the price
function setOracleWhitelist(address _address) public onlyOwner {
oracleWhitelisted[_address] = true;
}
/**
* Returns the latest ETH price in USD
*/
function getLatestETHPrice() public view returns (uint256) {
(
uint80 roundID,
int256 ETHprice,
uint256 startedAt,
uint256 timeStamp,
uint80 answeredInRound
) = priceFeedEthUSD.latestRoundData();
return uint256(ETHprice);
}
/**
* Returns the latest MANA price in USD
*/
function getLatestManaPrice() public view returns (uint256) {
(
uint80 roundID,
int256 manaPrice,
uint256 startedAt,
uint256 timeStamp,
uint80 answeredInRound
) = priceFeedMANAETH.latestRoundData();
return uint256(manaPrice);
}
// Calculates how much Mana can you get per one ETH
function manaPerEth() public view returns (uint256) {
uint256 ManaPrice = getLatestManaPrice();
uint256 ETHPrice = getLatestETHPrice();
return (ManaPrice * ETHPrice) / 1e8;
}
function landIndexTokenPerEth() public view returns (uint256) {
uint256 lastManaPerEth = manaPerEth();
uint256 lastLandIndexTokenPerEth =
(lastManaPerEth * 1e18) / landPriceInMana;
return lastLandIndexTokenPerEth;
}
function requestLandData()
public
oracleWhitelist
returns (bytes32 requestId)
{
Chainlink.Request memory request =
buildChainlinkRequest(jobId, address(this), this.fulfill.selector);
// Set the URL to perform the GET request on
request.add(
"get",
"https://whispering-beyond-26434.herokuapp.com/decentraland/orders/price-mean/750"
);
request.add("path", "mean");
// Sends the request
return sendChainlinkRequestTo(oracle, request, fee);
}
/**
* Receive the response in the form of uint256
*/
function fulfill(bytes32 _requestId, uint256 _landPriceInMana)
public
recordChainlinkFulfillment(_requestId)
{
landPriceInMana = _landPriceInMana;
}
}
|
Calculates how much Mana can you get per one ETH
|
function manaPerEth() public view returns (uint256) {
uint256 ManaPrice = getLatestManaPrice();
uint256 ETHPrice = getLatestETHPrice();
return (ManaPrice * ETHPrice) / 1e8;
}
| 2,579,054 |
./full_match/43114/0xe0C38b2a8D09aAD53f1C67734B9A95E43d5981c0/sources/FireBirdRouter.sol
|
require(path[0] == WETH, 'Router: INVALID_PATH');
|
function swapExactETHForTokensSupportingFeeOnTransferTokens(
address tokenOut,
uint256 amountOutMin,
address[] calldata path,
uint8[] calldata dexIds,
address to,
uint256 deadline
) external payable virtual override ensure(deadline) {
uint256 amountIn = msg.value;
transferETHTo(amountIn, path[0]);
uint256 balanceBefore = IERC20(tokenOut).balanceOf(to);
_swapSupportingFeeOnTransferTokens(WETH, path, dexIds, to);
require(IERC20(tokenOut).balanceOf(to).sub(balanceBefore) >= amountOutMin, "Router: INSUFFICIENT_OUTPUT_AMOUNT");
}
| 4,630,926 |
// SPDX-License-Identifier: MIT
// @unsupported: ovm
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol";
import { Lib_AddressResolver } from "../../libraries/resolver/Lib_AddressResolver.sol";
import { Lib_MerkleTree } from "../../libraries/utils/Lib_MerkleTree.sol";
/* Interface Imports */
import { iOVM_CanonicalTransactionChain } from
"../../iOVM/chain/iOVM_CanonicalTransactionChain.sol";
import { iOVM_ChainStorageContainer } from "../../iOVM/chain/iOVM_ChainStorageContainer.sol";
/* Contract Imports */
import { OVM_ExecutionManager } from "../execution/OVM_ExecutionManager.sol";
/* External Imports */
import { Math } from "@openzeppelin/contracts/math/Math.sol";
/**
* @title OVM_CanonicalTransactionChain
* @dev The Canonical Transaction Chain (CTC) contract is an append-only log of transactions
* which must be applied to the rollup state. It defines the ordering of rollup transactions by
* writing them to the 'CTC:batches' instance of the Chain Storage Container.
* The CTC also allows any account to 'enqueue' an L2 transaction, which will require that the
* Sequencer will eventually append it to the rollup state.
* If the Sequencer does not include an enqueued transaction within the 'force inclusion period',
* then any account may force it to be included by calling appendQueueBatch().
*
* Compiler used: solc
* Runtime target: EVM
*/
contract OVM_CanonicalTransactionChain is iOVM_CanonicalTransactionChain, Lib_AddressResolver {
/*************
* Constants *
*************/
// L2 tx gas-related
uint256 constant public MIN_ROLLUP_TX_GAS = 100000;
uint256 constant public MAX_ROLLUP_TX_SIZE = 50000;
uint256 constant public L2_GAS_DISCOUNT_DIVISOR = 32;
// Encoding-related (all in bytes)
uint256 constant internal BATCH_CONTEXT_SIZE = 16;
uint256 constant internal BATCH_CONTEXT_LENGTH_POS = 12;
uint256 constant internal BATCH_CONTEXT_START_POS = 15;
uint256 constant internal TX_DATA_HEADER_SIZE = 3;
uint256 constant internal BYTES_TILL_TX_DATA = 65;
/*************
* Variables *
*************/
uint256 public forceInclusionPeriodSeconds;
uint256 public forceInclusionPeriodBlocks;
uint256 public maxTransactionGasLimit;
/***************
* Constructor *
***************/
constructor(
address _libAddressManager,
uint256 _forceInclusionPeriodSeconds,
uint256 _forceInclusionPeriodBlocks,
uint256 _maxTransactionGasLimit
)
Lib_AddressResolver(_libAddressManager)
{
forceInclusionPeriodSeconds = _forceInclusionPeriodSeconds;
forceInclusionPeriodBlocks = _forceInclusionPeriodBlocks;
maxTransactionGasLimit = _maxTransactionGasLimit;
}
/********************
* Public Functions *
********************/
/**
* Accesses the batch storage container.
* @return Reference to the batch storage container.
*/
function batches()
override
public
view
returns (
iOVM_ChainStorageContainer
)
{
return iOVM_ChainStorageContainer(
resolve("OVM_ChainStorageContainer-CTC-batches")
);
}
/**
* Accesses the queue storage container.
* @return Reference to the queue storage container.
*/
function queue()
override
public
view
returns (
iOVM_ChainStorageContainer
)
{
return iOVM_ChainStorageContainer(
resolve("OVM_ChainStorageContainer-CTC-queue")
);
}
/**
* Retrieves the total number of elements submitted.
* @return _totalElements Total submitted elements.
*/
function getTotalElements()
override
public
view
returns (
uint256 _totalElements
)
{
(uint40 totalElements,,,) = _getBatchExtraData();
return uint256(totalElements);
}
/**
* Retrieves the total number of batches submitted.
* @return _totalBatches Total submitted batches.
*/
function getTotalBatches()
override
public
view
returns (
uint256 _totalBatches
)
{
return batches().length();
}
/**
* Returns the index of the next element to be enqueued.
* @return Index for the next queue element.
*/
function getNextQueueIndex()
override
public
view
returns (
uint40
)
{
(,uint40 nextQueueIndex,,) = _getBatchExtraData();
return nextQueueIndex;
}
/**
* Returns the timestamp of the last transaction.
* @return Timestamp for the last transaction.
*/
function getLastTimestamp()
override
public
view
returns (
uint40
)
{
(,,uint40 lastTimestamp,) = _getBatchExtraData();
return lastTimestamp;
}
/**
* Returns the blocknumber of the last transaction.
* @return Blocknumber for the last transaction.
*/
function getLastBlockNumber()
override
public
view
returns (
uint40
)
{
(,,,uint40 lastBlockNumber) = _getBatchExtraData();
return lastBlockNumber;
}
/**
* Gets the queue element at a particular index.
* @param _index Index of the queue element to access.
* @return _element Queue element at the given index.
*/
function getQueueElement(
uint256 _index
)
override
public
view
returns (
Lib_OVMCodec.QueueElement memory _element
)
{
return _getQueueElement(
_index,
queue()
);
}
/**
* Get the number of queue elements which have not yet been included.
* @return Number of pending queue elements.
*/
function getNumPendingQueueElements()
override
public
view
returns (
uint40
)
{
return getQueueLength() - getNextQueueIndex();
}
/**
* Retrieves the length of the queue, including
* both pending and canonical transactions.
* @return Length of the queue.
*/
function getQueueLength()
override
public
view
returns (
uint40
)
{
return _getQueueLength(
queue()
);
}
/**
* Adds a transaction to the queue.
* @param _target Target L2 contract to send the transaction to.
* @param _gasLimit Gas limit for the enqueued L2 transaction.
* @param _data Transaction data.
*/
function enqueue(
address _target,
uint256 _gasLimit,
bytes memory _data
)
override
public
{
require(
_data.length <= MAX_ROLLUP_TX_SIZE,
"Transaction data size exceeds maximum for rollup transaction."
);
require(
_gasLimit <= maxTransactionGasLimit,
"Transaction gas limit exceeds maximum for rollup transaction."
);
require(
_gasLimit >= MIN_ROLLUP_TX_GAS,
"Transaction gas limit too low to enqueue."
);
// We need to consume some amount of L1 gas in order to rate limit transactions going into
// L2. However, L2 is cheaper than L1 so we only need to burn some small proportion of the
// provided L1 gas.
uint256 gasToConsume = _gasLimit/L2_GAS_DISCOUNT_DIVISOR;
uint256 startingGas = gasleft();
// Although this check is not necessary (burn below will run out of gas if not true), it
// gives the user an explicit reason as to why the enqueue attempt failed.
require(
startingGas > gasToConsume,
"Insufficient gas for L2 rate limiting burn."
);
// Here we do some "dumb" work in order to burn gas, although we should probably replace
// this with something like minting gas token later on.
uint256 i;
while(startingGas - gasleft() < gasToConsume) {
i++;
}
bytes32 transactionHash = keccak256(
abi.encode(
msg.sender,
_target,
_gasLimit,
_data
)
);
bytes32 timestampAndBlockNumber;
assembly {
timestampAndBlockNumber := timestamp()
timestampAndBlockNumber := or(timestampAndBlockNumber, shl(40, number()))
}
iOVM_ChainStorageContainer queueRef = queue();
queueRef.push(transactionHash);
queueRef.push(timestampAndBlockNumber);
// The underlying queue data structure stores 2 elements
// per insertion, so to get the real queue length we need
// to divide by 2 and subtract 1.
uint256 queueIndex = queueRef.length() / 2 - 1;
emit TransactionEnqueued(
msg.sender,
_target,
_gasLimit,
_data,
queueIndex,
block.timestamp
);
}
/**
* Appends a given number of queued transactions as a single batch.
* param _numQueuedTransactions Number of transactions to append.
*/
function appendQueueBatch(
uint256 // _numQueuedTransactions
)
override
public
pure
{
// TEMPORARY: Disable `appendQueueBatch` for minnet
revert("appendQueueBatch is currently disabled.");
// solhint-disable max-line-length
// _numQueuedTransactions = Math.min(_numQueuedTransactions, getNumPendingQueueElements());
// require(
// _numQueuedTransactions > 0,
// "Must append more than zero transactions."
// );
// bytes32[] memory leaves = new bytes32[](_numQueuedTransactions);
// uint40 nextQueueIndex = getNextQueueIndex();
// for (uint256 i = 0; i < _numQueuedTransactions; i++) {
// if (msg.sender != resolve("OVM_Sequencer")) {
// Lib_OVMCodec.QueueElement memory el = getQueueElement(nextQueueIndex);
// require(
// el.timestamp + forceInclusionPeriodSeconds < block.timestamp,
// "Queue transactions cannot be submitted during the sequencer inclusion period."
// );
// }
// leaves[i] = _getQueueLeafHash(nextQueueIndex);
// nextQueueIndex++;
// }
// Lib_OVMCodec.QueueElement memory lastElement = getQueueElement(nextQueueIndex - 1);
// _appendBatch(
// Lib_MerkleTree.getMerkleRoot(leaves),
// _numQueuedTransactions,
// _numQueuedTransactions,
// lastElement.timestamp,
// lastElement.blockNumber
// );
// emit QueueBatchAppended(
// nextQueueIndex - _numQueuedTransactions,
// _numQueuedTransactions,
// getTotalElements()
// );
// solhint-enable max-line-length
}
/**
* Allows the sequencer to append a batch of transactions.
* @dev This function uses a custom encoding scheme for efficiency reasons.
* .param _shouldStartAtElement Specific batch we expect to start appending to.
* .param _totalElementsToAppend Total number of batch elements we expect to append.
* .param _contexts Array of batch contexts.
* .param _transactionDataFields Array of raw transaction data.
*/
function appendSequencerBatch()
override
public
{
uint40 shouldStartAtElement;
uint24 totalElementsToAppend;
uint24 numContexts;
assembly {
shouldStartAtElement := shr(216, calldataload(4))
totalElementsToAppend := shr(232, calldataload(9))
numContexts := shr(232, calldataload(12))
}
require(
shouldStartAtElement == getTotalElements(),
"Actual batch start index does not match expected start index."
);
require(
msg.sender == resolve("OVM_Sequencer"),
"Function can only be called by the Sequencer."
);
require(
numContexts > 0,
"Must provide at least one batch context."
);
require(
totalElementsToAppend > 0,
"Must append at least one element."
);
uint40 nextTransactionPtr = uint40(
BATCH_CONTEXT_START_POS + BATCH_CONTEXT_SIZE * numContexts
);
require(
msg.data.length >= nextTransactionPtr,
"Not enough BatchContexts provided."
);
// Take a reference to the queue and its length so we don't have to keep resolving it.
// Length isn't going to change during the course of execution, so it's fine to simply
// resolve this once at the start. Saves gas.
iOVM_ChainStorageContainer queueRef = queue();
uint40 queueLength = _getQueueLength(queueRef);
// Reserve some memory to save gas on hashing later on. This is a relatively safe estimate
// for the average transaction size that will prevent having to resize this chunk of memory
// later on. Saves gas.
bytes memory hashMemory = new bytes((msg.data.length / totalElementsToAppend) * 2);
// Initialize the array of canonical chain leaves that we will append.
bytes32[] memory leaves = new bytes32[](totalElementsToAppend);
// Each leaf index corresponds to a tx, either sequenced or enqueued.
uint32 leafIndex = 0;
// Counter for number of sequencer transactions appended so far.
uint32 numSequencerTransactions = 0;
// We will sequentially append leaves which are pointers to the queue.
// The initial queue index is what is currently in storage.
uint40 nextQueueIndex = getNextQueueIndex();
BatchContext memory curContext;
for (uint32 i = 0; i < numContexts; i++) {
BatchContext memory nextContext = _getBatchContext(i);
if (i == 0) {
// Execute a special check for the first batch.
_validateFirstBatchContext(nextContext);
}
// Execute this check on every single batch, including the first one.
_validateNextBatchContext(
curContext,
nextContext,
nextQueueIndex,
queueRef
);
// Now we can update our current context.
curContext = nextContext;
// Process sequencer transactions first.
for (uint32 j = 0; j < curContext.numSequencedTransactions; j++) {
uint256 txDataLength;
assembly {
txDataLength := shr(232, calldataload(nextTransactionPtr))
}
require(
txDataLength <= MAX_ROLLUP_TX_SIZE,
"Transaction data size exceeds maximum for rollup transaction."
);
leaves[leafIndex] = _getSequencerLeafHash(
curContext,
nextTransactionPtr,
txDataLength,
hashMemory
);
nextTransactionPtr += uint40(TX_DATA_HEADER_SIZE + txDataLength);
numSequencerTransactions++;
leafIndex++;
}
// Now process any subsequent queue transactions.
for (uint32 j = 0; j < curContext.numSubsequentQueueTransactions; j++) {
require(
nextQueueIndex < queueLength,
"Not enough queued transactions to append."
);
leaves[leafIndex] = _getQueueLeafHash(nextQueueIndex);
nextQueueIndex++;
leafIndex++;
}
}
_validateFinalBatchContext(
curContext,
nextQueueIndex,
queueLength,
queueRef
);
require(
msg.data.length == nextTransactionPtr,
"Not all sequencer transactions were processed."
);
require(
leafIndex == totalElementsToAppend,
"Actual transaction index does not match expected total elements to append."
);
// Generate the required metadata that we need to append this batch
uint40 numQueuedTransactions = totalElementsToAppend - numSequencerTransactions;
uint40 blockTimestamp;
uint40 blockNumber;
if (curContext.numSubsequentQueueTransactions == 0) {
// The last element is a sequencer tx, therefore pull timestamp and block number from
// the last context.
blockTimestamp = uint40(curContext.timestamp);
blockNumber = uint40(curContext.blockNumber);
} else {
// The last element is a queue tx, therefore pull timestamp and block number from the
// queue element.
// curContext.numSubsequentQueueTransactions > 0 which means that we've processed at
// least one queue element. We increment nextQueueIndex after processing each queue
// element, so the index of the last element we processed is nextQueueIndex - 1.
Lib_OVMCodec.QueueElement memory lastElement = _getQueueElement(
nextQueueIndex - 1,
queueRef
);
blockTimestamp = lastElement.timestamp;
blockNumber = lastElement.blockNumber;
}
// For efficiency reasons getMerkleRoot modifies the `leaves` argument in place
// while calculating the root hash therefore any arguments passed to it must not
// be used again afterwards
_appendBatch(
Lib_MerkleTree.getMerkleRoot(leaves),
totalElementsToAppend,
numQueuedTransactions,
blockTimestamp,
blockNumber
);
emit SequencerBatchAppended(
nextQueueIndex - numQueuedTransactions,
numQueuedTransactions,
getTotalElements()
);
}
/**
* Verifies whether a transaction is included in the chain.
* @param _transaction Transaction to verify.
* @param _txChainElement Transaction chain element corresponding to the transaction.
* @param _batchHeader Header of the batch the transaction was included in.
* @param _inclusionProof Inclusion proof for the provided transaction chain element.
* @return True if the transaction exists in the CTC, false if not.
*/
function verifyTransaction(
Lib_OVMCodec.Transaction memory _transaction,
Lib_OVMCodec.TransactionChainElement memory _txChainElement,
Lib_OVMCodec.ChainBatchHeader memory _batchHeader,
Lib_OVMCodec.ChainInclusionProof memory _inclusionProof
)
override
public
view
returns (
bool
)
{
if (_txChainElement.isSequenced == true) {
return _verifySequencerTransaction(
_transaction,
_txChainElement,
_batchHeader,
_inclusionProof
);
} else {
return _verifyQueueTransaction(
_transaction,
_txChainElement.queueIndex,
_batchHeader,
_inclusionProof
);
}
}
/**********************
* Internal Functions *
**********************/
/**
* Returns the BatchContext located at a particular index.
* @param _index The index of the BatchContext
* @return The BatchContext at the specified index.
*/
function _getBatchContext(
uint256 _index
)
internal
pure
returns (
BatchContext memory
)
{
uint256 contextPtr = 15 + _index * BATCH_CONTEXT_SIZE;
uint256 numSequencedTransactions;
uint256 numSubsequentQueueTransactions;
uint256 ctxTimestamp;
uint256 ctxBlockNumber;
assembly {
numSequencedTransactions := shr(232, calldataload(contextPtr))
numSubsequentQueueTransactions := shr(232, calldataload(add(contextPtr, 3)))
ctxTimestamp := shr(216, calldataload(add(contextPtr, 6)))
ctxBlockNumber := shr(216, calldataload(add(contextPtr, 11)))
}
return BatchContext({
numSequencedTransactions: numSequencedTransactions,
numSubsequentQueueTransactions: numSubsequentQueueTransactions,
timestamp: ctxTimestamp,
blockNumber: ctxBlockNumber
});
}
/**
* Parses the batch context from the extra data.
* @return Total number of elements submitted.
* @return Index of the next queue element.
*/
function _getBatchExtraData()
internal
view
returns (
uint40,
uint40,
uint40,
uint40
)
{
bytes27 extraData = batches().getGlobalMetadata();
uint40 totalElements;
uint40 nextQueueIndex;
uint40 lastTimestamp;
uint40 lastBlockNumber;
// solhint-disable max-line-length
assembly {
extraData := shr(40, extraData)
totalElements := and(extraData, 0x000000000000000000000000000000000000000000000000000000FFFFFFFFFF)
nextQueueIndex := shr(40, and(extraData, 0x00000000000000000000000000000000000000000000FFFFFFFFFF0000000000))
lastTimestamp := shr(80, and(extraData, 0x0000000000000000000000000000000000FFFFFFFFFF00000000000000000000))
lastBlockNumber := shr(120, and(extraData, 0x000000000000000000000000FFFFFFFFFF000000000000000000000000000000))
}
// solhint-enable max-line-length
return (
totalElements,
nextQueueIndex,
lastTimestamp,
lastBlockNumber
);
}
/**
* Encodes the batch context for the extra data.
* @param _totalElements Total number of elements submitted.
* @param _nextQueueIndex Index of the next queue element.
* @param _timestamp Timestamp for the last batch.
* @param _blockNumber Block number of the last batch.
* @return Encoded batch context.
*/
function _makeBatchExtraData(
uint40 _totalElements,
uint40 _nextQueueIndex,
uint40 _timestamp,
uint40 _blockNumber
)
internal
pure
returns (
bytes27
)
{
bytes27 extraData;
assembly {
extraData := _totalElements
extraData := or(extraData, shl(40, _nextQueueIndex))
extraData := or(extraData, shl(80, _timestamp))
extraData := or(extraData, shl(120, _blockNumber))
extraData := shl(40, extraData)
}
return extraData;
}
/**
* Retrieves the hash of a queue element.
* @param _index Index of the queue element to retrieve a hash for.
* @return Hash of the queue element.
*/
function _getQueueLeafHash(
uint256 _index
)
internal
pure
returns (
bytes32
)
{
return _hashTransactionChainElement(
Lib_OVMCodec.TransactionChainElement({
isSequenced: false,
queueIndex: _index,
timestamp: 0,
blockNumber: 0,
txData: hex""
})
);
}
/**
* Gets the queue element at a particular index.
* @param _index Index of the queue element to access.
* @return _element Queue element at the given index.
*/
function _getQueueElement(
uint256 _index,
iOVM_ChainStorageContainer _queueRef
)
internal
view
returns (
Lib_OVMCodec.QueueElement memory _element
)
{
// The underlying queue data structure stores 2 elements
// per insertion, so to get the actual desired queue index
// we need to multiply by 2.
uint40 trueIndex = uint40(_index * 2);
bytes32 transactionHash = _queueRef.get(trueIndex);
bytes32 timestampAndBlockNumber = _queueRef.get(trueIndex + 1);
uint40 elementTimestamp;
uint40 elementBlockNumber;
// solhint-disable max-line-length
assembly {
elementTimestamp := and(timestampAndBlockNumber, 0x000000000000000000000000000000000000000000000000000000FFFFFFFFFF)
elementBlockNumber := shr(40, and(timestampAndBlockNumber, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000000000))
}
// solhint-enable max-line-length
return Lib_OVMCodec.QueueElement({
transactionHash: transactionHash,
timestamp: elementTimestamp,
blockNumber: elementBlockNumber
});
}
/**
* Retrieves the length of the queue.
* @return Length of the queue.
*/
function _getQueueLength(
iOVM_ChainStorageContainer _queueRef
)
internal
view
returns (
uint40
)
{
// The underlying queue data structure stores 2 elements
// per insertion, so to get the real queue length we need
// to divide by 2.
return uint40(_queueRef.length() / 2);
}
/**
* Retrieves the hash of a sequencer element.
* @param _context Batch context for the given element.
* @param _nextTransactionPtr Pointer to the next transaction in the calldata.
* @param _txDataLength Length of the transaction item.
* @return Hash of the sequencer element.
*/
function _getSequencerLeafHash(
BatchContext memory _context,
uint256 _nextTransactionPtr,
uint256 _txDataLength,
bytes memory _hashMemory
)
internal
pure
returns (
bytes32
)
{
// Only allocate more memory if we didn't reserve enough to begin with.
if (BYTES_TILL_TX_DATA + _txDataLength > _hashMemory.length) {
_hashMemory = new bytes(BYTES_TILL_TX_DATA + _txDataLength);
}
uint256 ctxTimestamp = _context.timestamp;
uint256 ctxBlockNumber = _context.blockNumber;
bytes32 leafHash;
assembly {
let chainElementStart := add(_hashMemory, 0x20)
// Set the first byte equal to `1` to indicate this is a sequencer chain element.
// This distinguishes sequencer ChainElements from queue ChainElements because
// all queue ChainElements are ABI encoded and the first byte of ABI encoded
// elements is always zero
mstore8(chainElementStart, 1)
mstore(add(chainElementStart, 1), ctxTimestamp)
mstore(add(chainElementStart, 33), ctxBlockNumber)
// solhint-disable-next-line max-line-length
calldatacopy(add(chainElementStart, BYTES_TILL_TX_DATA), add(_nextTransactionPtr, 3), _txDataLength)
leafHash := keccak256(chainElementStart, add(BYTES_TILL_TX_DATA, _txDataLength))
}
return leafHash;
}
/**
* Retrieves the hash of a sequencer element.
* @param _txChainElement The chain element which is hashed to calculate the leaf.
* @return Hash of the sequencer element.
*/
function _getSequencerLeafHash(
Lib_OVMCodec.TransactionChainElement memory _txChainElement
)
internal
view
returns(
bytes32
)
{
bytes memory txData = _txChainElement.txData;
uint256 txDataLength = _txChainElement.txData.length;
bytes memory chainElement = new bytes(BYTES_TILL_TX_DATA + txDataLength);
uint256 ctxTimestamp = _txChainElement.timestamp;
uint256 ctxBlockNumber = _txChainElement.blockNumber;
bytes32 leafHash;
assembly {
let chainElementStart := add(chainElement, 0x20)
// Set the first byte equal to `1` to indicate this is a sequencer chain element.
// This distinguishes sequencer ChainElements from queue ChainElements because
// all queue ChainElements are ABI encoded and the first byte of ABI encoded
// elements is always zero
mstore8(chainElementStart, 1)
mstore(add(chainElementStart, 1), ctxTimestamp)
mstore(add(chainElementStart, 33), ctxBlockNumber)
// solhint-disable-next-line max-line-length
pop(staticcall(gas(), 0x04, add(txData, 0x20), txDataLength, add(chainElementStart, BYTES_TILL_TX_DATA), txDataLength))
leafHash := keccak256(chainElementStart, add(BYTES_TILL_TX_DATA, txDataLength))
}
return leafHash;
}
/**
* Inserts a batch into the chain of batches.
* @param _transactionRoot Root of the transaction tree for this batch.
* @param _batchSize Number of elements in the batch.
* @param _numQueuedTransactions Number of queue transactions in the batch.
* @param _timestamp The latest batch timestamp.
* @param _blockNumber The latest batch blockNumber.
*/
function _appendBatch(
bytes32 _transactionRoot,
uint256 _batchSize,
uint256 _numQueuedTransactions,
uint40 _timestamp,
uint40 _blockNumber
)
internal
{
iOVM_ChainStorageContainer batchesRef = batches();
(uint40 totalElements, uint40 nextQueueIndex,,) = _getBatchExtraData();
Lib_OVMCodec.ChainBatchHeader memory header = Lib_OVMCodec.ChainBatchHeader({
batchIndex: batchesRef.length(),
batchRoot: _transactionRoot,
batchSize: _batchSize,
prevTotalElements: totalElements,
extraData: hex""
});
emit TransactionBatchAppended(
header.batchIndex,
header.batchRoot,
header.batchSize,
header.prevTotalElements,
header.extraData
);
bytes32 batchHeaderHash = Lib_OVMCodec.hashBatchHeader(header);
bytes27 latestBatchContext = _makeBatchExtraData(
totalElements + uint40(header.batchSize),
nextQueueIndex + uint40(_numQueuedTransactions),
_timestamp,
_blockNumber
);
batchesRef.push(batchHeaderHash, latestBatchContext);
}
/**
* Checks that the first batch context in a sequencer submission is valid
* @param _firstContext The batch context to validate.
*/
function _validateFirstBatchContext(
BatchContext memory _firstContext
)
internal
view
{
// If there are existing elements, this batch must have the same context
// or a later timestamp and block number.
if (getTotalElements() > 0) {
(,, uint40 lastTimestamp, uint40 lastBlockNumber) = _getBatchExtraData();
require(
_firstContext.blockNumber >= lastBlockNumber,
"Context block number is lower than last submitted."
);
require(
_firstContext.timestamp >= lastTimestamp,
"Context timestamp is lower than last submitted."
);
}
// Sequencer cannot submit contexts which are more than the force inclusion period old.
require(
_firstContext.timestamp + forceInclusionPeriodSeconds >= block.timestamp,
"Context timestamp too far in the past."
);
require(
_firstContext.blockNumber + forceInclusionPeriodBlocks >= block.number,
"Context block number too far in the past."
);
}
/**
* Checks that a given batch context has a time context which is below a given que element
* @param _context The batch context to validate has values lower.
* @param _queueIndex Index of the queue element we are validating came later than the context.
* @param _queueRef The storage container for the queue.
*/
function _validateContextBeforeEnqueue(
BatchContext memory _context,
uint40 _queueIndex,
iOVM_ChainStorageContainer _queueRef
)
internal
view
{
Lib_OVMCodec.QueueElement memory nextQueueElement = _getQueueElement(
_queueIndex,
_queueRef
);
// If the force inclusion period has passed for an enqueued transaction, it MUST be the
// next chain element.
require(
block.timestamp < nextQueueElement.timestamp + forceInclusionPeriodSeconds,
// solhint-disable-next-line max-line-length
"Previously enqueued batches have expired and must be appended before a new sequencer batch."
);
// Just like sequencer transaction times must be increasing relative to each other,
// We also require that they be increasing relative to any interspersed queue elements.
require(
_context.timestamp <= nextQueueElement.timestamp,
"Sequencer transaction timestamp exceeds that of next queue element."
);
require(
_context.blockNumber <= nextQueueElement.blockNumber,
"Sequencer transaction blockNumber exceeds that of next queue element."
);
}
/**
* Checks that a given batch context is valid based on its previous context, and the next queue
* elemtent.
* @param _prevContext The previously validated batch context.
* @param _nextContext The batch context to validate with this call.
* @param _nextQueueIndex Index of the next queue element to process for the _nextContext's
* subsequentQueueElements.
* @param _queueRef The storage container for the queue.
*/
function _validateNextBatchContext(
BatchContext memory _prevContext,
BatchContext memory _nextContext,
uint40 _nextQueueIndex,
iOVM_ChainStorageContainer _queueRef
)
internal
view
{
// All sequencer transactions' times must be greater than or equal to the previous ones.
require(
_nextContext.timestamp >= _prevContext.timestamp,
"Context timestamp values must monotonically increase."
);
require(
_nextContext.blockNumber >= _prevContext.blockNumber,
"Context blockNumber values must monotonically increase."
);
// If there is going to be a queue element pulled in from this context:
if (_nextContext.numSubsequentQueueTransactions > 0) {
_validateContextBeforeEnqueue(
_nextContext,
_nextQueueIndex,
_queueRef
);
}
}
/**
* Checks that the final batch context in a sequencer submission is valid.
* @param _finalContext The batch context to validate.
* @param _queueLength The length of the queue at the start of the batchAppend call.
* @param _nextQueueIndex The next element in the queue that will be pulled into the CTC.
* @param _queueRef The storage container for the queue.
*/
function _validateFinalBatchContext(
BatchContext memory _finalContext,
uint40 _nextQueueIndex,
uint40 _queueLength,
iOVM_ChainStorageContainer _queueRef
)
internal
view
{
// If the queue is not now empty, check the mononoticity of whatever the next batch that
// will come in is.
if (_queueLength - _nextQueueIndex > 0 && _finalContext.numSubsequentQueueTransactions == 0)
{
_validateContextBeforeEnqueue(
_finalContext,
_nextQueueIndex,
_queueRef
);
}
// Batches cannot be added from the future, or subsequent enqueue() contexts would violate
// monotonicity.
require(_finalContext.timestamp <= block.timestamp,
"Context timestamp is from the future.");
require(_finalContext.blockNumber <= block.number,
"Context block number is from the future.");
}
/**
* Hashes a transaction chain element.
* @param _element Chain element to hash.
* @return Hash of the chain element.
*/
function _hashTransactionChainElement(
Lib_OVMCodec.TransactionChainElement memory _element
)
internal
pure
returns (
bytes32
)
{
return keccak256(
abi.encode(
_element.isSequenced,
_element.queueIndex,
_element.timestamp,
_element.blockNumber,
_element.txData
)
);
}
/**
* Verifies a sequencer transaction, returning true if it was indeed included in the CTC
* @param _transaction The transaction we are verifying inclusion of.
* @param _txChainElement The chain element that the transaction is claimed to be a part of.
* @param _batchHeader Header of the batch the transaction was included in.
* @param _inclusionProof An inclusion proof into the CTC at a particular index.
* @return True if the transaction was included in the specified location, else false.
*/
function _verifySequencerTransaction(
Lib_OVMCodec.Transaction memory _transaction,
Lib_OVMCodec.TransactionChainElement memory _txChainElement,
Lib_OVMCodec.ChainBatchHeader memory _batchHeader,
Lib_OVMCodec.ChainInclusionProof memory _inclusionProof
)
internal
view
returns (
bool
)
{
OVM_ExecutionManager ovmExecutionManager =
OVM_ExecutionManager(resolve("OVM_ExecutionManager"));
uint256 gasLimit = ovmExecutionManager.getMaxTransactionGasLimit();
bytes32 leafHash = _getSequencerLeafHash(_txChainElement);
require(
_verifyElement(
leafHash,
_batchHeader,
_inclusionProof
),
"Invalid Sequencer transaction inclusion proof."
);
require(
_transaction.blockNumber == _txChainElement.blockNumber
&& _transaction.timestamp == _txChainElement.timestamp
&& _transaction.entrypoint == resolve("OVM_DecompressionPrecompileAddress")
&& _transaction.gasLimit == gasLimit
&& _transaction.l1TxOrigin == address(0)
&& _transaction.l1QueueOrigin == Lib_OVMCodec.QueueOrigin.SEQUENCER_QUEUE
&& keccak256(_transaction.data) == keccak256(_txChainElement.txData),
"Invalid Sequencer transaction."
);
return true;
}
/**
* Verifies a queue transaction, returning true if it was indeed included in the CTC
* @param _transaction The transaction we are verifying inclusion of.
* @param _queueIndex The queueIndex of the queued transaction.
* @param _batchHeader Header of the batch the transaction was included in.
* @param _inclusionProof An inclusion proof into the CTC at a particular index (should point to
* queue tx).
* @return True if the transaction was included in the specified location, else false.
*/
function _verifyQueueTransaction(
Lib_OVMCodec.Transaction memory _transaction,
uint256 _queueIndex,
Lib_OVMCodec.ChainBatchHeader memory _batchHeader,
Lib_OVMCodec.ChainInclusionProof memory _inclusionProof
)
internal
view
returns (
bool
)
{
bytes32 leafHash = _getQueueLeafHash(_queueIndex);
require(
_verifyElement(
leafHash,
_batchHeader,
_inclusionProof
),
"Invalid Queue transaction inclusion proof."
);
bytes32 transactionHash = keccak256(
abi.encode(
_transaction.l1TxOrigin,
_transaction.entrypoint,
_transaction.gasLimit,
_transaction.data
)
);
Lib_OVMCodec.QueueElement memory el = getQueueElement(_queueIndex);
require(
el.transactionHash == transactionHash
&& el.timestamp == _transaction.timestamp
&& el.blockNumber == _transaction.blockNumber,
"Invalid Queue transaction."
);
return true;
}
/**
* Verifies a batch inclusion proof.
* @param _element Hash of the element to verify a proof for.
* @param _batchHeader Header of the batch in which the element was included.
* @param _proof Merkle inclusion proof for the element.
*/
function _verifyElement(
bytes32 _element,
Lib_OVMCodec.ChainBatchHeader memory _batchHeader,
Lib_OVMCodec.ChainInclusionProof memory _proof
)
internal
view
returns (
bool
)
{
require(
Lib_OVMCodec.hashBatchHeader(_batchHeader) ==
batches().get(uint32(_batchHeader.batchIndex)),
"Invalid batch header."
);
require(
Lib_MerkleTree.verify(
_batchHeader.batchRoot,
_element,
_proof.index,
_proof.siblings,
_batchHeader.batchSize
),
"Invalid inclusion proof."
);
return true;
}
}
|
Returns the blocknumber of the last transaction. return Blocknumber for the last transaction./
|
function getLastBlockNumber()
override
public
view
returns (
uint40
)
{
(,,,uint40 lastBlockNumber) = _getBatchExtraData();
return lastBlockNumber;
}
| 940,370 |
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.6.12;
import "./PoolTokensContainer.sol";
import "./LiquidityPoolV2ConverterCustomFactory.sol";
import "../../LiquidityPoolConverter.sol";
import "../../interfaces/IConverterFactory.sol";
import "../../../utility/interfaces/IPriceOracle.sol";
/**
* @dev Liquidity Pool v2 Converter
*
* The liquidity pool v2 converter is a specialized version of a converter that uses
* price oracles to rebalance the reserve weights in such a way that the primary token
* balance always strives to match the staked balance.
*
* This type of liquidity pool always has 2 reserves and the reserve weights are dynamic.
*/
contract LiquidityPoolV2Converter is LiquidityPoolConverter {
uint32 internal constant HIGH_FEE_UPPER_BOUND = 997500; // high fee upper bound in PPM units
uint256 internal constant MAX_RATE_FACTOR_LOWER_BOUND = 1e30;
struct Fraction {
uint256 n; // numerator
uint256 d; // denominator
}
IPriceOracle public priceOracle; // external price oracle
IERC20Token public primaryReserveToken; // primary reserve in the pool
IERC20Token public secondaryReserveToken; // secondary reserve in the pool (cache)
mapping (IERC20Token => uint256) private stakedBalances; // tracks the staked liquidity in the pool plus the fees
mapping (IERC20Token => ISmartToken) private reservesToPoolTokens; // maps each reserve to its pool token
mapping (ISmartToken => IERC20Token) private poolTokensToReserves; // maps each pool token to its reserve
uint8 public amplificationFactor = 20; // factor to use for conversion calculations (reduces slippage)
uint256 public externalRatePropagationTime = 1 hours; // the time it takes for the external rate to fully take effect
uint256 public prevConversionTime; // previous conversion time in seconds
// factors used in fee calculations
uint32 public lowFeeFactor = 200000;
uint32 public highFeeFactor = 800000;
// used by the temp liquidity limit mechanism during the beta
mapping (IERC20Token => uint256) public maxStakedBalances;
bool public maxStakedBalanceEnabled = true;
/**
* @dev triggered when the amplification factor is updated
*
* @param _prevAmplificationFactor previous amplification factor
* @param _newAmplificationFactor new amplification factor
*/
event AmplificationFactorUpdate(uint8 _prevAmplificationFactor, uint8 _newAmplificationFactor);
/**
* @dev triggered when the external rate propagation time is updated
*
* @param _prevPropagationTime previous external rate propagation time, in seconds
* @param _newPropagationTime new external rate propagation time, in seconds
*/
event ExternalRatePropagationTimeUpdate(uint256 _prevPropagationTime, uint256 _newPropagationTime);
/**
* @dev triggered when the fee factors are updated
*
* @param _prevLowFactor previous low factor percentage, represented in ppm
* @param _newLowFactor new low factor percentage, represented in ppm
* @param _prevHighFactor previous high factor percentage, represented in ppm
* @param _newHighFactor new high factor percentage, represented in ppm
*/
event FeeFactorsUpdate(uint256 _prevLowFactor, uint256 _newLowFactor, uint256 _prevHighFactor, uint256 _newHighFactor);
/**
* @dev initializes a new LiquidityPoolV2Converter instance
*
* @param _poolTokensContainer pool tokens container governed by the converter
* @param _registry address of a contract registry contract
* @param _maxConversionFee maximum conversion fee, represented in ppm
*/
constructor(IPoolTokensContainer _poolTokensContainer, IContractRegistry _registry, uint32 _maxConversionFee)
public LiquidityPoolConverter(_poolTokensContainer, _registry, _maxConversionFee)
{
}
// ensures the address is a pool token
modifier validPoolToken(ISmartToken _address) {
_validPoolToken(_address);
_;
}
// error message binary size optimization
function _validPoolToken(ISmartToken _address) internal view {
require(address(poolTokensToReserves[_address]) != address(0), "ERR_INVALID_POOL_TOKEN");
}
/**
* @dev returns the converter type
*
* @return see the converter types in the the main contract doc
*/
function converterType() public override pure returns (uint16) {
return 2;
}
/**
* @dev returns true if the converter is active, false otherwise
*
* @return true if the converter is active, false otherwise
*/
function isActive() public override view returns (bool) {
return super.isActive() && address(priceOracle) != address(0);
}
/**
* @dev sets the pool's primary reserve token / price oracles and activates the pool
* each oracle must be able to provide the rate for each reserve token
* note that the oracle must be whitelisted prior to the call
* can only be called by the owner while the pool is inactive
*
* @param _primaryReserveToken address of the pool's primary reserve token
* @param _primaryReserveOracle address of a chainlink price oracle for the primary reserve token
* @param _secondaryReserveOracle address of a chainlink price oracle for the secondary reserve token
*/
function activate(
IERC20Token _primaryReserveToken,
IChainlinkPriceOracle _primaryReserveOracle,
IChainlinkPriceOracle _secondaryReserveOracle)
public
inactive
ownerOnly
validReserve(_primaryReserveToken)
notThis(address(_primaryReserveOracle))
notThis(address(_secondaryReserveOracle))
validAddress(address(_primaryReserveOracle))
validAddress(address(_secondaryReserveOracle))
{
// validate anchor ownership
require(anchor.owner() == address(this), "ERR_ANCHOR_NOT_OWNED");
// validate oracles
IWhitelist oracleWhitelist = IWhitelist(addressOf(CHAINLINK_ORACLE_WHITELIST));
require(oracleWhitelist.isWhitelisted(address(_primaryReserveOracle)) &&
oracleWhitelist.isWhitelisted(address(_secondaryReserveOracle)), "ERR_INVALID_ORACLE");
// create the converter's pool tokens if they don't already exist
createPoolTokens();
// sets the primary & secondary reserve tokens
primaryReserveToken = _primaryReserveToken;
if (_primaryReserveToken == reserveTokens[0])
secondaryReserveToken = reserveTokens[1];
else
secondaryReserveToken = reserveTokens[0];
// creates and initalizes the price oracle and sets initial rates
LiquidityPoolV2ConverterCustomFactory customFactory =
LiquidityPoolV2ConverterCustomFactory(address(IConverterFactory(addressOf(CONVERTER_FACTORY)).customFactories(converterType())));
priceOracle = customFactory.createPriceOracle(
_primaryReserveToken,
secondaryReserveToken,
_primaryReserveOracle,
_secondaryReserveOracle);
// if we are upgrading from an older converter, make sure that reserve balances are in-sync and rebalance
uint256 primaryReserveStakedBalance = reserveStakedBalance(primaryReserveToken);
uint256 primaryReserveBalance = reserveBalance(primaryReserveToken);
uint256 secondaryReserveBalance = reserveBalance(secondaryReserveToken);
if (primaryReserveStakedBalance == primaryReserveBalance) {
if (primaryReserveStakedBalance > 0 || secondaryReserveBalance > 0) {
rebalance();
}
}
else if (primaryReserveStakedBalance > 0 && primaryReserveBalance > 0 && secondaryReserveBalance > 0) {
rebalance();
}
emit Activation(converterType(), anchor, true);
}
/**
* @dev returns the staked balance of a given reserve token
*
* @param _reserveToken reserve token address
*
* @return staked balance
*/
function reserveStakedBalance(IERC20Token _reserveToken)
public
view
validReserve(_reserveToken)
returns (uint256)
{
return stakedBalances[_reserveToken];
}
/**
* @dev returns the amplified balance of a given reserve token
*
* @param _reserveToken reserve token address
*
* @return amplified balance
*/
function reserveAmplifiedBalance(IERC20Token _reserveToken)
public
view
validReserve(_reserveToken)
returns (uint256)
{
return amplifiedBalance(_reserveToken);
}
/**
* @dev sets the reserve's staked balance
* can only be called by the upgrader contract while the upgrader is the owner
*
* @param _reserveToken reserve token address
* @param _balance new reserve staked balance
*/
function setReserveStakedBalance(IERC20Token _reserveToken, uint256 _balance)
public
ownerOnly
only(CONVERTER_UPGRADER)
validReserve(_reserveToken)
{
stakedBalances[_reserveToken] = _balance;
}
/**
* @dev sets the max staked balance for both reserves
* available as a temporary mechanism during the beta
* can only be called by the owner
*
* @param _reserve1MaxStakedBalance max staked balance for reserve 1
* @param _reserve2MaxStakedBalance max staked balance for reserve 2
*/
function setMaxStakedBalances(uint256 _reserve1MaxStakedBalance, uint256 _reserve2MaxStakedBalance) public ownerOnly {
maxStakedBalances[reserveTokens[0]] = _reserve1MaxStakedBalance;
maxStakedBalances[reserveTokens[1]] = _reserve2MaxStakedBalance;
}
/**
* @dev disables the max staked balance mechanism
* available as a temporary mechanism during the beta
* once disabled, it cannot be re-enabled
* can only be called by the owner
*/
function disableMaxStakedBalances() public ownerOnly {
maxStakedBalanceEnabled = false;
}
/**
* @dev returns the pool token address by the reserve token address
*
* @param _reserveToken reserve token address
*
* @return pool token address
*/
function poolToken(IERC20Token _reserveToken) public view returns (ISmartToken) {
return reservesToPoolTokens[_reserveToken];
}
/**
* @dev returns the maximum number of pool tokens that can currently be liquidated
*
* @param _poolToken address of the pool token
*
* @return liquidation limit
*/
function liquidationLimit(ISmartToken _poolToken) public view returns (uint256) {
// get the pool token supply
uint256 poolTokenSupply = _poolToken.totalSupply();
// get the reserve token associated with the pool token and its balance / staked balance
IERC20Token reserveToken = poolTokensToReserves[_poolToken];
uint256 balance = reserveBalance(reserveToken);
uint256 stakedBalance = stakedBalances[reserveToken];
// calculate the amount that's available for liquidation
return balance.mul(poolTokenSupply).div(stakedBalance);
}
/**
* @dev defines a new reserve token for the converter
* can only be called by the owner while the converter is inactive and
* 2 reserves aren't defined yet
*
* @param _token address of the reserve token
* @param _weight reserve weight, represented in ppm, 1-1000000
*/
function addReserve(IERC20Token _token, uint32 _weight) public override ownerOnly {
// verify that the converter doesn't have 2 reserves yet
require(reserveTokenCount() < 2, "ERR_INVALID_RESERVE_COUNT");
super.addReserve(_token, _weight);
}
/**
* @dev returns the effective rate of 1 primary token in secondary tokens
*
* @return rate of 1 primary token in secondary tokens (numerator)
* @return rate of 1 primary token in secondary tokens (denominator)
*/
function effectiveTokensRate() public view returns (uint256, uint256) {
Fraction memory rate = rateFromPrimaryWeight(effectivePrimaryWeight());
return (rate.n, rate.d);
}
/**
* @dev returns the effective reserve tokens weights
*
* @return reserve1 weight
* @return reserve2 weight
*/
function effectiveReserveWeights() public view returns (uint256, uint256) {
uint32 primaryReserveWeight = effectivePrimaryWeight();
if (primaryReserveToken == reserveTokens[0]) {
return (primaryReserveWeight, inverseWeight(primaryReserveWeight));
}
return (inverseWeight(primaryReserveWeight), primaryReserveWeight);
}
/**
* @dev updates the amplification factor
* can only be called by the contract owner
*
* @param _amplificationFactor new amplification factor
*/
function setAmplificationFactor(uint8 _amplificationFactor) public ownerOnly {
emit AmplificationFactorUpdate(amplificationFactor, _amplificationFactor);
amplificationFactor = _amplificationFactor;
}
/**
* @dev updates the external rate propagation time
* can only be called by the contract owner
*
* @param _propagationTime new rate propagation time, in seconds
*/
function setExternalRatePropagationTime(uint256 _propagationTime) public ownerOnly {
emit ExternalRatePropagationTimeUpdate(externalRatePropagationTime, _propagationTime);
externalRatePropagationTime = _propagationTime;
}
/**
* @dev updates the fee factors
* can only be called by the contract owner
*
* @param _lowFactor new low fee factor, represented in ppm
* @param _highFactor new high fee factor, represented in ppm
*/
function setFeeFactors(uint32 _lowFactor, uint32 _highFactor) public ownerOnly {
require(_lowFactor <= PPM_RESOLUTION, "ERR_INVALID_FEE_FACTOR");
require(_highFactor <= PPM_RESOLUTION, "ERR_INVALID_FEE_FACTOR");
emit FeeFactorsUpdate(lowFeeFactor, _lowFactor, highFeeFactor, _highFactor);
lowFeeFactor = _lowFactor;
highFeeFactor = _highFactor;
}
/**
* @dev returns the expected target amount of converting one reserve to another along with the fee
*
* @param _sourceToken contract address of the source reserve token
* @param _targetToken contract address of the target reserve token
* @param _amount amount of tokens received from the user
*
* @return expected target amount
* @return expected fee
*/
function targetAmountAndFee(IERC20Token _sourceToken, IERC20Token _targetToken, uint256 _amount)
public
override
view
active
validReserve(_sourceToken)
validReserve(_targetToken)
returns (uint256, uint256)
{
// validate input
require(_sourceToken != _targetToken, "ERR_SAME_SOURCE_TARGET");
// get the external rate between the reserves along with its update time
Fraction memory externalRate;
uint256 externalRateUpdateTime;
(externalRate.n, externalRate.d, externalRateUpdateTime) =
priceOracle.latestRateAndUpdateTime(primaryReserveToken, secondaryReserveToken);
// get the source token effective / external weights
(uint32 sourceTokenWeight, uint32 externalSourceTokenWeight) = effectiveAndExternalPrimaryWeight(externalRate, externalRateUpdateTime);
if (_targetToken == primaryReserveToken) {
sourceTokenWeight = inverseWeight(sourceTokenWeight);
externalSourceTokenWeight = inverseWeight(externalSourceTokenWeight);
}
// return the target amount and the fee using the updated reserve weights
return targetAmountAndFee(
_sourceToken, _targetToken,
sourceTokenWeight, inverseWeight(sourceTokenWeight),
externalRate, inverseWeight(externalSourceTokenWeight),
_amount);
}
/**
* @dev converts a specific amount of source tokens to target tokens
* can only be called by the bancor network contract
*
* @param _sourceToken source ERC20 token
* @param _targetToken target ERC20 token
* @param _amount amount of tokens to convert (in units of the source token)
* @param _trader address of the caller who executed the conversion
* @param _beneficiary wallet to receive the conversion result
*
* @return amount of tokens received (in units of the target token)
*/
function doConvert(IERC20Token _sourceToken, IERC20Token _targetToken, uint256 _amount, address _trader, address payable _beneficiary)
internal
override
active
validReserve(_sourceToken)
validReserve(_targetToken)
returns (uint256)
{
// convert and get the target amount and fee
(uint256 amount, uint256 fee) = doConvert(_sourceToken, _targetToken, _amount);
// update the previous conversion time
prevConversionTime = time();
// transfer funds to the beneficiary in the to reserve token
if (_targetToken == ETH_RESERVE_ADDRESS) {
_beneficiary.transfer(amount);
}
else {
safeTransfer(_targetToken, _beneficiary, amount);
}
// dispatch the conversion event
dispatchConversionEvent(_sourceToken, _targetToken, _trader, _amount, amount, fee);
// dispatch rate updates for the pool / reserve tokens
dispatchRateEvents(_sourceToken, _targetToken, reserves[_sourceToken].weight, reserves[_targetToken].weight);
// return the conversion result amount
return amount;
}
/**
* @dev converts a specific amount of source tokens to target tokens
* can only be called by the bancor network contract
*
* @param _sourceToken source ERC20 token
* @param _targetToken target ERC20 token
* @param _amount amount of tokens to convert (in units of the source token)
*
* @return amount of target tokens received
* @return fee amount
*/
function doConvert(IERC20Token _sourceToken, IERC20Token _targetToken, uint256 _amount) private returns (uint256, uint256) {
// get the external rate between the reserves along with its update time
Fraction memory externalRate;
uint256 externalRateUpdateTime;
(externalRate.n, externalRate.d, externalRateUpdateTime) = priceOracle.latestRateAndUpdateTime(primaryReserveToken, secondaryReserveToken);
// pre-conversion preparation - update the weights if needed and get the target amount and feee
(uint256 targetAmount, uint256 fee) = prepareConversion(_sourceToken, _targetToken, _amount, externalRate, externalRateUpdateTime);
// ensure that the trade gives something in return
require(targetAmount != 0, "ERR_ZERO_TARGET_AMOUNT");
// ensure that the trade won't deplete the reserve balance
uint256 targetReserveBalance = reserves[_targetToken].balance;
require(targetAmount < targetReserveBalance, "ERR_TARGET_AMOUNT_TOO_HIGH");
// ensure that the input amount was already deposited
if (_sourceToken == ETH_RESERVE_ADDRESS)
require(msg.value == _amount, "ERR_ETH_AMOUNT_MISMATCH");
else
require(msg.value == 0 && _sourceToken.balanceOf(address(this)).sub(reserves[_sourceToken].balance) >= _amount, "ERR_INVALID_AMOUNT");
// sync the reserve balances
syncReserveBalance(_sourceToken);
reserves[_targetToken].balance = targetReserveBalance.sub(targetAmount);
// if the pool is in deficit, add half the fee to the target staked balance, otherwise add all
stakedBalances[_targetToken] = stakedBalances[_targetToken].add(calculateDeficit(externalRate) == 0 ? fee : fee / 2);
// return a tuple of [target amount (excluding fee), fee]
return (targetAmount, fee);
}
/**
* @dev increases the pool's liquidity and mints new shares in the pool to the caller
*
* @param _reserveToken address of the reserve token to add liquidity to
* @param _amount amount of liquidity to add
* @param _minReturn minimum return-amount of pool tokens
*
* @return amount of pool tokens minted
*/
function addLiquidity(IERC20Token _reserveToken, uint256 _amount, uint256 _minReturn)
public
payable
protected
active
validReserve(_reserveToken)
greaterThanZero(_amount)
greaterThanZero(_minReturn)
returns (uint256)
{
// verify that msg.value is identical to the provided amount for ETH reserve, or 0 otherwise
require(_reserveToken == ETH_RESERVE_ADDRESS ? msg.value == _amount : msg.value == 0, "ERR_ETH_AMOUNT_MISMATCH");
// sync the reserve balances just in case
syncReserveBalances();
// for ETH reserve, deduct the amount that was just synced (since it's already in the converter)
if (_reserveToken == ETH_RESERVE_ADDRESS) {
reserves[ETH_RESERVE_ADDRESS].balance = reserves[ETH_RESERVE_ADDRESS].balance.sub(msg.value);
}
// get the reserve staked balance before adding the liquidity to it
uint256 initialStakedBalance = stakedBalances[_reserveToken];
// during the beta, ensure that the new staked balance isn't greater than the max limit
if (maxStakedBalanceEnabled) {
require(maxStakedBalances[_reserveToken] == 0 || initialStakedBalance.add(_amount) <= maxStakedBalances[_reserveToken], "ERR_MAX_STAKED_BALANCE_REACHED");
}
// get the pool token associated with the reserve and its supply
ISmartToken reservePoolToken = reservesToPoolTokens[_reserveToken];
uint256 poolTokenSupply = reservePoolToken.totalSupply();
// for non ETH reserve, transfer the funds from the user to the pool
if (_reserveToken != ETH_RESERVE_ADDRESS)
safeTransferFrom(_reserveToken, msg.sender, address(this), _amount);
// get the rate before updating the staked balance
Fraction memory rate = rebalanceRate();
// sync the reserve balance / staked balance
reserves[_reserveToken].balance = reserves[_reserveToken].balance.add(_amount);
stakedBalances[_reserveToken] = initialStakedBalance.add(_amount);
// calculate how many pool tokens to mint
// for an empty pool, the price is 1:1, otherwise the price is based on the ratio
// between the pool token supply and the staked balance
uint256 poolTokenAmount = 0;
if (initialStakedBalance == 0 || poolTokenSupply == 0)
poolTokenAmount = _amount;
else
poolTokenAmount = _amount.mul(poolTokenSupply).div(initialStakedBalance);
require(poolTokenAmount >= _minReturn, "ERR_RETURN_TOO_LOW");
// mint new pool tokens to the caller
IPoolTokensContainer(address(anchor)).mint(reservePoolToken, msg.sender, poolTokenAmount);
// rebalance the pool's reserve weights
rebalance(rate);
// dispatch the LiquidityAdded event
emit LiquidityAdded(msg.sender, _reserveToken, _amount, initialStakedBalance.add(_amount), poolTokenSupply.add(poolTokenAmount));
// dispatch the `TokenRateUpdate` event for the pool token
dispatchPoolTokenRateUpdateEvent(reservePoolToken, poolTokenSupply.add(poolTokenAmount), _reserveToken);
// dispatch the `TokenRateUpdate` event for the reserve tokens
dispatchTokenRateUpdateEvent(reserveTokens[0], reserveTokens[1], 0, 0);
// return the amount of pool tokens minted
return poolTokenAmount;
}
/**
* @dev decreases the pool's liquidity and burns the caller's shares in the pool
*
* @param _poolToken address of the pool token
* @param _amount amount of pool tokens to burn
* @param _minReturn minimum return-amount of reserve tokens
*
* @return amount of liquidity removed
*/
function removeLiquidity(ISmartToken _poolToken, uint256 _amount, uint256 _minReturn)
public
protected
active
validPoolToken(_poolToken)
greaterThanZero(_amount)
greaterThanZero(_minReturn)
returns (uint256)
{
// sync the reserve balances just in case
syncReserveBalances();
// get the pool token supply before burning the caller's shares
uint256 initialPoolSupply = _poolToken.totalSupply();
// get the reserve token return before burning the caller's shares
(uint256 reserveAmount, ) = removeLiquidityReturnAndFee(_poolToken, _amount);
require(reserveAmount >= _minReturn, "ERR_RETURN_TOO_LOW");
// get the reserve token associated with the pool token
IERC20Token reserveToken = poolTokensToReserves[_poolToken];
// burn the caller's pool tokens
IPoolTokensContainer(address(anchor)).burn(_poolToken, msg.sender, _amount);
// get the rate before updating the staked balance
Fraction memory rate = rebalanceRate();
// sync the reserve balance / staked balance
reserves[reserveToken].balance = reserves[reserveToken].balance.sub(reserveAmount);
uint256 newStakedBalance = stakedBalances[reserveToken].sub(reserveAmount);
stakedBalances[reserveToken] = newStakedBalance;
// transfer the reserve amount to the caller
if (reserveToken == ETH_RESERVE_ADDRESS)
msg.sender.transfer(reserveAmount);
else
safeTransfer(reserveToken, msg.sender, reserveAmount);
// rebalance the pool's reserve weights
rebalance(rate);
uint256 newPoolTokenSupply = initialPoolSupply.sub(_amount);
// dispatch the LiquidityRemoved event
emit LiquidityRemoved(msg.sender, reserveToken, reserveAmount, newStakedBalance, newPoolTokenSupply);
// dispatch the `TokenRateUpdate` event for the pool token
dispatchPoolTokenRateUpdateEvent(_poolToken, newPoolTokenSupply, reserveToken);
// dispatch the `TokenRateUpdate` event for the reserve tokens
dispatchTokenRateUpdateEvent(reserveTokens[0], reserveTokens[1], 0, 0);
// return the amount of liquidity removed
return reserveAmount;
}
/**
* @dev calculates the amount of reserve tokens entitled for a given amount of pool tokens
* note that a fee is applied according to the equilibrium level of the primary reserve token
*
* @param _poolToken address of the pool token
* @param _amount amount of pool tokens
*
* @return amount after fee and fee, in reserve token units
*/
function removeLiquidityReturnAndFee(ISmartToken _poolToken, uint256 _amount) public view returns (uint256, uint256) {
uint256 totalSupply = _poolToken.totalSupply();
uint256 stakedBalance = stakedBalances[poolTokensToReserves[_poolToken]];
if (_amount < totalSupply) {
(uint256 min, uint256 max) = tokensRateAccuracy();
uint256 amountBeforeFee = _amount.mul(stakedBalance).div(totalSupply);
uint256 amountAfterFee = amountBeforeFee.mul(min).div(max);
return (amountAfterFee, amountBeforeFee - amountAfterFee);
}
return (stakedBalance, 0);
}
/**
* @dev calculates the tokens-rate accuracy
*
* @return the tokens-rate accuracy as a tuple of numerator and denominator
*/
function tokensRateAccuracy() internal view returns (uint256, uint256) {
uint32 weight = reserves[primaryReserveToken].weight;
Fraction memory poolRate = tokensRate(primaryReserveToken, secondaryReserveToken, weight, inverseWeight(weight));
(uint256 n, uint256 d) = effectiveTokensRate();
(uint256 x, uint256 y) = reducedRatio(poolRate.n.mul(d), poolRate.d.mul(n), MAX_RATE_FACTOR_LOWER_BOUND);
return x < y ? (x, y) : (y, x);
}
/**
* @dev returns the expected target amount of converting one reserve to another along with the fee
* this version of the function expects the reserve weights as an input (gas optimization)
*
* @param _sourceToken contract address of the source reserve token
* @param _targetToken contract address of the target reserve token
* @param _sourceWeight source reserve token weight
* @param _targetWeight target reserve token weight
* @param _externalRate external rate of 1 primary token in secondary tokens
* @param _targetExternalWeight target reserve token weight based on external rate
* @param _amount amount of tokens received from the user
*
* @return expected target amount
* @return expected fee
*/
function targetAmountAndFee(
IERC20Token _sourceToken,
IERC20Token _targetToken,
uint32 _sourceWeight,
uint32 _targetWeight,
Fraction memory _externalRate,
uint32 _targetExternalWeight,
uint256 _amount)
private
view
returns (uint256, uint256)
{
// get the tokens amplified balances
uint256 sourceBalance = amplifiedBalance(_sourceToken);
uint256 targetBalance = amplifiedBalance(_targetToken);
// get the target amount
uint256 targetAmount = IBancorFormula(addressOf(BANCOR_FORMULA)).crossReserveTargetAmount(
sourceBalance,
_sourceWeight,
targetBalance,
_targetWeight,
_amount
);
// if the target amount is larger than the target reserve balance, return 0
// this can happen due to the amplification
require(targetAmount <= reserves[_targetToken].balance, "ERR_TARGET_AMOUNT_TOO_HIGH");
// return a tuple of [target amount (excluding fee), fee]
uint256 fee = calculateFee(_sourceToken, _targetToken, _sourceWeight, _targetWeight, _externalRate, _targetExternalWeight, targetAmount);
return (targetAmount - fee, fee);
}
/**
* @dev returns the fee amount for a given target amount
*
* @param _sourceToken contract address of the source reserve token
* @param _targetToken contract address of the target reserve token
* @param _sourceWeight source reserve token weight
* @param _targetWeight target reserve token weight
* @param _externalRate external rate of 1 primary token in secondary tokens
* @param _targetExternalWeight target reserve token weight based on external rate
* @param _targetAmount target amount
*
* @return fee amount
*/
function calculateFee(
IERC20Token _sourceToken,
IERC20Token _targetToken,
uint32 _sourceWeight,
uint32 _targetWeight,
Fraction memory _externalRate,
uint32 _targetExternalWeight,
uint256 _targetAmount)
internal view returns (uint256)
{
// get the external rate of 1 source token in target tokens
Fraction memory targetExternalRate;
if (_targetToken == primaryReserveToken) {
(targetExternalRate.n, targetExternalRate.d) = (_externalRate.n, _externalRate.d);
}
else {
(targetExternalRate.n, targetExternalRate.d) = (_externalRate.d, _externalRate.n);
}
// get the token pool rate
Fraction memory currentRate = tokensRate(_targetToken, _sourceToken, _targetWeight, _sourceWeight);
if (compareRates(currentRate, targetExternalRate) < 0) {
uint256 lo = currentRate.n.mul(targetExternalRate.d);
uint256 hi = targetExternalRate.n.mul(currentRate.d);
(lo, hi) = reducedRatio(hi - lo, hi, MAX_RATE_FACTOR_LOWER_BOUND);
// apply the high fee only if the ratio between the effective weight and the external (target) weight is below the high fee upper bound
uint32 feeFactor;
if (uint256(_targetWeight).mul(PPM_RESOLUTION) < uint256(_targetExternalWeight).mul(HIGH_FEE_UPPER_BOUND)) {
feeFactor = highFeeFactor;
}
else {
feeFactor = lowFeeFactor;
}
return _targetAmount.mul(lo).mul(feeFactor).div(hi.mul(PPM_RESOLUTION));
}
return 0;
}
/**
* @dev calculates the deficit in the pool (in secondary reserve token amount)
*
* @param _externalRate external rate of 1 primary token in secondary tokens
*
* @return the deficit in the pool
*/
function calculateDeficit(Fraction memory _externalRate) internal view returns (uint256) {
IERC20Token primaryReserveTokenLocal = primaryReserveToken; // gas optimization
IERC20Token secondaryReserveTokenLocal = secondaryReserveToken; // gas optimization
// get the amount of primary balances in secondary tokens using the external rate
uint256 primaryBalanceInSecondary = reserves[primaryReserveTokenLocal].balance.mul(_externalRate.n).div(_externalRate.d);
uint256 primaryStakedInSecondary = stakedBalances[primaryReserveTokenLocal].mul(_externalRate.n).div(_externalRate.d);
// if the total balance is lower than the total staked balance, return the delta
uint256 totalBalance = primaryBalanceInSecondary.add(reserves[secondaryReserveTokenLocal].balance);
uint256 totalStaked = primaryStakedInSecondary.add(stakedBalances[secondaryReserveTokenLocal]);
if (totalBalance < totalStaked) {
return totalStaked - totalBalance;
}
return 0;
}
/**
* @dev updates the weights based on the effective weights calculation if needed
* and returns the target amount and fee
*
* @param _sourceToken source ERC20 token
* @param _targetToken target ERC20 token
* @param _amount amount of tokens to convert (in units of the source token)
* @param _externalRate external rate of 1 primary token in secondary tokens
* @param _externalRateUpdateTime external rate update time
*
* @return expected target amount
* @return expected fee
*/
function prepareConversion(
IERC20Token _sourceToken,
IERC20Token _targetToken,
uint256 _amount,
Fraction memory _externalRate,
uint256 _externalRateUpdateTime)
internal
returns (uint256, uint256)
{
// get the source token effective / external weights
(uint32 effectiveSourceReserveWeight, uint32 externalSourceReserveWeight) =
effectiveAndExternalPrimaryWeight(_externalRate, _externalRateUpdateTime);
if (_targetToken == primaryReserveToken) {
effectiveSourceReserveWeight = inverseWeight(effectiveSourceReserveWeight);
externalSourceReserveWeight = inverseWeight(externalSourceReserveWeight);
}
// check if the weights need to be updated
if (reserves[_sourceToken].weight != effectiveSourceReserveWeight) {
// update the weights
reserves[_sourceToken].weight = effectiveSourceReserveWeight;
reserves[_targetToken].weight = inverseWeight(effectiveSourceReserveWeight);
}
// get expected target amount and fee
return targetAmountAndFee(
_sourceToken, _targetToken,
effectiveSourceReserveWeight, inverseWeight(effectiveSourceReserveWeight),
_externalRate, inverseWeight(externalSourceReserveWeight),
_amount);
}
/**
* @dev creates the converter's pool tokens
* note that technically pool tokens can be created on deployment but gas limit
* might get too high for a block, so creating them on first activation
*
*/
function createPoolTokens() internal {
IPoolTokensContainer container = IPoolTokensContainer(address(anchor));
ISmartToken[] memory poolTokens = container.poolTokens();
bool initialSetup = poolTokens.length == 0;
uint256 reserveCount = reserveTokens.length;
for (uint256 i = 0; i < reserveCount; i++) {
ISmartToken reservePoolToken;
if (initialSetup) {
reservePoolToken = container.createToken();
}
else {
reservePoolToken = poolTokens[i];
}
// cache the pool token address (gas optimization)
reservesToPoolTokens[reserveTokens[i]] = reservePoolToken;
poolTokensToReserves[reservePoolToken] = reserveTokens[i];
}
}
/**
* @dev returns the effective primary reserve token weight
*
* @return effective primary reserve weight
*/
function effectivePrimaryWeight() internal view returns (uint32) {
// get the external rate between the reserves along with its update time
Fraction memory externalRate;
uint256 externalRateUpdateTime;
(externalRate.n, externalRate.d, externalRateUpdateTime) = priceOracle.latestRateAndUpdateTime(primaryReserveToken, secondaryReserveToken);
(uint32 effectiveWeight,) = effectiveAndExternalPrimaryWeight(externalRate, externalRateUpdateTime);
return effectiveWeight;
}
/**
* @dev returns the effective and the external primary reserve token weights
*
* @param _externalRate external rate of 1 primary token in secondary tokens
* @param _externalRateUpdateTime external rate update time
*
* @return effective primary reserve weight
* @return external primary reserve weight
*/
function effectiveAndExternalPrimaryWeight(Fraction memory _externalRate, uint256 _externalRateUpdateTime)
internal
view
returns
(uint32, uint32)
{
// get the external rate primary reserve weight
uint32 externalPrimaryReserveWeight = primaryWeightFromRate(_externalRate);
// get the primary reserve weight
IERC20Token primaryReserveTokenLocal = primaryReserveToken; // gas optimization
uint32 primaryReserveWeight = reserves[primaryReserveTokenLocal].weight;
// if the weights are already at their target, return current weights
if (primaryReserveWeight == externalPrimaryReserveWeight) {
return (primaryReserveWeight, externalPrimaryReserveWeight);
}
// get the elapsed time since the last conversion time and the external rate update time
uint256 referenceTime = prevConversionTime;
if (referenceTime < _externalRateUpdateTime) {
referenceTime = _externalRateUpdateTime;
}
// limit the reference time by current time
uint256 currentTime = time();
if (referenceTime > currentTime) {
referenceTime = currentTime;
}
// if no time has passed since the reference time, return current weights (also ensures a single update per block)
uint256 elapsedTime = currentTime - referenceTime;
if (elapsedTime == 0) {
return (primaryReserveWeight, externalPrimaryReserveWeight);
}
// find the token whose weight is lower than the target weight and get its pool rate - if it's
// lower than external rate, update the weights
Fraction memory poolRate = tokensRate(
primaryReserveTokenLocal,
secondaryReserveToken,
primaryReserveWeight,
inverseWeight(primaryReserveWeight));
bool updateWeights = false;
if (primaryReserveWeight < externalPrimaryReserveWeight) {
updateWeights = compareRates(poolRate, _externalRate) < 0;
}
else {
updateWeights = compareRates(poolRate, _externalRate) > 0;
}
if (!updateWeights) {
return (primaryReserveWeight, externalPrimaryReserveWeight);
}
// if the elapsed time since the reference rate is equal or larger than the propagation time,
// the external rate should take full effect
if (elapsedTime >= externalRatePropagationTime) {
return (externalPrimaryReserveWeight, externalPrimaryReserveWeight);
}
// move the weights towards their target by the same proportion of elapsed time out of the rate propagation time
primaryReserveWeight = uint32(weightedAverageIntegers(
primaryReserveWeight, externalPrimaryReserveWeight,
elapsedTime, externalRatePropagationTime));
return (primaryReserveWeight, externalPrimaryReserveWeight);
}
/**
* @dev returns the current rate for add/remove liquidity rebalancing
* only used to circumvent the `stack too deep` compiler error
*
* @return effective rate
*/
function rebalanceRate() private view returns (Fraction memory) {
// if one of the balances is 0, return the external rate
if (reserves[primaryReserveToken].balance == 0 || reserves[secondaryReserveToken].balance == 0) {
Fraction memory externalRate;
(externalRate.n, externalRate.d) = priceOracle.latestRate(primaryReserveToken, secondaryReserveToken);
return externalRate;
}
// return the rate based on the current rate
return tokensRate(primaryReserveToken, secondaryReserveToken, 0, 0);
}
/**
* @dev updates the reserve weights based on the external rate
*/
function rebalance() private {
// get the external rate
Fraction memory externalRate;
(externalRate.n, externalRate.d) = priceOracle.latestRate(primaryReserveToken, secondaryReserveToken);
// rebalance the weights based on the external rate
rebalance(externalRate);
}
/**
* @dev updates the reserve weights based on the given rate
*
* @param _rate rate of 1 primary token in secondary tokens
*/
function rebalance(Fraction memory _rate) private {
// get the new primary reserve weight
uint256 a = amplifiedBalance(primaryReserveToken).mul(_rate.n);
uint256 b = amplifiedBalance(secondaryReserveToken).mul(_rate.d);
(uint256 x, uint256 y) = normalizedRatio(a, b, PPM_RESOLUTION);
// update the reserve weights with the new values
reserves[primaryReserveToken].weight = uint32(x);
reserves[secondaryReserveToken].weight = uint32(y);
}
/**
* @dev returns the amplified balance of a given reserve token
* this version skips the input validation (gas optimization)
*
* @param _reserveToken reserve token address
*
* @return amplified balance
*/
function amplifiedBalance(IERC20Token _reserveToken) internal view returns (uint256) {
return stakedBalances[_reserveToken].mul(amplificationFactor - 1).add(reserves[_reserveToken].balance);
}
/**
* @dev returns the effective primary reserve weight based on the staked balance, current balance and given rate
*
* @param _rate rate of 1 primary token in secondary tokens
*
* @return primary reserve weight
*/
function primaryWeightFromRate(Fraction memory _rate) private view returns (uint32) {
uint256 a = stakedBalances[primaryReserveToken].mul(_rate.n);
uint256 b = stakedBalances[secondaryReserveToken].mul(_rate.d);
(uint256 x,) = normalizedRatio(a, b, PPM_RESOLUTION);
return uint32(x);
}
/**
* @dev returns the effective rate based on the staked balance, current balance and given primary reserve weight
*
* @param _primaryReserveWeight primary reserve weight
*
* @return effective rate of 1 primary token in secondary tokens
*/
function rateFromPrimaryWeight(uint32 _primaryReserveWeight) private view returns (Fraction memory) {
uint256 n = stakedBalances[secondaryReserveToken].mul(_primaryReserveWeight);
uint256 d = stakedBalances[primaryReserveToken].mul(inverseWeight(_primaryReserveWeight));
(n, d) = reducedRatio(n, d, MAX_RATE_FACTOR_LOWER_BOUND);
return Fraction(n, d);
}
/**
* @dev calculates and returns the rate between two reserve tokens
*
* @param _token1 contract address of the token to calculate the rate of one unit of
* @param _token2 contract address of the token to calculate the rate of one `_token1` unit in
* @param _token1Weight reserve weight of token1
* @param _token2Weight reserve weight of token2
*
* @return rate
*/
function tokensRate(IERC20Token _token1, IERC20Token _token2, uint32 _token1Weight, uint32 _token2Weight) private view returns (Fraction memory) {
if (_token1Weight == 0) {
_token1Weight = reserves[_token1].weight;
}
if (_token2Weight == 0) {
_token2Weight = inverseWeight(_token1Weight);
}
uint256 n = amplifiedBalance(_token2).mul(_token1Weight);
uint256 d = amplifiedBalance(_token1).mul(_token2Weight);
(n, d) = reducedRatio(n, d, MAX_RATE_FACTOR_LOWER_BOUND);
return Fraction(n, d);
}
/**
* @dev dispatches rate events for both reserve tokens and for the target pool token
* only used to circumvent the `stack too deep` compiler error
*
* @param _sourceToken contract address of the source reserve token
* @param _targetToken contract address of the target reserve token
* @param _sourceWeight source reserve token weight
* @param _targetWeight target reserve token weight
*/
function dispatchRateEvents(IERC20Token _sourceToken, IERC20Token _targetToken, uint32 _sourceWeight, uint32 _targetWeight) private {
dispatchTokenRateUpdateEvent(_sourceToken, _targetToken, _sourceWeight, _targetWeight);
// dispatch the `TokenRateUpdate` event for the pool token
// the target reserve pool token rate is the only one that's affected
// by conversions since conversion fees are applied to the target reserve
ISmartToken targetPoolToken = poolToken(_targetToken);
uint256 targetPoolTokenSupply = targetPoolToken.totalSupply();
dispatchPoolTokenRateUpdateEvent(targetPoolToken, targetPoolTokenSupply, _targetToken);
}
/**
* @dev dispatches token rate update event
* only used to circumvent the `stack too deep` compiler error
*
* @param _token1 contract address of the token to calculate the rate of one unit of
* @param _token2 contract address of the token to calculate the rate of one `_token1` unit in
* @param _token1Weight reserve weight of token1
* @param _token2Weight reserve weight of token2
*/
function dispatchTokenRateUpdateEvent(IERC20Token _token1, IERC20Token _token2, uint32 _token1Weight, uint32 _token2Weight) private {
// dispatch token rate update event
Fraction memory rate = tokensRate(_token1, _token2, _token1Weight, _token2Weight);
emit TokenRateUpdate(_token1, _token2, rate.n, rate.d);
}
/**
* @dev dispatches the `TokenRateUpdate` for the pool token
* only used to circumvent the `stack too deep` compiler error
*
* @param _poolToken address of the pool token
* @param _poolTokenSupply total pool token supply
* @param _reserveToken address of the reserve token
*/
function dispatchPoolTokenRateUpdateEvent(ISmartToken _poolToken, uint256 _poolTokenSupply, IERC20Token _reserveToken) private {
emit TokenRateUpdate(_poolToken, _reserveToken, stakedBalances[_reserveToken], _poolTokenSupply);
}
// utilities
/**
* @dev returns the inverse weight for a given weight
*
* @param _weight reserve token weight
*
* @return reserve weight
*/
function inverseWeight(uint32 _weight) internal pure returns (uint32) {
return PPM_RESOLUTION - _weight;
}
/**
* @dev returns the current time
*/
function time() internal virtual view returns (uint256) {
return now;
}
/**
* @dev computes "scale * a / (a + b)" and "scale * b / (a + b)".
*/
function normalizedRatio(uint256 _a, uint256 _b, uint256 _scale) internal pure returns (uint256, uint256) {
if (_a == _b)
return (_scale / 2, _scale / 2);
if (_a < _b)
return accurateRatio(_a, _b, _scale);
(uint256 y, uint256 x) = accurateRatio(_b, _a, _scale);
return (x, y);
}
/**
* @dev computes "scale * a / (a + b)" and "scale * b / (a + b)", assuming that "a < b".
*/
function accurateRatio(uint256 _a, uint256 _b, uint256 _scale) internal pure returns (uint256, uint256) {
uint256 maxVal = uint256(-1) / _scale;
if (_a > maxVal) {
uint256 c = _a / (maxVal + 1) + 1;
_a /= c;
_b /= c;
}
uint256 x = roundDiv(_a * _scale, _a.add(_b));
uint256 y = _scale - x;
return (x, y);
}
/**
* @dev computes a reduced-scalar ratio
*
* @param _n ratio numerator
* @param _d ratio denominator
* @param _max maximum desired scalar
*
* @return ratio's numerator and denominator
*/
function reducedRatio(uint256 _n, uint256 _d, uint256 _max) internal pure returns (uint256, uint256) {
if (_n > _max || _d > _max)
return normalizedRatio(_n, _d, _max);
return (_n, _d);
}
/**
* @dev computes the nearest integer to a given quotient without overflowing or underflowing.
*/
function roundDiv(uint256 _n, uint256 _d) internal pure returns (uint256) {
return _n / _d + _n % _d / (_d - _d / 2);
}
/**
* @dev calculates the weighted-average of two integers
*
* @param _x first integer
* @param _y second integer
* @param _n factor numerator
* @param _d factor denominator
*
* @return the weighted-average of the given integers
*/
function weightedAverageIntegers(uint256 _x, uint256 _y, uint256 _n, uint256 _d) internal pure returns (uint256) {
return _x.mul(_d).add(_y.mul(_n)).sub(_x.mul(_n)).div(_d);
}
/**
* @dev compares two rates
*
* @param _rate1 first rate to compare
* @param _rate2 second rate to compare
*
* @return `-1` if `_rate1` is lower than `_rate2`, `1` if `_rate1` is higher than `_rate2`, 0 if the rates are identical
*/
function compareRates(Fraction memory _rate1, Fraction memory _rate2) internal pure returns (int8) {
uint256 x = _rate1.n.mul(_rate2.d);
uint256 y = _rate2.n.mul(_rate1.d);
if (x < y)
return -1;
if (x > y)
return 1;
return 0;
}
}
|
computes "scale a / (a + b)" and "scale b / (a + b)", assuming that "a < b"./
|
function accurateRatio(uint256 _a, uint256 _b, uint256 _scale) internal pure returns (uint256, uint256) {
uint256 maxVal = uint256(-1) / _scale;
if (_a > maxVal) {
uint256 c = _a / (maxVal + 1) + 1;
_a /= c;
_b /= c;
}
uint256 x = roundDiv(_a * _scale, _a.add(_b));
uint256 y = _scale - x;
return (x, y);
}
| 1,066,863 |
./partial_match/1/0xAE517e17844C09F2eEdf382DB0e7943C4C78C7F0/sources/contracts/vaults/BaseVaults/RibbonThetaVault.sol
|
Withdraws the assets on the vault using the outstanding `DepositReceipt.amount` amount is the amount to withdraw/ Subtraction underflow checks already ensure it is smaller than uint104
|
function withdrawInstantly(uint256 amount) external nonReentrant {
Vault.DepositReceipt storage depositReceipt =
depositReceipts[msg.sender];
uint256 currentRound = vaultState.round;
require(amount > 0, "!amount");
require(depositReceipt.round == currentRound, "Invalid round");
uint256 receiptAmount = depositReceipt.amount;
require(receiptAmount >= amount, "Exceed amount");
depositReceipt.amount = uint104(receiptAmount.sub(amount));
vaultState.totalPending = uint128(
uint256(vaultState.totalPending).sub(amount)
);
emit InstantWithdraw(msg.sender, amount, currentRound);
transferAsset(msg.sender, amount);
}
| 4,225,203 |
//Address: 0x6a20d74106f28ad19c60115917ff363ad71f525f
//Contract name: BW
//Balance: 2.172825 Ether
//Verification Date: 6/7/2018
//Transacion Count: 958
// CODE STARTS HERE
pragma solidity ^0.4.21;
library BWUtility {
// -------- UTILITY FUNCTIONS ----------
// Return next higher even _multiple for _amount parameter (e.g used to round up to even finneys).
function ceil(uint _amount, uint _multiple) pure public returns (uint) {
return ((_amount + _multiple - 1) / _multiple) * _multiple;
}
// Checks if two coordinates are adjacent:
// xxx
// xox
// xxx
// All x (_x2, _xy2) are adjacent to o (_x1, _y1) in this ascii image.
// Adjacency does not wrapp around map edges so if y2 = 255 and y1 = 0 then they are not ajacent
function isAdjacent(uint8 _x1, uint8 _y1, uint8 _x2, uint8 _y2) pure public returns (bool) {
return ((_x1 == _x2 && (_y2 - _y1 == 1 || _y1 - _y2 == 1))) || // Same column
((_y1 == _y2 && (_x2 - _x1 == 1 || _x1 - _x2 == 1))) || // Same row
((_x2 - _x1 == 1 && (_y2 - _y1 == 1 || _y1 - _y2 == 1))) || // Right upper or lower diagonal
((_x1 - _x2 == 1 && (_y2 - _y1 == 1 || _y1 - _y2 == 1))); // Left upper or lower diagonal
}
// Converts (x, y) to tileId xy
function toTileId(uint8 _x, uint8 _y) pure public returns (uint16) {
return uint16(_x) << 8 | uint16(_y);
}
// Converts _tileId to (x, y)
function fromTileId(uint16 _tileId) pure public returns (uint8, uint8) {
uint8 y = uint8(_tileId);
uint8 x = uint8(_tileId >> 8);
return (x, y);
}
function getBoostFromTile(address _claimer, address _attacker, address _defender, uint _blockValue) pure public returns (uint, uint) {
if (_claimer == _attacker) {
return (_blockValue, 0);
} else if (_claimer == _defender) {
return (0, _blockValue);
}
}
}
interface ERC20I {
function transfer(address _recipient, uint256 _amount) external returns (bool);
function balanceOf(address _holder) external view returns (uint256);
}
contract BWService {
using SafeMath for uint256;
address private owner;
address private bw;
address private bwMarket;
BWData private bwData;
uint private seed = 42;
uint private WITHDRAW_FEE = 5; // 5%
uint private ATTACK_FEE = 5; // 5%
uint private ATTACK_BOOST_CAP = 300; // 300%
uint private DEFEND_BOOST_CAP = 300; // 300%
uint private ATTACK_BOOST_MULTIPLIER = 100; // 100%
uint private DEFEND_BOOST_MULTIPLIER = 100; // 100%
mapping (uint16 => address) private localGames;
modifier isOwner {
if (msg.sender != owner) {
revert();
}
_;
}
modifier isValidCaller {
if (msg.sender != bw && msg.sender != bwMarket) {
revert();
}
_;
}
event TileClaimed(uint16 tileId, address newClaimer, uint priceInWei, uint creationTime);
event TileFortified(uint16 tileId, address claimer, uint addedValueInWei, uint priceInWei, uint fortifyTime); // Sent when a user fortifies an existing claim by bumping its value.
event TileAttackedSuccessfully(uint16 tileId, address attacker, uint attackAmount, uint totalAttackAmount, address defender, uint defendAmount, uint totalDefendAmount, uint attackRoll, uint attackTime); // Sent when a user successfully attacks a tile.
event TileDefendedSuccessfully(uint16 tileId, address attacker, uint attackAmount, uint totalAttackAmount, address defender, uint defendAmount, uint totalDefendAmount, uint attackRoll, uint defendTime); // Sent when a user successfully defends a tile when attacked.
event BlockValueMoved(uint16 sourceTileId, uint16 destTileId, address owner, uint movedBlockValue, uint postSourceValue, uint postDestValue, uint moveTime); // Sent when a user buys a tile from another user, by accepting a tile offer
event UserBattleValueUpdated(address userAddress, uint battleValue, bool isWithdraw);
// Constructor.
constructor(address _bwData) public {
bwData = BWData(_bwData);
owner = msg.sender;
}
// Can't send funds straight to this contract. Avoid people sending by mistake.
function () payable public {
revert();
}
// OWNER-ONLY FUNCTIONS
function kill() public isOwner {
selfdestruct(owner);
}
function setValidBwCaller(address _bw) public isOwner {
bw = _bw;
}
function setValidBwMarketCaller(address _bwMarket) public isOwner {
bwMarket = _bwMarket;
}
function setWithdrawFee(uint _feePercentage) public isOwner {
WITHDRAW_FEE = _feePercentage;
}
function setAttackFee(uint _feePercentage) public isOwner {
ATTACK_FEE = _feePercentage;
}
function setAttackBoostMultipler(uint _multiplierPercentage) public isOwner {
ATTACK_BOOST_MULTIPLIER = _multiplierPercentage;
}
function setDefendBoostMultiplier(uint _multiplierPercentage) public isOwner {
DEFEND_BOOST_MULTIPLIER = _multiplierPercentage;
}
function setAttackBoostCap(uint _capPercentage) public isOwner {
ATTACK_BOOST_CAP = _capPercentage;
}
function setDefendBoostCap(uint _capPercentage) public isOwner {
DEFEND_BOOST_CAP = _capPercentage;
}
// TILE-RELATED FUNCTIONS
// This function claims multiple previously unclaimed tiles in a single transaction.
// The value assigned to each tile is the msg.value divided by the number of tiles claimed.
// The msg.value is required to be an even multiple of the number of tiles claimed.
function storeInitialClaim(address _msgSender, uint16[] _claimedTileIds, uint _claimAmount, bool _useBattleValue) public isValidCaller {
uint tileCount = _claimedTileIds.length;
require(tileCount > 0);
require(_claimAmount >= 1 finney * tileCount); // ensure enough funds paid for all tiles
require(_claimAmount % tileCount == 0); // ensure payment is an even multiple of number of tiles claimed
uint valuePerBlockInWei = _claimAmount.div(tileCount); // Due to requires above this is guaranteed to be an even number
require(valuePerBlockInWei >= 5 finney);
if (_useBattleValue) {
subUserBattleValue(_msgSender, _claimAmount, false);
}
addGlobalBlockValueBalance(_claimAmount);
uint16 tileId;
bool isNewTile;
for (uint16 i = 0; i < tileCount; i++) {
tileId = _claimedTileIds[i];
isNewTile = bwData.isNewTile(tileId); // Is length 0 if first time purchased
require(isNewTile); // Can only claim previously unclaimed tiles.
// Send claim event
emit TileClaimed(tileId, _msgSender, valuePerBlockInWei, block.timestamp);
// Update contract state with new tile ownership.
bwData.storeClaim(tileId, _msgSender, valuePerBlockInWei);
}
}
function fortifyClaims(address _msgSender, uint16[] _claimedTileIds, uint _fortifyAmount, bool _useBattleValue) public isValidCaller {
uint tileCount = _claimedTileIds.length;
require(tileCount > 0);
address(this).balance.add(_fortifyAmount); // prevent overflow with SafeMath
require(_fortifyAmount % tileCount == 0); // ensure payment is an even multiple of number of tiles fortified
uint addedValuePerTileInWei = _fortifyAmount.div(tileCount); // Due to requires above this is guaranteed to be an even number
require(_fortifyAmount >= 1 finney * tileCount); // ensure enough funds paid for all tiles
address claimer;
uint blockValue;
for (uint16 i = 0; i < tileCount; i++) {
(claimer, blockValue) = bwData.getTileClaimerAndBlockValue(_claimedTileIds[i]);
require(claimer != 0); // Can't do this on never-owned tiles
require(claimer == _msgSender); // Only current claimer can fortify claim
if (_useBattleValue) {
subUserBattleValue(_msgSender, addedValuePerTileInWei, false);
}
fortifyClaim(_msgSender, _claimedTileIds[i], addedValuePerTileInWei);
}
}
function fortifyClaim(address _msgSender, uint16 _claimedTileId, uint _fortifyAmount) private {
uint blockValue;
uint sellPrice;
(blockValue, sellPrice) = bwData.getCurrentBlockValueAndSellPriceForTile(_claimedTileId);
uint updatedBlockValue = blockValue.add(_fortifyAmount);
// Send fortify event
emit TileFortified(_claimedTileId, _msgSender, _fortifyAmount, updatedBlockValue, block.timestamp);
// Update tile value. The tile has been fortified by bumping up its value.
bwData.updateTileBlockValue(_claimedTileId, updatedBlockValue);
// Track addition to global block value
addGlobalBlockValueBalance(_fortifyAmount);
}
// Return a pseudo random number between lower and upper bounds
// given the number of previous blocks it should hash.
// Random function copied from https://github.com/axiomzen/eth-random/blob/master/contracts/Random.sol.
// Changed sha3 to keccak256, then modified.
// Changed random range from uint64 to uint (=uint256).
function random(uint _upper) private returns (uint) {
seed = uint(keccak256(blockhash(block.number - 1), block.coinbase, block.timestamp, seed, address(0x3f5CE5FBFe3E9af3971dD833D26bA9b5C936f0bE).balance));
return seed % _upper;
}
// A user tries to claim a tile that's already owned by another user. A battle ensues.
// A random roll is done with % based on attacking vs defending amounts.
function attackTile(address _msgSender, uint16 _tileId, uint _attackAmount, bool _useBattleValue) public isValidCaller {
require(_attackAmount >= 1 finney); // Don't allow attacking with less than one base tile price.
require(_attackAmount % 1 finney == 0);
address claimer;
uint blockValue;
(claimer, blockValue) = bwData.getTileClaimerAndBlockValue(_tileId);
require(claimer != 0); // Can't do this on never-owned tiles
require(claimer != _msgSender); // Can't attack one's own tiles
require(claimer != owner); // Can't attack owner's tiles because it is used for raffle.
// Calculate boosted amounts for attacker and defender
// The base attack amount is sent in the by the user.
// The base defend amount is the attacked tile's current blockValue.
uint attackBoost;
uint defendBoost;
(attackBoost, defendBoost) = bwData.calculateBattleBoost(_tileId, _msgSender, claimer);
// Adjust boost to optimize game strategy
attackBoost = attackBoost.mul(ATTACK_BOOST_MULTIPLIER).div(100);
defendBoost = defendBoost.mul(DEFEND_BOOST_MULTIPLIER).div(100);
// Cap the boost to minimize its impact (prevents whales somehow)
if (attackBoost > _attackAmount.mul(ATTACK_BOOST_CAP).div(100)) {
attackBoost = _attackAmount.mul(ATTACK_BOOST_CAP).div(100);
}
if (defendBoost > blockValue.mul(DEFEND_BOOST_CAP).div(100)) {
defendBoost = blockValue.mul(DEFEND_BOOST_CAP).div(100);
}
uint totalAttackAmount = _attackAmount.add(attackBoost);
uint totalDefendAmount = blockValue.add(defendBoost);
// Verify that attack odds are within allowed range.
require(totalAttackAmount.div(10) <= totalDefendAmount); // Disallow attacks with more than 1000% of defendAmount
require(totalAttackAmount >= totalDefendAmount.div(10)); // Disallow attacks with less than 10% of defendAmount
uint attackFeeAmount = _attackAmount.mul(ATTACK_FEE).div(100);
uint attackAmountAfterFee = _attackAmount.sub(attackFeeAmount);
updateFeeBalance(attackFeeAmount);
// The battle considers boosts.
uint attackRoll = random(totalAttackAmount.add(totalDefendAmount)); // This is where the excitement happens!
//gas cost of attack branch is higher than denfense branch solving MSB1
if (attackRoll > totalDefendAmount) {
// Change block owner but keep same block value (attacker got battlevalue instead)
bwData.setClaimerForTile(_tileId, _msgSender);
// Tile successfully attacked!
if (_useBattleValue) {
// Withdraw followed by deposit of same amount to prevent MSB1
addUserBattleValue(_msgSender, attackAmountAfterFee); // Don't include boost here!
subUserBattleValue(_msgSender, attackAmountAfterFee, false);
} else {
addUserBattleValue(_msgSender, attackAmountAfterFee); // Don't include boost here!
}
addUserBattleValue(claimer, 0);
bwData.updateTileTimeStamp(_tileId);
// Send update event
emit TileAttackedSuccessfully(_tileId, _msgSender, attackAmountAfterFee, totalAttackAmount, claimer, blockValue, totalDefendAmount, attackRoll, block.timestamp);
} else {
bwData.setClaimerForTile(_tileId, claimer); //should be old owner
// Tile successfully defended!
if (_useBattleValue) {
subUserBattleValue(_msgSender, attackAmountAfterFee, false); // Don't include boost here!
}
addUserBattleValue(claimer, attackAmountAfterFee); // Don't include boost here!
// Send update event
emit TileDefendedSuccessfully(_tileId, _msgSender, attackAmountAfterFee, totalAttackAmount, claimer, blockValue, totalDefendAmount, attackRoll, block.timestamp);
}
}
function updateFeeBalance(uint attackFeeAmount) private {
uint feeBalance = bwData.getFeeBalance();
feeBalance = feeBalance.add(attackFeeAmount);
bwData.setFeeBalance(feeBalance);
}
function moveBlockValue(address _msgSender, uint8 _xSource, uint8 _ySource, uint8 _xDest, uint8 _yDest, uint _moveAmount) public isValidCaller {
uint16 sourceTileId = BWUtility.toTileId(_xSource, _ySource);
uint16 destTileId = BWUtility.toTileId(_xDest, _yDest);
address sourceTileClaimer;
address destTileClaimer;
uint sourceTileBlockValue;
uint destTileBlockValue;
(sourceTileClaimer, sourceTileBlockValue) = bwData.getTileClaimerAndBlockValue(sourceTileId);
(destTileClaimer, destTileBlockValue) = bwData.getTileClaimerAndBlockValue(destTileId);
uint newBlockValue = sourceTileBlockValue.sub(_moveAmount);
// Must transfer the entire block value or leave at least 5
require(newBlockValue == 0 || newBlockValue >= 5 finney);
require(sourceTileClaimer == _msgSender);
require(destTileClaimer == _msgSender);
require(_moveAmount >= 1 finney); // Can't be less
require(_moveAmount % 1 finney == 0); // Move amount must be in multiples of 1 finney
// require(sourceTile.blockValue - _moveAmount >= BASE_TILE_PRICE_WEI); // Must always leave some at source
require(BWUtility.isAdjacent(_xSource, _ySource, _xDest, _yDest));
sourceTileBlockValue = sourceTileBlockValue.sub(_moveAmount);
destTileBlockValue = destTileBlockValue.add(_moveAmount);
// If ALL block value was moved away from the source tile, we lose our claim to it. It becomes ownerless.
if (sourceTileBlockValue == 0) {
bwData.deleteTile(sourceTileId);
} else {
bwData.updateTileBlockValue(sourceTileId, sourceTileBlockValue);
bwData.deleteOffer(sourceTileId); // Offer invalid since block value has changed
}
bwData.updateTileBlockValue(destTileId, destTileBlockValue);
bwData.deleteOffer(destTileId); // Offer invalid since block value has changed
emit BlockValueMoved(sourceTileId, destTileId, _msgSender, _moveAmount, sourceTileBlockValue, destTileBlockValue, block.timestamp);
}
function verifyAmount(address _msgSender, uint _msgValue, uint _amount, bool _useBattleValue) view public isValidCaller {
if (_useBattleValue) {
require(_msgValue == 0);
require(bwData.getUserBattleValue(_msgSender) >= _amount);
} else {
require(_amount == _msgValue);
}
}
function setLocalGame(uint16 _tileId, address localGameAddress) public isOwner {
localGames[_tileId] = localGameAddress;
}
function getLocalGame(uint16 _tileId) view public isValidCaller returns (address) {
return localGames[_tileId];
}
// BATTLE VALUE FUNCTIONS
function withdrawBattleValue(address msgSender, uint _battleValueInWei) public isValidCaller returns (uint) {
//require(_battleValueInWei % 1 finney == 0); // Must be divisible by 1 finney
uint fee = _battleValueInWei.mul(WITHDRAW_FEE).div(100); // Since we divide by 20 we can never create infinite fractions, so we'll always count in whole wei amounts.
uint amountToWithdraw = _battleValueInWei.sub(fee);
uint feeBalance = bwData.getFeeBalance();
feeBalance = feeBalance.add(fee);
bwData.setFeeBalance(feeBalance);
subUserBattleValue(msgSender, _battleValueInWei, true);
return amountToWithdraw;
}
function addUserBattleValue(address _userId, uint _amount) public isValidCaller {
uint userBattleValue = bwData.getUserBattleValue(_userId);
uint newBattleValue = userBattleValue.add(_amount);
bwData.setUserBattleValue(_userId, newBattleValue); // Don't include boost here!
emit UserBattleValueUpdated(_userId, newBattleValue, false);
}
function subUserBattleValue(address _userId, uint _amount, bool _isWithdraw) public isValidCaller {
uint userBattleValue = bwData.getUserBattleValue(_userId);
require(_amount <= userBattleValue); // Must be less than user's battle value - also implicitly checks that underflow isn't possible
uint newBattleValue = userBattleValue.sub(_amount);
bwData.setUserBattleValue(_userId, newBattleValue); // Don't include boost here!
emit UserBattleValueUpdated(_userId, newBattleValue, _isWithdraw);
}
function addGlobalBlockValueBalance(uint _amount) public isValidCaller {
// Track addition to global block value.
uint blockValueBalance = bwData.getBlockValueBalance();
bwData.setBlockValueBalance(blockValueBalance.add(_amount));
}
function subGlobalBlockValueBalance(uint _amount) public isValidCaller {
// Track addition to global block value.
uint blockValueBalance = bwData.getBlockValueBalance();
bwData.setBlockValueBalance(blockValueBalance.sub(_amount));
}
// Allow us to transfer out airdropped tokens if we ever receive any
function transferTokens(address _tokenAddress, address _recipient) public isOwner {
ERC20I token = ERC20I(_tokenAddress);
require(token.transfer(_recipient, token.balanceOf(this)));
}
}
contract BWData {
address public owner;
address private bwService;
address private bw;
address private bwMarket;
uint private blockValueBalance = 0;
uint private feeBalance = 0;
uint private BASE_TILE_PRICE_WEI = 1 finney; // 1 milli-ETH.
mapping (address => User) private users; // user address -> user information
mapping (uint16 => Tile) private tiles; // tileId -> list of TileClaims for that particular tile
// Info about the users = those who have purchased tiles.
struct User {
uint creationTime;
bool censored;
uint battleValue;
}
// Info about a tile ownership
struct Tile {
address claimer;
uint blockValue;
uint creationTime;
uint sellPrice; // If 0 -> not on marketplace. If > 0 -> on marketplace.
}
struct Boost {
uint8 numAttackBoosts;
uint8 numDefendBoosts;
uint attackBoost;
uint defendBoost;
}
constructor() public {
owner = msg.sender;
}
// Can't send funds straight to this contract. Avoid people sending by mistake.
function () payable public {
revert();
}
function kill() public isOwner {
selfdestruct(owner);
}
modifier isValidCaller {
if (msg.sender != bwService && msg.sender != bw && msg.sender != bwMarket) {
revert();
}
_;
}
modifier isOwner {
if (msg.sender != owner) {
revert();
}
_;
}
function setBwServiceValidCaller(address _bwService) public isOwner {
bwService = _bwService;
}
function setBwValidCaller(address _bw) public isOwner {
bw = _bw;
}
function setBwMarketValidCaller(address _bwMarket) public isOwner {
bwMarket = _bwMarket;
}
// ----------USER-RELATED GETTER FUNCTIONS------------
//function getUser(address _user) view public returns (bytes32) {
//BWUtility.User memory user = users[_user];
//require(user.creationTime != 0);
//return (user.creationTime, user.imageUrl, user.tag, user.email, user.homeUrl, user.creationTime, user.censored, user.battleValue);
//}
function addUser(address _msgSender) public isValidCaller {
User storage user = users[_msgSender];
require(user.creationTime == 0);
user.creationTime = block.timestamp;
}
function hasUser(address _user) view public isValidCaller returns (bool) {
return users[_user].creationTime != 0;
}
// ----------TILE-RELATED GETTER FUNCTIONS------------
function getTile(uint16 _tileId) view public isValidCaller returns (address, uint, uint, uint) {
Tile storage currentTile = tiles[_tileId];
return (currentTile.claimer, currentTile.blockValue, currentTile.creationTime, currentTile.sellPrice);
}
function getTileClaimerAndBlockValue(uint16 _tileId) view public isValidCaller returns (address, uint) {
Tile storage currentTile = tiles[_tileId];
return (currentTile.claimer, currentTile.blockValue);
}
function isNewTile(uint16 _tileId) view public isValidCaller returns (bool) {
Tile storage currentTile = tiles[_tileId];
return currentTile.creationTime == 0;
}
function storeClaim(uint16 _tileId, address _claimer, uint _blockValue) public isValidCaller {
tiles[_tileId] = Tile(_claimer, _blockValue, block.timestamp, 0);
}
function updateTileBlockValue(uint16 _tileId, uint _blockValue) public isValidCaller {
tiles[_tileId].blockValue = _blockValue;
}
function setClaimerForTile(uint16 _tileId, address _claimer) public isValidCaller {
tiles[_tileId].claimer = _claimer;
}
function updateTileTimeStamp(uint16 _tileId) public isValidCaller {
tiles[_tileId].creationTime = block.timestamp;
}
function getCurrentClaimerForTile(uint16 _tileId) view public isValidCaller returns (address) {
Tile storage currentTile = tiles[_tileId];
if (currentTile.creationTime == 0) {
return 0;
}
return currentTile.claimer;
}
function getCurrentBlockValueAndSellPriceForTile(uint16 _tileId) view public isValidCaller returns (uint, uint) {
Tile storage currentTile = tiles[_tileId];
if (currentTile.creationTime == 0) {
return (0, 0);
}
return (currentTile.blockValue, currentTile.sellPrice);
}
function getBlockValueBalance() view public isValidCaller returns (uint){
return blockValueBalance;
}
function setBlockValueBalance(uint _blockValueBalance) public isValidCaller {
blockValueBalance = _blockValueBalance;
}
function getFeeBalance() view public isValidCaller returns (uint) {
return feeBalance;
}
function setFeeBalance(uint _feeBalance) public isValidCaller {
feeBalance = _feeBalance;
}
function getUserBattleValue(address _userId) view public isValidCaller returns (uint) {
return users[_userId].battleValue;
}
function setUserBattleValue(address _userId, uint _battleValue) public isValidCaller {
users[_userId].battleValue = _battleValue;
}
function verifyAmount(address _msgSender, uint _msgValue, uint _amount, bool _useBattleValue) view public isValidCaller {
User storage user = users[_msgSender];
require(user.creationTime != 0);
if (_useBattleValue) {
require(_msgValue == 0);
require(user.battleValue >= _amount);
} else {
require(_amount == _msgValue);
}
}
function addBoostFromTile(Tile _tile, address _attacker, address _defender, Boost memory _boost) pure private {
if (_tile.claimer == _attacker) {
require(_boost.attackBoost + _tile.blockValue >= _tile.blockValue); // prevent overflow
_boost.attackBoost += _tile.blockValue;
_boost.numAttackBoosts += 1;
} else if (_tile.claimer == _defender) {
require(_boost.defendBoost + _tile.blockValue >= _tile.blockValue); // prevent overflow
_boost.defendBoost += _tile.blockValue;
_boost.numDefendBoosts += 1;
}
}
function calculateBattleBoost(uint16 _tileId, address _attacker, address _defender) view public isValidCaller returns (uint, uint) {
uint8 x;
uint8 y;
(x, y) = BWUtility.fromTileId(_tileId);
Boost memory boost = Boost(0, 0, 0, 0);
// We overflow x, y on purpose here if x or y is 0 or 255 - the map overflows and so should adjacency.
// Go through all adjacent tiles to (x, y).
if (y != 255) {
if (x != 255) {
addBoostFromTile(tiles[BWUtility.toTileId(x+1, y+1)], _attacker, _defender, boost);
}
addBoostFromTile(tiles[BWUtility.toTileId(x, y+1)], _attacker, _defender, boost);
if (x != 0) {
addBoostFromTile(tiles[BWUtility.toTileId(x-1, y+1)], _attacker, _defender, boost);
}
}
if (x != 255) {
addBoostFromTile(tiles[BWUtility.toTileId(x+1, y)], _attacker, _defender, boost);
}
if (x != 0) {
addBoostFromTile(tiles[BWUtility.toTileId(x-1, y)], _attacker, _defender, boost);
}
if (y != 0) {
if(x != 255) {
addBoostFromTile(tiles[BWUtility.toTileId(x+1, y-1)], _attacker, _defender, boost);
}
addBoostFromTile(tiles[BWUtility.toTileId(x, y-1)], _attacker, _defender, boost);
if(x != 0) {
addBoostFromTile(tiles[BWUtility.toTileId(x-1, y-1)], _attacker, _defender, boost);
}
}
// The benefit of boosts is multiplicative (quadratic):
// - More boost tiles gives a higher total blockValue (the sum of the adjacent tiles)
// - More boost tiles give a higher multiple of that total blockValue that can be used (10% per adjacent tie)
// Example:
// A) I boost attack with 1 single tile worth 10 finney
// -> Total boost is 10 * 1 / 10 = 1 finney
// B) I boost attack with 3 tiles worth 1 finney each
// -> Total boost is (1+1+1) * 3 / 10 = 0.9 finney
// C) I boost attack with 8 tiles worth 2 finney each
// -> Total boost is (2+2+2+2+2+2+2+2) * 8 / 10 = 14.4 finney
// D) I boost attack with 3 tiles of 1, 5 and 10 finney respectively
// -> Total boost is (ss1+5+10) * 3 / 10 = 4.8 finney
// This division by 10 can't create fractions since our uint is wei, and we can't have overflow from the multiplication
// We do allow fractions of finney here since the boosted values aren't stored anywhere, only used for attack rolls and sent in events
boost.attackBoost = (boost.attackBoost / 10 * boost.numAttackBoosts);
boost.defendBoost = (boost.defendBoost / 10 * boost.numDefendBoosts);
return (boost.attackBoost, boost.defendBoost);
}
function censorUser(address _userAddress, bool _censored) public isValidCaller {
User storage user = users[_userAddress];
require(user.creationTime != 0);
user.censored = _censored;
}
function deleteTile(uint16 _tileId) public isValidCaller {
delete tiles[_tileId];
}
function setSellPrice(uint16 _tileId, uint _sellPrice) public isValidCaller {
tiles[_tileId].sellPrice = _sellPrice; //testrpc cannot estimate gas when delete is used.
}
function deleteOffer(uint16 _tileId) public isValidCaller {
tiles[_tileId].sellPrice = 0; //testrpc cannot estimate gas when delete is used.
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
/**
* Copyright 2018 Block Wars Team
*
*/
interface LocalGameI {
function getBountyBalance() view external returns (uint);
function getTimeLeftToNextCollect(address _claimer, uint _latestClaimTime) view external returns (uint);
function collectBounty(address _msgSender, uint _latestClaimTime, uint _amount) external returns (uint);
}
/*
* @title ERC721 interface
*/
contract ERC721 {
/// @dev This emits when ownership of any NFT changes by any mechanism.
/// This event emits when NFTs are created (`from` == 0) and destroyed
/// (`to` == 0). Exception: during contract creation, any number of NFTs
/// may be created and assigned without emitting Transfer. At the time of
/// any transfer, the approved address for that NFT (if any) is reset to none.
//event Transfer(address indexed _from, address indexed _to, uint256 _tokenId);
/// @dev This emits when the approved address for an NFT is changed or
/// reaffirmed. The zero address indicates there is no approved address.
/// When a Transfer event emits, this also indicates that the approved
/// address for that NFT (if any) is reset to none.
//event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId);
/// @dev This emits when an operator is enabled or disabled for an owner.
/// The operator can manage all NFTs of the owner.
//event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
/// @notice Count all NFTs assigned to an owner
/// @dev NFTs assigned to the zero address are considered invalid, and this
/// function throws for queries about the zero address.
/// @param _owner An address for whom to query the balance
/// @return The number of NFTs owned by `_owner`, possibly zero
function balanceOf(address _owner) external view returns (uint256);
/// @notice Find the owner of an NFT
/// @param _tokenId The identifier for an NFT
/// @dev NFTs assigned to zero address are considered invalid, and queries
/// about them do throw.
/// @return The address of the owner of the NFT
function ownerOf(uint256 _tokenId) external view returns (address);
/// @notice Transfers the ownership of an NFT from one address to another address
/// @dev Throws unless `msg.sender` is the current owner, an authorized
/// operator, or the approved address for this NFT. Throws if `_from` is
/// not the current owner. Throws if `_to` is the zero address. Throws if
/// `_tokenId` is not a valid NFT. When transfer is complete, this function
/// checks if `_to` is a smart contract (code size > 0). If so, it calls
/// `onERC721Received` on `_to` and throws if the return value is not
/// `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`.
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenId The NFT to transfer
/// @param data Additional data with no specified format, sent in call to `_to`
//function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data) external payable;
/// @notice Transfers the ownership of an NFT from one address to another address
/// @dev This works identically to the other function with an extra data parameter,
/// except this function just sets data to ""
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenId The NFT to transfer
function safeTransferFrom(address _from, address _to, uint256 _tokenId) external payable;
/// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE
/// TO CONFIRM THAT `_to` IS CAPABLE OF RECEIVING NFTS OR ELSE
/// THEY MAY BE PERMANENTLY LOST
/// @dev Throws unless `msg.sender` is the current owner, an authorized
/// operator, or the approved address for this NFT. Throws if `_from` is
/// not the current owner. Throws if `_to` is the zero address. Throws if
/// `_tokenId` is not a valid NFT.
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenId The NFT to transfer
//function transferFrom(address _from, address _to, uint256 _tokenId) external payable;
/// @notice Set or reaffirm the approved address for an NFT
/// @dev The zero address indicates there is no approved address.
/// @dev Throws unless `msg.sender` is the current NFT owner, or an authorized
/// operator of the current owner.
/// @param _approved The new approved NFT controller
/// @param _tokenId The NFT to approve
//function approve(address _approved, uint256 _tokenId) external payable;
/// @notice Enable or disable approval for a third party ("operator") to manage
/// all of `msg.sender`'s assets.
/// @dev Emits the ApprovalForAll event
/// @param _operator Address to add to the set of authorized operators.
/// @param _approved True if the operators is approved, false to revoke approval
//function setApprovalForAll(address _operator, bool _approved) external;
/// @notice Get the approved address for a single NFT
/// @dev Throws if `_tokenId` is not a valid NFT
/// @param _tokenId The NFT to find the approved address for
/// @return The approved address for this NFT, or the zero address if there is none
//function getApproved(uint256 _tokenId) external view returns (address);
/// @notice Query if an address is an authorized operator for another address
/// @param _owner The address that owns the NFTs
/// @param _operator The address that acts on behalf of the owner
/// @return True if `_operator` is an approved operator for `_owner`, false otherwise
//function isApprovedForAll(address _owner, address _operator) external view returns (bool);
/// @notice Query if a contract implements an interface
/// @param interfaceID The interface identifier, as specified in ERC-165
/// @dev Interface identification is specified in ERC-165. This function
/// uses less than 30,000 gas.
/// @return `true` if the contract implements `interfaceID` and
/// `interfaceID` is not 0xffffffff, `false` otherwise
//function supportsInterface(bytes4 interfaceID) external view returns (bool);
}
contract BW {
using SafeMath for uint256;
address public owner;
BWService private bwService;
BWData private bwData;
bool public paused = false;
uint private BV_TO_BP_FEE = 5; // 5%
mapping (uint16 => Prize[]) private prizes; // Use mapping instead of array (key would be a unique priceId) - NO (we want to loop all prices)
struct Prize {
address token; // BWT or CryptoKiities (ERC721)
uint tokenId;
uint startTime; // To be able to add a price before the game starts
uint hodlPeriod; // Amount of seconds you have to own the tile before being able to claim this price. One block is ~15 sec.
}
event PrizeCreated(uint16 tileId, address token, uint tokenId, uint creationTime, uint startTime, uint hodlPeriod);
event PrizeRemoved(uint16 tileId, address token, uint tokenId, uint removeTime);
event PrizeClaimed(address token, uint tokenId);
// Add price (only BW owner can do this)
function addPrize(uint16 _tileId, address _token, uint _tokenId, uint _startTime, uint _hodlPeriod) public isOwner {
//startTime must be same or after block.timestamp
uint startTime = _startTime;
if(startTime < block.timestamp) {
startTime = block.timestamp;
}
// we could check if token exists with ownerOf function in interface,
// but if any erc721 token doesn't implement the function, this function would revert.
// also cheaper to not make an interface call
prizes[_tileId].push(Prize(_token, _tokenId, startTime, _hodlPeriod));
emit PrizeCreated(_tileId, _token, _tokenId, block.timestamp, startTime, _hodlPeriod);
}
// Remove price (only BW owner can do this)
function removePrize(uint16 _tileId, address _token, uint _tokenId) public isOwner {
Prize[] storage prizeArr = prizes[_tileId];
require(prizeArr.length > 0);
for(uint idx = 0; idx < prizeArr.length; ++idx) {
if(prizeArr[idx].tokenId == _tokenId && prizeArr[idx].token == _token) {
delete prizeArr[idx];
emit PrizeRemoved(_tileId, _token, _tokenId, block.timestamp);
}
}
}
// Add price (only BW owner can do this)
function claimPrize(address _tokenAddress, uint16 _tileId) public isNotPaused isNotContractCaller {
ERC721 token = ERC721(_tokenAddress);
Prize[] storage prizeArr = prizes[_tileId];
require(prizeArr.length > 0);
address claimer;
uint blockValue;
uint lastClaimTime;
uint sellPrice;
(claimer, blockValue, lastClaimTime, sellPrice) = bwData.getTile(_tileId);
require(lastClaimTime != 0 && claimer == msg.sender);
for(uint idx = 0; idx < prizeArr.length; ++idx) {
if(prizeArr[idx].startTime.add(prizeArr[idx].hodlPeriod) <= block.timestamp
&& lastClaimTime.add(prizeArr[idx].hodlPeriod) <= block.timestamp) {
uint tokenId = prizeArr[idx].tokenId;
address tokenOwner = token.ownerOf(tokenId);
delete prizeArr[idx];
token.safeTransferFrom(tokenOwner, msg.sender, tokenId); //Will revert if token does not exists
emit PrizeClaimed(_tokenAddress, tokenId);
}
}
}
modifier isOwner {
if (msg.sender != owner) {
revert();
}
_;
}
// Checks if entire game (except battle value withdraw) is paused or not.
modifier isNotPaused {
if (paused) {
revert();
}
_;
}
// Only allow wallets to call this function, not contracts.
modifier isNotContractCaller {
require(msg.sender == tx.origin);
_;
}
// All contract event types.
event UserCreated(address userAddress, bytes32 name, bytes imageUrl, bytes32 tag, bytes32 homeUrl, uint creationTime, address invitedBy);
event UserCensored(address userAddress, bool isCensored);
event TransferTileFromOwner(uint16 tileId, address seller, address buyer, uint acceptTime); // Sent when a user buys a tile from another user, by accepting a tile offer
event UserUpdated(address userAddress, bytes32 name, bytes imageUrl, bytes32 tag, bytes32 homeUrl, uint updateTime);
event TileRetreated(uint16 tileId, address owner, uint amount, uint newBlockValue, uint retreatTime);
event BountyCollected(uint tile, address userAddress, uint amount, uint amountCollected, uint collectedTime, uint latestClaimTime);
// BASIC CONTRACT FUNCTIONS
constructor(address _bwService, address _bwData) public {
bwService = BWService(_bwService);
bwData = BWData(_bwData);
owner = msg.sender;
}
// Can't send funds straight to this contract. Avoid people sending by mistake.
function () payable public isOwner {
}
// Allow a new user to claim one or more previously unclaimed tiles by paying Ether.
function claimTilesForNewUser(bytes32 _name, bytes _imageUrl, bytes32 _tag, bytes32 _homeUrl, uint16[] _claimedTileIds, address _invitedBy) payable public isNotPaused isNotContractCaller {
bwData.addUser(msg.sender);
emit UserCreated(msg.sender, _name, _imageUrl, _tag, _homeUrl, block.timestamp, _invitedBy);
bwService.storeInitialClaim(msg.sender, _claimedTileIds, msg.value, false);
}
// Allow an existing user to claim one or more previously unclaimed tiles by paying Ether.
function claimTilesForExistingUser(uint16[] _claimedTileIds, uint _claimAmount, bool _useBattleValue) payable public isNotPaused isNotContractCaller {
bwService.verifyAmount(msg.sender, msg.value, _claimAmount, _useBattleValue);
bwService.storeInitialClaim(msg.sender, _claimedTileIds, _claimAmount, _useBattleValue);
}
// Allow users to change name, image URL, tag and home URL. Not censored status or battle value though.
function updateUser(bytes32 _name, bytes _imageUrl, bytes32 _tag, bytes32 _homeUrl) public isNotPaused isNotContractCaller {
require(bwData.hasUser(msg.sender));
// All the updated values are stored in events only so there's no state to update on the contract here.
emit UserUpdated(msg.sender, _name, _imageUrl, _tag, _homeUrl, block.timestamp);
}
// This function fortifies multiple previously claimed tiles in a single transaction.
// The value assigned to each tile is the msg.value divided by the number of tiles fortified.
// The msg.value is required to be an even multiple of the number of tiles fortified.
// Only tiles owned by msg.sender can be fortified.
function fortifyClaims(uint16[] _claimedTileIds, uint _fortifyAmount, bool _useBattleValue) payable public isNotPaused isNotContractCaller {
bwService.verifyAmount(msg.sender, msg.value, _fortifyAmount, _useBattleValue);
bwService.fortifyClaims(msg.sender, _claimedTileIds, _fortifyAmount, _useBattleValue);
}
// A new user attacks a tile claimed by someone else, trying to make it theirs through battle.
function attackTileForNewUser(uint16 _tileId, bytes32 _name, bytes _imageUrl, bytes32 _tag, bytes32 _homeUrl, address _invitedBy) payable public isNotPaused isNotContractCaller {
bwData.addUser(msg.sender);
emit UserCreated(msg.sender, _name, _imageUrl, _tag, _homeUrl, block.timestamp, _invitedBy);
bwService.attackTile(msg.sender, _tileId, msg.value, false);
}
// An existing user attacks a tile claimed by someone else, trying to make it theirs through battle.
function attackTileForExistingUser(uint16 _tileId, uint _attackAmount, bool _useBattleValue) payable public isNotPaused isNotContractCaller {
bwService.verifyAmount(msg.sender, msg.value, _attackAmount, _useBattleValue);
bwService.attackTile(msg.sender, _tileId, _attackAmount, _useBattleValue);
}
// Move "army" = block value from one block to an adjacent block. Moving ALL value equates giving up ownership of the source tile.
function moveBlockValue(uint8 _xSource, uint8 _ySource, uint8 _xDest, uint8 _yDest, uint _moveAmount) public isNotPaused isNotContractCaller {
require(_moveAmount > 0);
bwService.moveBlockValue(msg.sender, _xSource, _ySource, _xDest, _yDest, _moveAmount);
}
// Allow users to withdraw battle value in Ether.
function withdrawBattleValue(uint _battleValueInWei) public isNotContractCaller {
require(_battleValueInWei > 0);
uint amountToWithdraw = bwService.withdrawBattleValue(msg.sender, _battleValueInWei);
msg.sender.transfer(amountToWithdraw);
}
// Transfer block value to battle points for free
function transferBlockValueToBattleValue(uint16 _tileId, uint _amount) public isNotContractCaller {
require(_amount > 0);
address claimer;
uint blockValue;
(claimer, blockValue) = bwData.getTileClaimerAndBlockValue(_tileId);
require(claimer == msg.sender);
uint newBlockValue = blockValue.sub(_amount);
// Must transfer the entire block value or leave at least 5
require(newBlockValue == 0 || newBlockValue >= 5 finney);
if(newBlockValue == 0) {
bwData.deleteTile(_tileId);
} else {
bwData.updateTileBlockValue(_tileId, newBlockValue);
bwData.deleteOffer(_tileId); // Offer invalid since block value has changed
}
uint fee = _amount.mul(BV_TO_BP_FEE).div(100);
uint userAmount = _amount.sub(fee);
uint feeBalance = bwData.getFeeBalance();
feeBalance = feeBalance.add(fee);
bwData.setFeeBalance(feeBalance);
bwService.addUserBattleValue(msg.sender, userAmount);
bwService.subGlobalBlockValueBalance(_amount);
emit TileRetreated(_tileId, msg.sender, _amount, newBlockValue, block.timestamp);
}
// -------- LOCAL GAME FUNCTIONS ----------
function getLocalBountyBalance(uint16 _tileId) view public isNotContractCaller returns (uint) {
address localGameAddress = bwService.getLocalGame(_tileId);
require(localGameAddress != 0);
LocalGameI localGame = LocalGameI(localGameAddress);
return localGame.getBountyBalance();
}
function getTimeLeftToNextLocalBountyCollect(uint16 _tileId) view public isNotContractCaller returns (uint) {
address localGameAddress = bwService.getLocalGame(_tileId);
require(localGameAddress != 0);
LocalGameI localGame = LocalGameI(localGameAddress);
address claimer;
uint blockValue;
uint latestClaimTime;
uint sellPrice;
(claimer, blockValue, latestClaimTime, sellPrice) = bwData.getTile(_tileId);
return localGame.getTimeLeftToNextCollect(claimer, latestClaimTime);
}
function collectLocalBounty(uint16 _tileId, uint _amount) public isNotContractCaller {
address localGameAddress = bwService.getLocalGame(_tileId);
require(localGameAddress != 0);
address claimer;
uint blockValue;
uint latestClaimTime;
uint sellPrice;
(claimer, blockValue, latestClaimTime, sellPrice) = bwData.getTile(_tileId);
require(latestClaimTime != 0 && claimer == msg.sender);
LocalGameI localGame = LocalGameI(localGameAddress);
uint amountCollected = localGame.collectBounty(msg.sender, latestClaimTime, _amount);
emit BountyCollected(_tileId, msg.sender, _amount, amountCollected, block.timestamp, latestClaimTime);
}
// -------- OWNER-ONLY FUNCTIONS ----------
// Only used by owner for raffle. Owner need name, address and picture from user.
// These users can then be given tiles by owner using transferTileFromOwner.
function createNewUser(bytes32 _name, bytes _imageUrl, bytes32 _tag, bytes32 _homeUrl, address _user) public isOwner {
bwData.addUser(_user);
emit UserCreated(_user, _name, _imageUrl, _tag, _homeUrl, block.timestamp, msg.sender); //check on client if invitedBy is owner.
}
// Allow updating censored status. Owner only. In case someone uploads offensive content.
// The contract owners reserve the right to apply censorship. This will mean that the
// name, tag or URL images might not be displayed for a censored user.
function censorUser(address _userAddress, bool _censored) public isOwner {
bwData.censorUser(_userAddress, _censored);
emit UserCensored(_userAddress, _censored);
}
// Pause the entire game, but let users keep withdrawing battle value
function setPaused(bool _paused) public isOwner {
paused = _paused;
}
function kill() public isOwner {
selfdestruct(owner);
}
function withdrawFee() public isOwner {
uint balance = address(this).balance;
uint amountToWithdraw = bwData.getFeeBalance();
if (balance < amountToWithdraw) { // Should never happen, but paranoia
amountToWithdraw = balance;
}
bwData.setFeeBalance(0);
owner.transfer(amountToWithdraw);
}
function getFee() view public isOwner returns (uint) {
return bwData.getFeeBalance();
}
function setBvToBpFee(uint _feePercentage) public isOwner {
BV_TO_BP_FEE = _feePercentage;
}
function depositBattleValue(address _user) payable public isOwner {
require(msg.value % 1 finney == 0); // Must be divisible by 1 finney
bwService.addUserBattleValue(_user, msg.value);
}
// The owner can transfer ownership of own tiles to other users, as prizes in competitions.
function transferTileFromOwner(uint16[] _tileIds, address _newOwner) public isOwner {
for(uint i = 0; i < _tileIds.length; ++i) {
uint16 tileId = _tileIds[i];
address claimer = bwData.getCurrentClaimerForTile(tileId);
require(claimer == owner);
bwData.setClaimerForTile(tileId, _newOwner);
emit TransferTileFromOwner(tileId, _newOwner, msg.sender, block.timestamp);
}
}
// Allow us to transfer out airdropped tokens if we ever receive any
function transferTokens(address _tokenAddress, address _recipient) public isOwner {
ERC20I token = ERC20I(_tokenAddress);
require(token.transfer(_recipient, token.balanceOf(this)));
}
}
|
Allow users to withdraw battle value in Ether.
|
function withdrawBattleValue(uint _battleValueInWei) public isNotContractCaller {
require(_battleValueInWei > 0);
uint amountToWithdraw = bwService.withdrawBattleValue(msg.sender, _battleValueInWei);
msg.sender.transfer(amountToWithdraw);
}
| 6,375,674 |
/* solhint-disable-next-line compiler-fixed */
pragma solidity ^0.4.23;
// Copyright 2017 OpenST Ltd.
//
// 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.
//
// ----------------------------------------------------------------------------
// Value chain: OpenSTValue
//
// http://www.simpletoken.org/
//
// ----------------------------------------------------------------------------
import "./SafeMath.sol";
import "./Hasher.sol";
import "./OpsManaged.sol";
import "./EIP20Interface.sol";
import "./CoreInterface.sol";
import "./ProtocolVersioned.sol";
// value chain contracts
import "./SimpleStake.sol";
import "./ProofLib.sol";
/// @title OpenSTValue - value staking contract for OpenST
contract OpenSTValue is OpsManaged, Hasher {
using SafeMath for uint256;
/*
* Events
*/
event UtilityTokenRegistered(bytes32 indexed _uuid, address indexed stake,
string _symbol, string _name, uint8 _decimals, uint256 _conversionRate, uint8 _conversionRateDecimals,
uint256 _chainIdUtility, address indexed _stakingAccount);
event StakingIntentDeclared(bytes32 indexed _uuid, address indexed _staker,
uint256 _stakerNonce, bytes32 _intentKeyHash, address _beneficiary, uint256 _amountST,
uint256 _amountUT, uint256 _unlockHeight, bytes32 _stakingIntentHash,
uint256 _chainIdUtility);
event ProcessedStake(bytes32 indexed _uuid, bytes32 indexed _stakingIntentHash,
address _stake, address _staker, uint256 _amountST, uint256 _amountUT, bytes32 _unlockSecret);
event RevertedStake(bytes32 indexed _uuid, bytes32 indexed _stakingIntentHash,
address _staker, uint256 _amountST, uint256 _amountUT);
event RedemptionIntentConfirmed(bytes32 indexed _uuid, bytes32 _redemptionIntentHash,
address _redeemer, address _beneficiary, uint256 _amountST, uint256 _amountUT, uint256 _expirationHeight);
event ProcessedUnstake(bytes32 indexed _uuid, bytes32 indexed _redemptionIntentHash,
address stake, address _redeemer, address _beneficiary, uint256 _amountST, bytes32 _unlockSecret);
event RevertedUnstake(bytes32 indexed _uuid, bytes32 indexed _redemptionIntentHash,
address _redeemer, address _beneficiary, uint256 _amountST);
/*
* Constants
*/
uint8 public constant TOKEN_DECIMALS = 18;
uint256 public constant DECIMALSFACTOR = 10**uint256(TOKEN_DECIMALS);
// 2 weeks in seconds
uint256 private constant TIME_TO_WAIT_LONG = 1209600;
// 1hour in seconds
uint256 private constant TIME_TO_WAIT_SHORT = 3600;
// indentified index position of redemptionIntents mapping in storage (in OpenSTUtility)
// positions 0-3 are occupied by public state variables in OpsManaged and Owned
// private constants do not occupy the storage of a contract
uint8 internal constant intentsMappingStorageIndexPosition = 4;
// storage for staking intent hash of active staking intents
mapping(bytes32 /* hashIntentKey */ => bytes32 /* stakingIntentHash */) public stakingIntents;
// register the active stakes and unstakes
mapping(bytes32 /* hashStakingIntent */ => Stake) public stakes;
mapping(uint256 /* chainIdUtility */ => CoreInterface) internal cores;
mapping(bytes32 /* uuid */ => UtilityToken) public utilityTokens;
/// nonce makes the staking process atomic across the two-phased process
/// and protects against replay attack on (un)staking proofs during the process.
/// On the value chain nonces need to strictly increase by one; on the utility
/// chain the nonce need to strictly increase (as one value chain can have multiple
/// utility chains)
mapping(address /* (un)staker */ => uint256) internal nonces;
mapping(bytes32 /* hashRedemptionIntent */ => Unstake) public unstakes;
/*
* Storage
*/
uint256 public chainIdValue;
EIP20Interface public valueToken;
address public registrar;
uint256 public blocksToWaitShort;
uint256 public blocksToWaitLong;
bytes32[] public uuids;
/*
* Structures
*/
struct UtilityToken {
string symbol;
string name;
uint256 conversionRate;
uint8 conversionRateDecimals;
uint8 decimals;
uint256 chainIdUtility;
SimpleStake simpleStake;
address stakingAccount;
}
struct Stake {
bytes32 uuid;
address staker;
address beneficiary;
uint256 nonce;
uint256 amountST;
uint256 amountUT;
uint256 unlockHeight;
bytes32 hashLock;
}
struct Unstake {
bytes32 uuid;
address redeemer;
address beneficiary;
uint256 amountST;
// @dev consider removal of amountUT
uint256 amountUT;
uint256 expirationHeight;
bytes32 hashLock;
}
/*
* Modifiers
*/
modifier onlyRegistrar() {
// for now keep unique registrar
require(msg.sender == registrar);
_;
}
constructor(
uint256 _chainIdValue,
EIP20Interface _eip20token,
address _registrar,
uint256 _valueChainBlockGenerationTime)
public
OpsManaged()
{
require(_chainIdValue != 0);
require(_eip20token != address(0));
require(_registrar != address(0));
require(_valueChainBlockGenerationTime != 0);
blocksToWaitShort = TIME_TO_WAIT_SHORT.div(_valueChainBlockGenerationTime);
blocksToWaitLong = TIME_TO_WAIT_LONG.div(_valueChainBlockGenerationTime);
chainIdValue = _chainIdValue;
valueToken = _eip20token;
// registrar cannot be reset
// TODO: require it to be a contract
registrar = _registrar;
}
/*
* External functions
*/
/// @dev In order to stake the tx.origin needs to set an allowance
/// for the OpenSTValue contract to transfer to itself to hold
/// during the staking process.
function stake(
bytes32 _uuid,
uint256 _amountST,
address _beneficiary,
bytes32 _hashLock,
address _staker)
external
returns (
uint256 amountUT,
uint256 nonce,
uint256 unlockHeight,
bytes32 stakingIntentHash)
/* solhint-disable-next-line function-max-lines */
{
/* solhint-disable avoid-tx-origin */
// check the staking contract has been approved to spend the amount to stake
// OpenSTValue needs to be able to transfer the stake into its balance for
// keeping until the two-phase process is completed on both chains.
require(_amountST > uint256(0));
require(utilityTokens[_uuid].simpleStake != address(0));
require(_beneficiary != address(0));
require(_staker != address(0));
UtilityToken storage utilityToken = utilityTokens[_uuid];
// if the staking account is set to a non-zero address,
// then all stakes have come (from/over) the staking account
if (utilityToken.stakingAccount != address(0)) require(msg.sender == utilityToken.stakingAccount);
require(valueToken.transferFrom(msg.sender, address(this), _amountST));
amountUT = (_amountST.mul(utilityToken.conversionRate))
.div(10**uint256(utilityToken.conversionRateDecimals));
unlockHeight = block.number + blocksToWaitLong;
nonces[_staker]++;
nonce = nonces[_staker];
stakingIntentHash = hashStakingIntent(
_uuid,
_staker,
nonce,
_beneficiary,
_amountST,
amountUT,
unlockHeight,
_hashLock
);
stakes[stakingIntentHash] = Stake({
uuid: _uuid,
staker: _staker,
beneficiary: _beneficiary,
nonce: nonce,
amountST: _amountST,
amountUT: amountUT,
unlockHeight: unlockHeight,
hashLock: _hashLock
});
// store the staking intent hash directly in storage of OpenSTValue
// so that a Merkle proof can be generated for active staking intents
bytes32 intentKeyHash = hashIntentKey(_staker, nonce);
stakingIntents[intentKeyHash] = stakingIntentHash;
emit StakingIntentDeclared(_uuid, _staker, nonce, intentKeyHash, _beneficiary,
_amountST, amountUT, unlockHeight, stakingIntentHash, utilityToken.chainIdUtility);
return (amountUT, nonce, unlockHeight, stakingIntentHash);
/* solhint-enable avoid-tx-origin */
}
function processStaking(
bytes32 _stakingIntentHash,
bytes32 _unlockSecret)
external
returns (address stakeAddress)
{
require(_stakingIntentHash != "");
Stake storage stakeItem = stakes[_stakingIntentHash];
// present the secret to unlock the hashlock and continue process
require(stakeItem.hashLock == keccak256(abi.encodePacked(_unlockSecret)));
// as this bears the cost, there is no need to require
// that the stakeItem.unlockHeight is not yet surpassed
// as is required on processMinting
UtilityToken storage utilityToken = utilityTokens[stakeItem.uuid];
// if the staking account is set to a non-zero address,
// then all stakes have come (from/over) the staking account
if (utilityToken.stakingAccount != address(0)) require(msg.sender == utilityToken.stakingAccount);
stakeAddress = address(utilityToken.simpleStake);
require(stakeAddress != address(0));
assert(valueToken.balanceOf(address(this)) >= stakeItem.amountST);
require(valueToken.transfer(stakeAddress, stakeItem.amountST));
emit ProcessedStake(stakeItem.uuid, _stakingIntentHash, stakeAddress, stakeItem.staker,
stakeItem.amountST, stakeItem.amountUT, _unlockSecret);
// remove from stakingIntents mapping
delete stakingIntents[hashIntentKey(stakeItem.staker, stakeItem.nonce)];
delete stakes[_stakingIntentHash];
return stakeAddress;
}
function revertStaking(
bytes32 _stakingIntentHash)
external
returns (
bytes32 uuid,
uint256 amountST,
address staker)
{
require(_stakingIntentHash != "");
Stake storage stakeItem = stakes[_stakingIntentHash];
UtilityToken storage utilityToken = utilityTokens[stakeItem.uuid];
// if the staking account is set to a non-zero address,
// then all stakes have come (from/over) the staking account
if (utilityToken.stakingAccount != address(0)) require(msg.sender == utilityToken.stakingAccount);
// require that the stake is unlocked and exists
require(stakeItem.unlockHeight > 0);
require(stakeItem.unlockHeight <= block.number);
assert(valueToken.balanceOf(address(this)) >= stakeItem.amountST);
// revert the amount that was intended to be staked back to staker
require(valueToken.transfer(stakeItem.staker, stakeItem.amountST));
uuid = stakeItem.uuid;
amountST = stakeItem.amountST;
staker = stakeItem.staker;
emit RevertedStake(stakeItem.uuid, _stakingIntentHash, stakeItem.staker,
stakeItem.amountST, stakeItem.amountUT);
// remove from stakingIntents mapping
delete stakingIntents[hashIntentKey(stakeItem.staker, stakeItem.nonce)];
delete stakes[_stakingIntentHash];
return (uuid, amountST, staker);
}
/**
* @notice Confirm redemption intent on value chain.
*
* @dev RedemptionIntentHash is generated in Utility chain, the paramerters are that were used for hash generation
* is passed in this function along with rpl encoded parent nodes of merkle pactritia tree proof
* for RedemptionIntentHash.
*
* @param _uuid UUID for utility token
* @param _redeemer Redeemer address
* @param _redeemerNonce Nonce for redeemer account
* @param _beneficiary Beneficiary address
* @param _amountUT Amount of utility token
* @param _redemptionUnlockHeight Unlock height for redemption
* @param _hashLock Hash lock
* @param _blockHeight Block height at which the Merkle proof was generated
* @param _rlpParentNodes RLP encoded parent nodes for proof verification
*
* @return bytes32 amount of OST
* @return uint256 expiration height
*/
function confirmRedemptionIntent(
bytes32 _uuid,
address _redeemer,
uint256 _redeemerNonce,
address _beneficiary,
uint256 _amountUT,
uint256 _redemptionUnlockHeight,
bytes32 _hashLock,
uint256 _blockHeight,
bytes _rlpParentNodes)
external
returns (
uint256 amountST,
uint256 expirationHeight)
{
UtilityToken storage utilityToken = utilityTokens[_uuid];
require(utilityToken.simpleStake != address(0));
require(_amountUT > 0);
require(_beneficiary != address(0));
// later core will provide a view on the block height of the
// utility chain
require(_redemptionUnlockHeight > 0);
require(cores[utilityToken.chainIdUtility].safeUnlockHeight() < _redemptionUnlockHeight);
nonces[_redeemer]++;
require(nonces[_redeemer] == _redeemerNonce);
bytes32 redemptionIntentHash = hashRedemptionIntent(
_uuid,
_redeemer,
_redeemerNonce,
_beneficiary,
_amountUT,
_redemptionUnlockHeight,
_hashLock
);
expirationHeight = block.number + blocksToWaitShort;
// minimal precision to unstake 1 STWei
require(_amountUT >= (utilityToken.conversionRate.div(10**uint256(utilityToken.conversionRateDecimals))));
amountST = (_amountUT
.mul(10**uint256(utilityToken.conversionRateDecimals))).div(utilityToken.conversionRate);
require(valueToken.balanceOf(address(utilityToken.simpleStake)) >= amountST);
require(verifyRedemptionIntent(
_uuid,
_redeemer,
_redeemerNonce,
_blockHeight,
redemptionIntentHash,
_rlpParentNodes), "RedemptionIntentHash storage verification failed");
unstakes[redemptionIntentHash] = Unstake({
uuid: _uuid,
redeemer: _redeemer,
beneficiary: _beneficiary,
amountUT: _amountUT,
amountST: amountST,
expirationHeight: expirationHeight,
hashLock: _hashLock
});
emit RedemptionIntentConfirmed(_uuid, redemptionIntentHash, _redeemer,
_beneficiary, amountST, _amountUT, expirationHeight);
return (amountST, expirationHeight);
}
/**
* @notice Verify storage of redemption intent hash
*
* @param _uuid UUID for utility token
* @param _redeemer Redeemer address
* @param _redeemerNonce Nonce for redeemer account
* @param _blockHeight Block height at which the Merkle proof was generated
* @param _rlpParentNodes RLP encoded parent nodes for proof verification
*
* @return true if successfully verifies, otherwise throws an exception.
*/
function verifyRedemptionIntent(
bytes32 _uuid,
address _redeemer,
uint256 _redeemerNonce,
uint256 _blockHeight,
bytes32 _redemptionIntentHash,
bytes _rlpParentNodes)
internal
view
returns (bool /* verification status */)
{
// get storageRoot from core for the given block height
bytes32 storageRoot = CoreInterface(cores[utilityTokens[_uuid].chainIdUtility]).getStorageRoot(_blockHeight);
// storageRoot cannot be 0
require(storageRoot != bytes32(0), "storageRoot not found for given blockHeight");
require(ProofLib.verifyIntentStorage(
intentsMappingStorageIndexPosition,
_redeemer,
_redeemerNonce,
_redemptionIntentHash,
_rlpParentNodes,
storageRoot), "RedemptionIntentHash storage verification failed");
return true;
}
function processUnstaking(
bytes32 _redemptionIntentHash,
bytes32 _unlockSecret)
external
returns (
address stakeAddress)
{
require(_redemptionIntentHash != "");
Unstake storage unstake = unstakes[_redemptionIntentHash];
// present secret to unlock hashlock and proceed
require(unstake.hashLock == keccak256(abi.encodePacked(_unlockSecret)));
// as the process unstake results in a gain for the caller
// it needs to expire well before the process redemption can
// be reverted in OpenSTUtility
require(unstake.expirationHeight > block.number);
UtilityToken storage utilityToken = utilityTokens[unstake.uuid];
stakeAddress = address(utilityToken.simpleStake);
require(stakeAddress != address(0));
require(utilityToken.simpleStake.releaseTo(unstake.beneficiary, unstake.amountST));
emit ProcessedUnstake(unstake.uuid, _redemptionIntentHash, stakeAddress,
unstake.redeemer, unstake.beneficiary, unstake.amountST, _unlockSecret);
delete unstakes[_redemptionIntentHash];
return stakeAddress;
}
function revertUnstaking(
bytes32 _redemptionIntentHash)
external
returns (
bytes32 uuid,
address redeemer,
address beneficiary,
uint256 amountST)
{
require(_redemptionIntentHash != "");
Unstake storage unstake = unstakes[_redemptionIntentHash];
// require that the unstake has expired and that the redeemer has not
// processed the unstaking, ie unstake has not been deleted
require(unstake.expirationHeight > 0);
require(unstake.expirationHeight <= block.number);
uuid = unstake.uuid;
redeemer = unstake.redeemer;
beneficiary = unstake.beneficiary;
amountST = unstake.amountST;
delete unstakes[_redemptionIntentHash];
emit RevertedUnstake(uuid, _redemptionIntentHash, redeemer, beneficiary, amountST);
return (uuid, redeemer, beneficiary, amountST);
}
function core(
uint256 _chainIdUtility)
external
view
returns (address /* core address */ )
{
return address(cores[_chainIdUtility]);
}
/*
* Public view functions
*/
function getNextNonce(
address _account)
public
view
returns (uint256 /* nextNonce */)
{
return (nonces[_account] + 1);
}
/// @dev Returns size of uuids
/// @return size
function getUuidsSize() public view returns (uint256) {
return uuids.length;
}
/*
* Registrar functions
*/
function addCore(
CoreInterface _core)
public
onlyRegistrar
returns (bool /* success */)
{
require(address(_core) != address(0));
// on value chain core only tracks a remote utility chain
uint256 chainIdUtility = _core.chainIdRemote();
require(chainIdUtility != 0);
// cannot overwrite core for given chainId
require(cores[chainIdUtility] == address(0));
cores[chainIdUtility] = _core;
return true;
}
function registerUtilityToken(
string _symbol,
string _name,
uint256 _conversionRate,
uint8 _conversionRateDecimals,
uint256 _chainIdUtility,
address _stakingAccount,
bytes32 _checkUuid)
public
onlyRegistrar
returns (bytes32 uuid)
{
require(bytes(_name).length > 0);
require(bytes(_symbol).length > 0);
require(_conversionRate > 0);
require(_conversionRateDecimals <= 5);
address openSTRemote = cores[_chainIdUtility].openSTRemote();
require(openSTRemote != address(0));
uuid = hashUuid(
_symbol,
_name,
chainIdValue,
_chainIdUtility,
openSTRemote,
_conversionRate,
_conversionRateDecimals);
require(uuid == _checkUuid);
require(address(utilityTokens[uuid].simpleStake) == address(0));
SimpleStake simpleStake = new SimpleStake(
valueToken, address(this), uuid);
utilityTokens[uuid] = UtilityToken({
symbol: _symbol,
name: _name,
conversionRate: _conversionRate,
conversionRateDecimals: _conversionRateDecimals,
decimals: TOKEN_DECIMALS,
chainIdUtility: _chainIdUtility,
simpleStake: simpleStake,
stakingAccount: _stakingAccount
});
uuids.push(uuid);
emit UtilityTokenRegistered(uuid, address(simpleStake), _symbol, _name,
TOKEN_DECIMALS, _conversionRate, _conversionRateDecimals, _chainIdUtility, _stakingAccount);
return uuid;
}
/**
* @notice Initiates protocol transfer.
*
* @param _protocolVersioned The address of the current protocol.
* @param _proposedProtocol The address of the proposed protocol.
*
* @return bool true in case of success, otherwise throws an exception.
*/
function initiateProtocolTransfer(
ProtocolVersioned _protocolVersioned,
address _proposedProtocol)
public
onlyAdmin
returns (bool)
{
_protocolVersioned.initiateProtocolTransfer(_proposedProtocol);
return true;
}
/**
* @notice Revokes protocol transfer.
*
* @param _protocolVersioned The address of the current protocol.
*
* @return bool true in case of success, otherwise throws an exception.
*/
function revokeProtocolTransfer(
ProtocolVersioned _protocolVersioned)
public
onlyAdmin
returns (bool)
{
_protocolVersioned.revokeProtocolTransfer();
return true;
}
function getStakerAddress(
bytes32 _stakingIntentHash)
view
external
returns (address /* staker */)
{
require(_stakingIntentHash != "");
Stake storage stakeItem = stakes[_stakingIntentHash];
return stakeItem.staker;
}
}
|
Revokes protocol transfer. _protocolVersioned The address of the current protocol. return bool true in case of success, otherwise throws an exception./
|
function revokeProtocolTransfer(
ProtocolVersioned _protocolVersioned)
public
onlyAdmin
returns (bool)
{
_protocolVersioned.revokeProtocolTransfer();
return true;
}
| 1,821,053 |
./full_match/80001/0xaB6b504514B0e7391572aB52d95C1023Ac4587d6/sources/contracts/Hypercert.sol
|
=========================================================================================================== Internal functions
|
function _onlyPool() internal view virtual {
require(msg.sender == poolAddress, "Funding Pool only function");
}
| 858,271 |
pragma solidity ^0.4.18;
import './Content.sol';
import '../utils/StringUtils.sol';
/**
* @title Updatable Content
* @dev The UpdateableContent contract allows the offchain content address to be updated in case of content change
*/
contract UpdatableContent is Content {
uint256 public contentUpdateTime;
event ContentChanged(string newContent);
function UpdatableContent(
string _contentAddress)
Content(_contentAddress)
Ownable()
public
{
contentUpdateTime = now;
}
/**
* @dev It changes the offchain content address
* @param _contentAddress A non-empty string that represents offchain content address
*/
function changeContent(
string _contentAddress)
onlyOwner
public
{
require(StringUtils.isNotEmpty(_contentAddress));
ContentChanged(_contentAddress);
contentAddress = _contentAddress;
contentUpdateTime = now;
}
}
|
It changes the offchain content address _contentAddress A non-empty string that represents offchain content address/
|
function changeContent(
string _contentAddress)
onlyOwner
public
{
require(StringUtils.isNotEmpty(_contentAddress));
ContentChanged(_contentAddress);
contentAddress = _contentAddress;
contentUpdateTime = now;
}
| 5,395,711 |
./partial_match/1/0x709Ab96e74f77629C7F7108a26831Af4C919102b/sources/StabilizeStrategyStablecoinArbV2.sol
|
Now find our target token to sell into Check if target ID has more than minimum reserve If less, we want to fill the reserve When restrict swaps is true, DAI will only sell to sUSD and sUSD will only sell to DAI as these pairs swap prices frequently We have a small amount of tokens to sell, so sell all of it We are getting a greater number of tokens, complete the exchange
|
function checkAndSwapTokens(bool _restrictSwaps, address _executor) internal {
lastTradeTime = now;
CurvePool pool = CurvePool(curveAddress);
uint256 length = tokenList.length;
if(_restrictSwaps == true){
uint256 _minReserveTarget = minReserve.mul(10**tokenList[targetID].decimals);
if(tokenList[targetID].token.balanceOf(address(this)) < _minReserveTarget){
_restrictSwaps = false;
}
}
for(uint256 i = 0; i < length; i++){
if(i != targetID){
uint256 localTarget = targetID;
if(_restrictSwaps == true){
}
}
uint256 sellBalance = 0;
uint256 _minTradeTarget = minTradeSplit.mul(10**tokenList[i].decimals);
if(tokenList[i].token.balanceOf(address(this)) <= _minTradeTarget){
sellBalance = tokenList[i].token.balanceOf(address(this));
sellBalance = tokenList[i].token.balanceOf(address(this)).mul(percentSell).div(divisionFactor);
}
if(sellBalance > 0){
uint256 estimate = pool.get_dy_underlying(tokenList[i].curveID, tokenList[localTarget].curveID, sellBalance);
if(estimate > minReceiveBalance){
_expectIncrease = true;
tokenList[i].token.safeApprove(address(pool), sellBalance);
pool.exchange_underlying(tokenList[i].curveID, tokenList[localTarget].curveID, sellBalance, minReceiveBalance);
}
}
}
}
uint256 _newBalance = balance();
| 4,261,733 |
pragma solidity 0.5.16;
interface ICERC20 {
/**
* @notice The mint function transfers an asset into the protocol, which begins accumulating
* interest based on the current Supply Rate for the asset. The user receives a quantity of
* cTokens equal to the underlying tokens supplied, divided by the current Exchange Rate.
* @param mintAmount The amount of the asset to be supplied, in units of the underlying asset.
* @return 0 on success, otherwise an Error codes
*/
function mint(uint mintAmount) external returns (uint);
/**
* @notice The redeem underlying function converts cTokens into a specified quantity of the underlying
* asset, and returns them to the user. The amount of cTokens redeemed is equal to the quantity of
* underlying tokens received, divided by the current Exchange Rate. The amount redeemed must be less
* than the user's Account Liquidity and the market's available liquidity.
* @param redeemAmount The amount of underlying to be redeemed.
* @return 0 on success, otherwise an Error codes
*/
function redeemUnderlying(uint redeemAmount) external returns (uint);
/**
* @notice The user's underlying balance, representing their assets in the protocol, is equal to
* the user's cToken balance multiplied by the Exchange Rate.
* @param owner The account to get the underlying balance of.
* @return The amount of underlying currently owned by the account.
*/
function balanceOfUnderlying(address owner) external returns (uint);
/**
* @notice Calculates the exchange rate from the underlying to the CToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateStored() external view returns (uint);
/**
* @notice Get the token balance of the `owner`
* @param owner The address of the account to query
* @return The number of tokens owned by `owner`
*/
function balanceOf(address owner) external view returns (uint256);
}
interface IBasicToken {
function decimals() external view returns (uint8);
}
library CommonHelpers {
/**
* @notice Fetch the `decimals()` from an ERC20 token
* @dev Grabs the `decimals()` from a contract and fails if
* the decimal value does not live within a certain range
* @param _token Address of the ERC20 token
* @return uint256 Decimals of the ERC20 token
*/
function getDecimals(address _token)
internal
view
returns (uint256) {
uint256 decimals = IBasicToken(_token).decimals();
require(decimals >= 4 && decimals <= 18, "Token must have sufficient decimal places");
return decimals;
}
}
interface IPlatformIntegration {
/**
* @dev Deposit the given bAsset to Lending platform
* @param _bAsset bAsset address
* @param _amount Amount to deposit
*/
function deposit(address _bAsset, uint256 _amount, bool isTokenFeeCharged)
external returns (uint256 quantityDeposited);
/**
* @dev Withdraw given bAsset from Lending platform
*/
function withdraw(address _receiver, address _bAsset, uint256 _amount, bool _isTokenFeeCharged) external;
/**
* @dev Returns the current balance of the given bAsset
*/
function checkBalance(address _bAsset) external returns (uint256 balance);
/**
* @dev Returns the pToken
*/
function bAssetToPToken(address _bAsset) external returns (address pToken);
}
contract InitializableModuleKeys {
// Governance // Phases
bytes32 internal KEY_GOVERNANCE; // 2.x
bytes32 internal KEY_STAKING; // 1.2
bytes32 internal KEY_PROXY_ADMIN; // 1.0
// mStable
bytes32 internal KEY_ORACLE_HUB; // 1.2
bytes32 internal KEY_MANAGER; // 1.2
bytes32 internal KEY_RECOLLATERALISER; // 2.x
bytes32 internal KEY_META_TOKEN; // 1.1
bytes32 internal KEY_SAVINGS_MANAGER; // 1.0
/**
* @dev Initialize function for upgradable proxy contracts. This function should be called
* via Proxy to initialize constants in the Proxy contract.
*/
function _initialize() internal {
// keccak256() values are evaluated only once at the time of this function call.
// Hence, no need to assign hard-coded values to these variables.
KEY_GOVERNANCE = keccak256("Governance");
KEY_STAKING = keccak256("Staking");
KEY_PROXY_ADMIN = keccak256("ProxyAdmin");
KEY_ORACLE_HUB = keccak256("OracleHub");
KEY_MANAGER = keccak256("Manager");
KEY_RECOLLATERALISER = keccak256("Recollateraliser");
KEY_META_TOKEN = keccak256("MetaToken");
KEY_SAVINGS_MANAGER = keccak256("SavingsManager");
}
}
interface INexus {
function governor() external view returns (address);
function getModule(bytes32 key) external view returns (address);
function proposeModule(bytes32 _key, address _addr) external;
function cancelProposedModule(bytes32 _key) external;
function acceptProposedModule(bytes32 _key) external;
function acceptProposedModules(bytes32[] calldata _keys) external;
function requestLockModule(bytes32 _key) external;
function cancelLockModule(bytes32 _key) external;
function lockModule(bytes32 _key) external;
}
contract InitializableModule is InitializableModuleKeys {
INexus public nexus;
/**
* @dev Modifier to allow function calls only from the Governor.
*/
modifier onlyGovernor() {
require(msg.sender == _governor(), "Only governor can execute");
_;
}
/**
* @dev Modifier to allow function calls only from the Governance.
* Governance is either Governor address or Governance address.
*/
modifier onlyGovernance() {
require(
msg.sender == _governor() || msg.sender == _governance(),
"Only governance can execute"
);
_;
}
/**
* @dev Modifier to allow function calls only from the ProxyAdmin.
*/
modifier onlyProxyAdmin() {
require(
msg.sender == _proxyAdmin(), "Only ProxyAdmin can execute"
);
_;
}
/**
* @dev Modifier to allow function calls only from the Manager.
*/
modifier onlyManager() {
require(msg.sender == _manager(), "Only manager can execute");
_;
}
/**
* @dev Initialization function for upgradable proxy contracts
* @param _nexus Nexus contract address
*/
function _initialize(address _nexus) internal {
require(_nexus != address(0), "Nexus address is zero");
nexus = INexus(_nexus);
InitializableModuleKeys._initialize();
}
/**
* @dev Returns Governor address from the Nexus
* @return Address of Governor Contract
*/
function _governor() internal view returns (address) {
return nexus.governor();
}
/**
* @dev Returns Governance Module address from the Nexus
* @return Address of the Governance (Phase 2)
*/
function _governance() internal view returns (address) {
return nexus.getModule(KEY_GOVERNANCE);
}
/**
* @dev Return Staking Module address from the Nexus
* @return Address of the Staking Module contract
*/
function _staking() internal view returns (address) {
return nexus.getModule(KEY_STAKING);
}
/**
* @dev Return ProxyAdmin Module address from the Nexus
* @return Address of the ProxyAdmin Module contract
*/
function _proxyAdmin() internal view returns (address) {
return nexus.getModule(KEY_PROXY_ADMIN);
}
/**
* @dev Return MetaToken Module address from the Nexus
* @return Address of the MetaToken Module contract
*/
function _metaToken() internal view returns (address) {
return nexus.getModule(KEY_META_TOKEN);
}
/**
* @dev Return OracleHub Module address from the Nexus
* @return Address of the OracleHub Module contract
*/
function _oracleHub() internal view returns (address) {
return nexus.getModule(KEY_ORACLE_HUB);
}
/**
* @dev Return Manager Module address from the Nexus
* @return Address of the Manager Module contract
*/
function _manager() internal view returns (address) {
return nexus.getModule(KEY_MANAGER);
}
/**
* @dev Return SavingsManager Module address from the Nexus
* @return Address of the SavingsManager Module contract
*/
function _savingsManager() internal view returns (address) {
return nexus.getModule(KEY_SAVINGS_MANAGER);
}
/**
* @dev Return Recollateraliser Module address from the Nexus
* @return Address of the Recollateraliser Module contract (Phase 2)
*/
function _recollateraliser() internal view returns (address) {
return nexus.getModule(KEY_RECOLLATERALISER);
}
}
contract InitializableGovernableWhitelist is InitializableModule {
event Whitelisted(address indexed _address);
mapping(address => bool) public whitelist;
/**
* @dev Modifier to allow function calls only from the whitelisted address.
*/
modifier onlyWhitelisted() {
require(whitelist[msg.sender], "Not a whitelisted address");
_;
}
/**
* @dev Initialization function for upgradable proxy contracts
* @param _nexus Nexus contract address
* @param _whitelisted Array of whitelisted addresses.
*/
function _initialize(
address _nexus,
address[] memory _whitelisted
)
internal
{
InitializableModule._initialize(_nexus);
require(_whitelisted.length > 0, "Empty whitelist array");
for(uint256 i = 0; i < _whitelisted.length; i++) {
_addWhitelist(_whitelisted[i]);
}
}
/**
* @dev Adds a new whitelist address
* @param _address Address to add in whitelist
*/
function _addWhitelist(address _address) internal {
require(_address != address(0), "Address is zero");
require(! whitelist[_address], "Already whitelisted");
whitelist[_address] = true;
emit Whitelisted(_address);
}
}
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 use in the initializer function of a contract.
*/
modifier initializer() {
require(initializing || isConstructor() || !initialized, "Contract instance has already been 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;
assembly { cs := extcodesize(self) }
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
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;
}
}
library StableMath {
using SafeMath for uint256;
/**
* @dev Scaling unit for use in specific calculations,
* where 1 * 10**18, or 1e18 represents a unit '1'
*/
uint256 private constant FULL_SCALE = 1e18;
/**
* @notice Token Ratios are used when converting between units of bAsset, mAsset and MTA
* Reasoning: Takes into account token decimals, and difference in base unit (i.e. grams to Troy oz for gold)
* @dev bAsset ratio unit for use in exact calculations,
* where (1 bAsset unit * bAsset.ratio) / ratioScale == x mAsset unit
*/
uint256 private constant RATIO_SCALE = 1e8;
/**
* @dev Provides an interface to the scaling unit
* @return Scaling unit (1e18 or 1 * 10**18)
*/
function getFullScale() internal pure returns (uint256) {
return FULL_SCALE;
}
/**
* @dev Provides an interface to the ratio unit
* @return Ratio scale unit (1e8 or 1 * 10**8)
*/
function getRatioScale() internal pure returns (uint256) {
return RATIO_SCALE;
}
/**
* @dev Scales a given integer to the power of the full scale.
* @param x Simple uint256 to scale
* @return Scaled value a to an exact number
*/
function scaleInteger(uint256 x)
internal
pure
returns (uint256)
{
return x.mul(FULL_SCALE);
}
/***************************************
PRECISE ARITHMETIC
****************************************/
/**
* @dev Multiplies two precise units, and then truncates by the full scale
* @param x Left hand input to multiplication
* @param y Right hand input to multiplication
* @return Result after multiplying the two inputs and then dividing by the shared
* scale unit
*/
function mulTruncate(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
return mulTruncateScale(x, y, FULL_SCALE);
}
/**
* @dev Multiplies two precise units, and then truncates by the given scale. For example,
* when calculating 90% of 10e18, (10e18 * 9e17) / 1e18 = (9e36) / 1e18 = 9e18
* @param x Left hand input to multiplication
* @param y Right hand input to multiplication
* @param scale Scale unit
* @return Result after multiplying the two inputs and then dividing by the shared
* scale unit
*/
function mulTruncateScale(uint256 x, uint256 y, uint256 scale)
internal
pure
returns (uint256)
{
// e.g. assume scale = fullScale
// z = 10e18 * 9e17 = 9e36
uint256 z = x.mul(y);
// return 9e38 / 1e18 = 9e18
return z.div(scale);
}
/**
* @dev Multiplies two precise units, and then truncates by the full scale, rounding up the result
* @param x Left hand input to multiplication
* @param y Right hand input to multiplication
* @return Result after multiplying the two inputs and then dividing by the shared
* scale unit, rounded up to the closest base unit.
*/
function mulTruncateCeil(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
// e.g. 8e17 * 17268172638 = 138145381104e17
uint256 scaled = x.mul(y);
// e.g. 138145381104e17 + 9.99...e17 = 138145381113.99...e17
uint256 ceil = scaled.add(FULL_SCALE.sub(1));
// e.g. 13814538111.399...e18 / 1e18 = 13814538111
return ceil.div(FULL_SCALE);
}
/**
* @dev Precisely divides two units, by first scaling the left hand operand. Useful
* for finding percentage weightings, i.e. 8e18/10e18 = 80% (or 8e17)
* @param x Left hand input to division
* @param y Right hand input to division
* @return Result after multiplying the left operand by the scale, and
* executing the division on the right hand input.
*/
function divPrecisely(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
// e.g. 8e18 * 1e18 = 8e36
uint256 z = x.mul(FULL_SCALE);
// e.g. 8e36 / 10e18 = 8e17
return z.div(y);
}
/***************************************
RATIO FUNCS
****************************************/
/**
* @dev Multiplies and truncates a token ratio, essentially flooring the result
* i.e. How much mAsset is this bAsset worth?
* @param x Left hand operand to multiplication (i.e Exact quantity)
* @param ratio bAsset ratio
* @return Result after multiplying the two inputs and then dividing by the ratio scale
*/
function mulRatioTruncate(uint256 x, uint256 ratio)
internal
pure
returns (uint256 c)
{
return mulTruncateScale(x, ratio, RATIO_SCALE);
}
/**
* @dev Multiplies and truncates a token ratio, rounding up the result
* i.e. How much mAsset is this bAsset worth?
* @param x Left hand input to multiplication (i.e Exact quantity)
* @param ratio bAsset ratio
* @return Result after multiplying the two inputs and then dividing by the shared
* ratio scale, rounded up to the closest base unit.
*/
function mulRatioTruncateCeil(uint256 x, uint256 ratio)
internal
pure
returns (uint256)
{
// e.g. How much mAsset should I burn for this bAsset (x)?
// 1e18 * 1e8 = 1e26
uint256 scaled = x.mul(ratio);
// 1e26 + 9.99e7 = 100..00.999e8
uint256 ceil = scaled.add(RATIO_SCALE.sub(1));
// return 100..00.999e8 / 1e8 = 1e18
return ceil.div(RATIO_SCALE);
}
/**
* @dev Precisely divides two ratioed units, by first scaling the left hand operand
* i.e. How much bAsset is this mAsset worth?
* @param x Left hand operand in division
* @param ratio bAsset ratio
* @return Result after multiplying the left operand by the scale, and
* executing the division on the right hand input.
*/
function divRatioPrecisely(uint256 x, uint256 ratio)
internal
pure
returns (uint256 c)
{
// e.g. 1e14 * 1e8 = 1e22
uint256 y = x.mul(RATIO_SCALE);
// return 1e22 / 1e12 = 1e10
return y.div(ratio);
}
/***************************************
HELPERS
****************************************/
/**
* @dev Calculates minimum of two numbers
* @param x Left hand input
* @param y Right hand input
* @return Minimum of the two inputs
*/
function min(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
return x > y ? y : x;
}
/**
* @dev Calculated maximum of two numbers
* @param x Left hand input
* @param y Right hand input
* @return Maximum of the two inputs
*/
function max(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
return x > y ? x : y;
}
/**
* @dev Clamps a value to an upper bound
* @param x Left hand input
* @param upperBound Maximum possible value to return
* @return Input x clamped to a maximum value, upperBound
*/
function clamp(uint256 x, uint256 upperBound)
internal
pure
returns (uint256)
{
return x > upperBound ? upperBound : x;
}
}
/**
* @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);
}
/**
* @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.
*/
/**
* @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");
}
}
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");
}
}
}
library MassetHelpers {
using StableMath for uint256;
using SafeMath for uint256;
using SafeERC20 for IERC20;
function transferTokens(
address _sender,
address _recipient,
address _basset,
bool _erc20TransferFeeCharged,
uint256 _qty
)
internal
returns (uint256 receivedQty)
{
receivedQty = _qty;
if(_erc20TransferFeeCharged) {
uint256 balBefore = IERC20(_basset).balanceOf(_recipient);
IERC20(_basset).safeTransferFrom(_sender, _recipient, _qty);
uint256 balAfter = IERC20(_basset).balanceOf(_recipient);
receivedQty = StableMath.min(_qty, balAfter.sub(balBefore));
} else {
IERC20(_basset).safeTransferFrom(_sender, _recipient, _qty);
}
}
function safeInfiniteApprove(address _asset, address _spender)
internal
{
IERC20(_asset).safeApprove(_spender, 0);
IERC20(_asset).safeApprove(_spender, uint256(-1));
}
}
contract InitializableReentrancyGuard {
bool private _notEntered;
function _initialize() internal {
// Storing an initial non-zero value makes deployment a bit more
// expensive, but in exchange the refund on every call to nonReentrant
// will be lower in amount. Since refunds are capped to a percetange of
// the total transaction's gas, it is best to keep them low in cases
// like this one, to increase the likelihood of the full refund coming
// into effect.
_notEntered = true;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_notEntered, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_notEntered = false;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_notEntered = true;
}
}
contract InitializableAbstractIntegration is
Initializable,
IPlatformIntegration,
InitializableGovernableWhitelist,
InitializableReentrancyGuard
{
using SafeERC20 for IERC20;
using SafeMath for uint256;
event PTokenAdded(address indexed _bAsset, address _pToken);
event Deposit(address indexed _bAsset, address _pToken, uint256 _amount);
event Withdrawal(address indexed _bAsset, address _pToken, uint256 _amount);
// Core address for the given platform */
address public platformAddress;
// bAsset => pToken (Platform Specific Token Address)
mapping(address => address) public bAssetToPToken;
// Full list of all bAssets supported here
address[] internal bAssetsMapped;
/**
* @dev Initialization function for upgradable proxy contract.
* This function should be called via Proxy just after contract deployment.
* @param _nexus Address of the Nexus
* @param _whitelisted Whitelisted addresses for vault access
* @param _platformAddress Generic platform address
* @param _bAssets Addresses of initial supported bAssets
* @param _pTokens Platform Token corresponding addresses
*/
function initialize(
address _nexus,
address[] calldata _whitelisted,
address _platformAddress,
address[] calldata _bAssets,
address[] calldata _pTokens
)
external
initializer
{
InitializableReentrancyGuard._initialize();
InitializableGovernableWhitelist._initialize(_nexus, _whitelisted);
InitializableAbstractIntegration._initialize(_platformAddress, _bAssets, _pTokens);
}
/**
* @dev Internal initialize function, to set up initial internal state
* @param _platformAddress Generic platform address
* @param _bAssets Addresses of initial supported bAssets
* @param _pTokens Platform Token corresponding addresses
*/
function _initialize(
address _platformAddress,
address[] memory _bAssets,
address[] memory _pTokens
)
internal
{
platformAddress = _platformAddress;
uint256 bAssetCount = _bAssets.length;
require(bAssetCount == _pTokens.length, "Invalid input arrays");
for(uint256 i = 0; i < bAssetCount; i++){
_setPTokenAddress(_bAssets[i], _pTokens[i]);
}
}
/***************************************
CONFIG
****************************************/
/**
* @dev Provide support for bAsset by passing its pToken address.
* This method can only be called by the system Governor
* @param _bAsset Address for the bAsset
* @param _pToken Address for the corresponding platform token
*/
function setPTokenAddress(address _bAsset, address _pToken)
external
onlyGovernor
{
_setPTokenAddress(_bAsset, _pToken);
}
/**
* @dev Provide support for bAsset by passing its pToken address.
* Add to internal mappings and execute the platform specific,
* abstract method `_abstractSetPToken`
* @param _bAsset Address for the bAsset
* @param _pToken Address for the corresponding platform token
*/
function _setPTokenAddress(address _bAsset, address _pToken)
internal
{
require(bAssetToPToken[_bAsset] == address(0), "pToken already set");
require(_bAsset != address(0) && _pToken != address(0), "Invalid addresses");
bAssetToPToken[_bAsset] = _pToken;
bAssetsMapped.push(_bAsset);
emit PTokenAdded(_bAsset, _pToken);
_abstractSetPToken(_bAsset, _pToken);
}
function _abstractSetPToken(address _bAsset, address _pToken) internal;
function reApproveAllTokens() external;
/***************************************
ABSTRACT
****************************************/
/**
* @dev Deposit a quantity of bAsset into the platform
* @param _bAsset Address for the bAsset
* @param _amount Units of bAsset to deposit
* @param _isTokenFeeCharged Flag that signals if an xfer fee is charged on bAsset
* @return quantityDeposited Quantity of bAsset that entered the platform
*/
function deposit(address _bAsset, uint256 _amount, bool _isTokenFeeCharged)
external returns (uint256 quantityDeposited);
/**
* @dev Withdraw a quantity of bAsset from the platform
* @param _receiver Address to which the bAsset should be sent
* @param _bAsset Address of the bAsset
* @param _amount Units of bAsset to withdraw
* @param _isTokenFeeCharged Flag that signals if an xfer fee is charged on bAsset
*/
function withdraw(address _receiver, address _bAsset, uint256 _amount, bool _isTokenFeeCharged) external;
/**
* @dev Get the total bAsset value held in the platform
* This includes any interest that was generated since depositing
* @param _bAsset Address of the bAsset
* @return balance Total value of the bAsset in the platform
*/
function checkBalance(address _bAsset) external returns (uint256 balance);
/***************************************
HELPERS
****************************************/
/**
* @dev Simple helper func to get the min of two values
*/
function _min(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
return x > y ? y : x;
}
}
/**
* @title CompoundIntegration
* @author Stability Labs Pty. Ltd.
* @notice A simple connection to deposit and withdraw bAssets from Compound
* @dev VERSION: 1.2
* DATE: 2020-10-19
*/
contract CompoundIntegration is InitializableAbstractIntegration {
event SkippedWithdrawal(address bAsset, uint256 amount);
event RewardTokenApproved(address rewardToken, address account);
/***************************************
ADMIN
****************************************/
/**
* @dev Approves Liquidator to spend reward tokens
*/
function approveRewardToken()
external
onlyGovernor
{
address liquidator = nexus.getModule(keccak256("Liquidator"));
require(liquidator != address(0), "Liquidator address cannot be zero");
// Official checksummed COMP token address
// https://ethplorer.io/address/0xc00e94cb662c3520282e6f5717214004a7f26888
address compToken = address(0xc00e94Cb662C3520282E6f5717214004A7f26888);
MassetHelpers.safeInfiniteApprove(compToken, liquidator);
emit RewardTokenApproved(address(compToken), liquidator);
}
/***************************************
CORE
****************************************/
/**
* @dev Deposit a quantity of bAsset into the platform. Credited cTokens
* remain here in the vault. Can only be called by whitelisted addresses
* (mAsset and corresponding BasketManager)
* @param _bAsset Address for the bAsset
* @param _amount Units of bAsset to deposit
* @param _isTokenFeeCharged Flag that signals if an xfer fee is charged on bAsset
* @return quantityDeposited Quantity of bAsset that entered the platform
*/
function deposit(
address _bAsset,
uint256 _amount,
bool _isTokenFeeCharged
)
external
onlyWhitelisted
nonReentrant
returns (uint256 quantityDeposited)
{
require(_amount > 0, "Must deposit something");
// Get the Target token
ICERC20 cToken = _getCTokenFor(_bAsset);
// We should have been sent this amount, if not, the deposit will fail
quantityDeposited = _amount;
if(_isTokenFeeCharged) {
// If we charge a fee, account for it
uint256 prevBal = _checkBalance(cToken);
require(cToken.mint(_amount) == 0, "cToken mint failed");
uint256 newBal = _checkBalance(cToken);
quantityDeposited = _min(quantityDeposited, newBal.sub(prevBal));
} else {
// Else just execute the mint
require(cToken.mint(_amount) == 0, "cToken mint failed");
}
emit Deposit(_bAsset, address(cToken), quantityDeposited);
}
/**
* @dev Withdraw a quantity of bAsset from Compound. Redemption
* should fail if we have insufficient cToken balance.
* @param _receiver Address to which the withdrawn bAsset should be sent
* @param _bAsset Address of the bAsset
* @param _amount Units of bAsset to withdraw
*/
function withdraw(
address _receiver,
address _bAsset,
uint256 _amount,
bool _isTokenFeeCharged
)
external
onlyWhitelisted
nonReentrant
{
require(_amount > 0, "Must withdraw something");
require(_receiver != address(0), "Must specify recipient");
// Get the Target token
ICERC20 cToken = _getCTokenFor(_bAsset);
// If redeeming 0 cTokens, just skip, else COMP will revert
// Reason for skipping: to ensure that redeemMasset is always able to execute
uint256 cTokensToRedeem = _convertUnderlyingToCToken(cToken, _amount);
if(cTokensToRedeem == 0) {
emit SkippedWithdrawal(_bAsset, _amount);
return;
}
uint256 quantityWithdrawn = _amount;
if(_isTokenFeeCharged) {
IERC20 b = IERC20(_bAsset);
uint256 prevBal = b.balanceOf(address(this));
require(cToken.redeemUnderlying(_amount) == 0, "redeem failed");
uint256 newBal = b.balanceOf(address(this));
quantityWithdrawn = _min(quantityWithdrawn, newBal.sub(prevBal));
} else {
// Redeem Underlying bAsset amount
require(cToken.redeemUnderlying(_amount) == 0, "redeem failed");
}
// Send redeemed bAsset to the receiver
IERC20(_bAsset).safeTransfer(_receiver, quantityWithdrawn);
emit Withdrawal(_bAsset, address(cToken), quantityWithdrawn);
}
/**
* @dev Get the total bAsset value held in the platform
* This includes any interest that was generated since depositing
* Compound exchange rate between the cToken and bAsset gradually increases,
* causing the cToken to be worth more corresponding bAsset.
* @param _bAsset Address of the bAsset
* @return balance Total value of the bAsset in the platform
*/
function checkBalance(address _bAsset)
external
returns (uint256 balance)
{
// balance is always with token cToken decimals
ICERC20 cToken = _getCTokenFor(_bAsset);
balance = _checkBalance(cToken);
}
/***************************************
APPROVALS
****************************************/
/**
* @dev Re-approve the spending of all bAssets by their corresponding cToken,
* if for some reason is it necessary. Only callable through Governance.
*/
function reApproveAllTokens()
external
onlyGovernor
{
uint256 bAssetCount = bAssetsMapped.length;
for(uint i = 0; i < bAssetCount; i++){
address bAsset = bAssetsMapped[i];
address cToken = bAssetToPToken[bAsset];
MassetHelpers.safeInfiniteApprove(bAsset, cToken);
}
}
/**
* @dev Internal method to respond to the addition of new bAsset / cTokens
* We need to approve the cToken and give it permission to spend the bAsset
* @param _bAsset Address of the bAsset to approve
* @param _cToken This cToken has the approval approval
*/
function _abstractSetPToken(address _bAsset, address _cToken)
internal
{
// approve the pool to spend the bAsset
MassetHelpers.safeInfiniteApprove(_bAsset, _cToken);
}
/***************************************
HELPERS
****************************************/
/**
* @dev Get the cToken wrapped in the ICERC20 interface for this bAsset.
* Fails if the pToken doesn't exist in our mappings.
* @param _bAsset Address of the bAsset
* @return Corresponding cToken to this bAsset
*/
function _getCTokenFor(address _bAsset)
internal
view
returns (ICERC20)
{
address cToken = bAssetToPToken[_bAsset];
require(cToken != address(0), "cToken does not exist");
return ICERC20(cToken);
}
/**
* @dev Get the total bAsset value held in the platform
* underlying = (cTokenAmt * exchangeRate) / 1e18
* @param _cToken cToken for which to check balance
* @return balance Total value of the bAsset in the platform
*/
function _checkBalance(ICERC20 _cToken)
internal
view
returns (uint256 balance)
{
uint256 cTokenBalance = _cToken.balanceOf(address(this));
uint256 exchangeRate = _cToken.exchangeRateStored();
// e.g. 50e8*205316390724364402565641705 / 1e18 = 1.0265..e18
balance = cTokenBalance.mul(exchangeRate).div(1e18);
}
/**
* @dev Converts an underlying amount into cToken amount
* cTokenAmt = (underlying * 1e18) / exchangeRate
* @param _cToken cToken for which to change
* @param _underlying Amount of underlying to convert
* @return amount Equivalent amount of cTokens
*/
function _convertUnderlyingToCToken(ICERC20 _cToken, uint256 _underlying)
internal
view
returns (uint256 amount)
{
uint256 exchangeRate = _cToken.exchangeRateStored();
// e.g. 1e18*1e18 / 205316390724364402565641705 = 50e8
// e.g. 1e8*1e18 / 205316390724364402565641705 = 0.45 or 0
amount = _underlying.mul(1e18).div(exchangeRate);
}
}
|
Get the total bAsset value held in the platform This includes any interest that was generated since depositing Compound exchange rate between the cToken and bAsset gradually increases, causing the cToken to be worth more corresponding bAsset. _bAsset Address of the bAsset return balance Total value of the bAsset in the platform/ balance is always with token cToken decimals
|
function checkBalance(address _bAsset)
external
returns (uint256 balance)
{
ICERC20 cToken = _getCTokenFor(_bAsset);
balance = _checkBalance(cToken);
}
| 560,308 |
./full_match/5/0x1939B5d3Cfff65789F88843948E7a312e77fd14d/sources/contracts/CrowdFunding.sol
|
Check that the campaign exists Retrieve the campaign from the campaigns mapping Check that the donor and donation amount are valid Remove the donor from the donators array
|
function refundDonation(uint256 _id, address _donator, uint256 _donationAmount, address _refundAddress) public payable {
require(_id < numberOfCampaigns, "Campaign ID does not exist");
Campaign storage campaign = campaigns[_id];
uint256 donationIndex;
uint256 donationAmount;
bool found = false;
for (uint256 i = 0; i < campaign.donators.length; i++) {
if (campaign.donators[i] == _donator && campaign.donations[i] == _donationAmount) {
donationIndex = i;
donationAmount = _donationAmount;
found = true;
break;
}
}
require(found, "Donor and donation amount do not match any recorded donations");
campaign.donations[donationIndex] = 0;
for (uint256 i = donationIndex; i < campaign.donators.length - 1; i++) {
campaign.donators[i] = campaign.donators[i + 1];
campaign.donations[i] = campaign.donations[i + 1];
}
delete campaign.donators[campaign.donators.length - 1];
delete campaign.donations[campaign.donations.length - 1];
}
| 1,914,510 |
./partial_match/4/0x5b561AC887b70823267DEF181728855Bb578516D/sources/etherATM_Exchange.sol
|
our calculation relies on the token supply, so we need supply. Doh.
|
function sellPrice()
public
view
returns(uint256)
{
if(tokenSupply_ == 0){
return tokenPriceInitial_ - tokenPriceIncremental_;
uint256 _ethereum = tokensToEthereum_(2,false);
uint256 _dividends = _ethereum * percent/10000;
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
}
| 8,731,291 |
pragma solidity ^0.4.24;
/* Smart Contract Security Audit by Callisto Network */
/* Mizhen Boss represents the right of being a member of Mizhen community
* Holders can use different tools and share profits in all the games developed by Mizhen team
* Total number of MZBoss is 21,000,000
* The price of MZBoss is constant at 0.005 ether
* Purchase fee is 15%, pay customers buy MZBoss, of which 10% is distributed to tokenholders, 5% is sent to community for further development.
* There is not selling fee
* The purchase fee is evenly distributed to the existing MZBoss holders
* All MZBoss holders will receive profit from different game pots
* Mizhen Team
*/
contract MZBoss {
/*=================================
= MODIFIERS =
=================================*/
// only people with tokens
modifier transferCheck(uint256 _amountOfTokens) {
address _customerAddress = msg.sender;
require((_amountOfTokens > 0) && (_amountOfTokens <= tokenBalanceLedger_[_customerAddress]));
_;
}
// only people with profits
modifier onlyStronghands() {
address _customerAddress = msg.sender;
require(dividendsOf(_customerAddress) > 0);
_;
}
// Check if the play has enough ETH to buy tokens
modifier enoughToreinvest() {
address _customerAddress = msg.sender;
uint256 priceForOne = (tokenPriceInitial_*100)/85;
require((dividendsOf(_customerAddress) >= priceForOne) && (_tokenLeft >= calculateTokensReceived(dividendsOf(_customerAddress))));
_;
}
// administrators can:
// -> change the name of the contract
// -> change the name of the token
// they CANNOT:
// -> take funds
// -> disable withdrawals
// -> kill the contract
// -> change the price of tokens
modifier onlyAdministrator(){
address _customerAddress = msg.sender;
require(administrators[_customerAddress] == true);
_;
}
// Check if the play has enough ETH to buy tokens
modifier enoughToBuytoken (){
uint256 _amountOfEthereum = msg.value;
uint256 priceForOne = (tokenPriceInitial_*100)/85;
require((_amountOfEthereum >= priceForOne) && (_tokenLeft >= calculateTokensReceived(_amountOfEthereum)));
_;
}
/*==============================
= EVENTS =
==============================*/
event OnTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensBought,
uint256 tokenSupplyUpdate,
uint256 tokenLeftUpdate
);
event OnTokenSell(
address indexed customerAddress,
uint256 tokensSold,
uint256 ethereumEarned,
uint256 tokenSupplyUpdate,
uint256 tokenLeftUpdate
);
event OnReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensBought,
uint256 tokenSupplyUpdate,
uint256 tokenLeftUpdate
);
event OnWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
// distribution of profit from pot
event OnTotalProfitPot(
uint256 _totalProfitPot
);
// ERC20
event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
/*=====================================
= CONFIGURABLES =
=====================================*/
string public name = "Mizhen";
string public symbol = "MZBoss";
uint256 constant public totalToken = 21000000e18; //total 21000000 MZBoss tokens
uint8 constant public decimals = 18;
uint8 constant internal dividendFee_ = 10; // percentage of fee sent to token holders
uint8 constant internal toCommunity_ = 5; // percentage of fee sent to community.
uint256 constant internal tokenPriceInitial_ = 5e15; // the price is constant and does not change as the purchase increases.
uint256 constant internal magnitude = 1e18; // related to payoutsTo_, profitPershare_, profitPerSharePot_, profitPerShareNew_
// ambassador program
mapping(address => bool) internal ambassadors_;
uint256 constant internal ambassadorMaxPurchase_ = 1e19;
uint256 constant internal ambassadorQuota_ = 1e19;
// exchange address, in the future customers can exchange MZBoss without the price limitation
mapping(address => bool) public exchangeAddress_;
/*================================
= DATASETS =
================================*/
// amount of shares for each address (scaled number)
mapping(address => uint256) public tokenBalanceLedger_;
mapping(address => int256) internal payoutsTo_;
mapping(address => uint256) internal ambassadorAccumulatedQuota_;
uint256 public tokenSupply_ = 0; // total sold tokens
uint256 public _tokenLeft = 21000000e18;
uint256 public totalEthereumBalance1 = 0;
uint256 public profitPerShare_ = 0 ;
uint256 public _totalProfitPot = 0;
address constant internal _communityAddress = 0x43e8587aCcE957629C9FD2185dD700dcDdE1dD1E;
// administrator list (see above on what they can do)
mapping(address => bool) public administrators;
// when this is set to true, only ambassadors can purchase tokens
bool public onlyAmbassadors = true;
/*=======================================
= PUBLIC FUNCTIONS =
=======================================*/
/*
* -- APPLICATION ENTRY POINTS --
*/
constructor ()
public
{
// add administrators here
administrators[0x6dAd1d9D24674bC9199237F93beb6E25b55Ec763] = true;
// add the ambassadors here.
ambassadors_[0x64BFD8F0F51569AEbeBE6AD2a1418462bCBeD842] = true;
}
function purchaseTokens()
enoughToBuytoken ()
public
payable
{
address _customerAddress = msg.sender;
uint256 _amountOfEthereum = msg.value;
// are we still in the ambassador phase?
if( onlyAmbassadors && (SafeMath.sub(totalEthereumBalance(), _amountOfEthereum) < ambassadorQuota_ )){
require(
// is the customer in the ambassador list?
(ambassadors_[_customerAddress] == true) &&
// does the customer purchase exceed the max ambassador quota?
(SafeMath.add(ambassadorAccumulatedQuota_[_customerAddress], _amountOfEthereum) <= ambassadorMaxPurchase_)
);
// updated the accumulated quota
ambassadorAccumulatedQuota_[_customerAddress] = SafeMath.add(ambassadorAccumulatedQuota_[_customerAddress], _amountOfEthereum);
totalEthereumBalance1 = SafeMath.add(totalEthereumBalance1, _amountOfEthereum);
uint256 _amountOfTokens = ethereumToTokens_(_amountOfEthereum);
tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens);
_tokenLeft = SafeMath.sub(totalToken, tokenSupply_);
emit OnTokenPurchase(_customerAddress, _amountOfEthereum, _amountOfTokens, tokenSupply_, _tokenLeft);
}
else {
// in case the ether count drops low, the ambassador phase won't reinitiate
onlyAmbassadors = false;
purchaseTokensAfter(_amountOfEthereum);
}
}
/**
* profit distribution from game pot
*/
function potDistribution()
public
payable
{
//
require(msg.value > 0);
uint256 _incomingEthereum = msg.value;
if(tokenSupply_ > 0){
// profit per share
uint256 profitPerSharePot_ = SafeMath.mul(_incomingEthereum, magnitude) / (tokenSupply_);
// update profitPerShare_, adding profit from game pot
profitPerShare_ = SafeMath.add(profitPerShare_, profitPerSharePot_);
} else {
// send to community
payoutsTo_[_communityAddress] -= (int256) (_incomingEthereum);
}
//update _totalProfitPot
_totalProfitPot = SafeMath.add(_incomingEthereum, _totalProfitPot);
}
/**
* Converts all of caller's dividends to tokens.
*/
function reinvest()
enoughToreinvest()
public
{
// pay out the dividends virtually
address _customerAddress = msg.sender;
// fetch dividends
uint256 _dividends = dividendsOf(_customerAddress);
uint256 priceForOne = (tokenPriceInitial_*100)/85;
// minimum purchase 1 ether token
if (_dividends >= priceForOne) {
// dispatch a buy order with the virtualized "withdrawn dividends"
purchaseTokensAfter(_dividends);
payoutsTo_[_customerAddress] += (int256) (_dividends);
}
}
/**
* Withdraws all of the callers earnings.
*/
function withdraw()
onlyStronghands()
public
{
// setup data
address _customerAddress = msg.sender;
uint256 _dividends = dividendsOf(_customerAddress);
// update dividend tracker, in order to calculate with payoutsTo which is int256, _dividends need to be casted to int256 first
payoutsTo_[_customerAddress] += (int256) (_dividends);
// send eth
_customerAddress.transfer(_dividends);
// fire event
emit OnWithdraw(_customerAddress, _dividends);
}
/**
* Liquifies tokens to ethereum.
*/
function sell(uint256 _amountOfTokens)
public
{
// setup data
address _customerAddress = msg.sender;
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, 0); // no fee when sell, but there is transaction fee included here
require((tokenBalanceLedger_[_customerAddress] >= _amountOfTokens) && ( totalEthereumBalance1 >= _taxedEthereum ) && (_amountOfTokens > 0));
// update the amount of the sold tokens
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens);
totalEthereumBalance1 = SafeMath.sub(totalEthereumBalance1, _taxedEthereum);
// update dividends tracker
int256 _updatedPayouts = (int256) (SafeMath.add(SafeMath.mul(profitPerShare_, _tokens)/magnitude, _taxedEthereum));
payoutsTo_[_customerAddress] -= _updatedPayouts;
tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens);
_tokenLeft = SafeMath.sub(totalToken, tokenSupply_);
// fire event
emit OnTokenSell(_customerAddress, _tokens, _taxedEthereum, tokenSupply_, _tokenLeft);
}
/**
* Transfer tokens from the caller to a new holder.
*/
function transfer(uint256 _amountOfTokens, address _toAddress)
transferCheck(_amountOfTokens)
public
returns(bool)
{
// setup
address _customerAddress = msg.sender;
// withdraw all outstanding dividends first
if(dividendsOf(_customerAddress) > 0) withdraw();
// exchange tokens
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _amountOfTokens);
// update dividend trackers
payoutsTo_[_customerAddress] -= (int256) (SafeMath.mul(profitPerShare_ , _amountOfTokens)/magnitude);
payoutsTo_[_toAddress] += (int256) (SafeMath.mul(profitPerShare_ , _amountOfTokens)/magnitude);
// fire event
emit Transfer(_customerAddress, _toAddress, _amountOfTokens);
// ERC20
return true;
}
/*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/
/**
* In case we need to replace ourselves.
*/
function setAdministrator(address _identifier, bool _status)
onlyAdministrator()
public
{
administrators[_identifier] = _status;
}
/**
* If we want to rebrand, we can.
*/
function setName(string _name)
onlyAdministrator()
public
{
name = _name;
}
/**
* If we want to rebrand, we can.
*/
function setSymbol(string _symbol)
onlyAdministrator()
public
{
symbol = _symbol;
}
/*---------- HELPERS AND CALCULATORS ----------*/
/**
* Method to view the current Ethereum stored in the contract
*
*/
function totalEthereumBalance()
public
view
returns(uint)
{
return address(this).balance;
}
/**
* Method to view the current sold tokens
*
*/
function tokenSupply()
public
view
returns(uint256)
{
return tokenSupply_;
}
/**
* Retrieve the token balance of any single address.
*/
function balanceOf(address _customerAddress)
public
view
returns(uint256)
{
return tokenBalanceLedger_[_customerAddress];
}
/**
* Retrieve the payoutsTo_ of any single address.
*/
function payoutsTo(address _customerAddress)
public
view
returns(int256)
{
return payoutsTo_[_customerAddress];
}
/**
* Retrieve the tokens owned by the caller.
*/
function myTokens()
public
view
returns(uint256)
{
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
/**
* Retrieve the dividend balance of any single address.
*/
function dividendsOf(address _customerAddress)
public
view
returns(uint256)
{
uint256 _TokensEther = tokenBalanceLedger_[_customerAddress];
if ((int256(SafeMath.mul(profitPerShare_, _TokensEther)/magnitude) - payoutsTo_[_customerAddress]) > 0 )
return uint256(int256(SafeMath.mul(profitPerShare_, _TokensEther)/magnitude) - payoutsTo_[_customerAddress]);
else
return 0;
}
/**
* Function for the frontend to dynamically retrieve the price scaling of buy orders.
*/
function calculateTokensReceived(uint256 _ethereumToSpend)
public
pure
returns(uint256)
{
uint256 _dividends = SafeMath.mul(_ethereumToSpend, dividendFee_) / 100;
uint256 _communityDistribution = SafeMath.mul(_ethereumToSpend, toCommunity_) / 100;
uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, SafeMath.add(_communityDistribution,_dividends));
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
return _amountOfTokens;
}
/**
* Function for the frontend to dynamically retrieve the price scaling of sell orders.
*/
function calculateEthereumReceived(uint256 _tokensToSell)
public
pure
returns(uint256)
{
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, 0); // transaction fee
return _taxedEthereum;
}
/*==========================================
= INTERNAL FUNCTIONS =
==========================================*/
function purchaseTokensAfter(uint256 _incomingEthereum)
private
{
// data setup
address _customerAddress = msg.sender;
// distribution as dividend to token holders
uint256 _dividends = SafeMath.mul(_incomingEthereum, dividendFee_) / 100;
// sent to community address
uint256 _communityDistribution = SafeMath.mul(_incomingEthereum, toCommunity_) / 100;
uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, SafeMath.add(_communityDistribution, _dividends));
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
// prevents overflow in the case that the pyramid somehow magically starts being used by everyone in the world
// minimum purchase 1 token
require((_amountOfTokens >= 1e18) && (SafeMath.add(_amountOfTokens,tokenSupply_) > tokenSupply_));
// profitPerShare calculation assuming the _dividends are only distributed to the holders before the new customer
// the tokenSupply_ here is the supply without considering the new customer's buying amount
if (tokenSupply_ == 0){
uint256 profitPerShareNew_ = 0;
}else{
profitPerShareNew_ = SafeMath.mul(_dividends, magnitude) / (tokenSupply_);
}
// take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder
profitPerShare_ = SafeMath.add(profitPerShare_, profitPerShareNew_);
// assumed total dividends considering the new customer's buying amount
uint256 _dividendsAssumed = SafeMath.div(SafeMath.mul(profitPerShare_, _amountOfTokens), magnitude);
// extra dividends in the assumed dividens, which does not exist
// this part is considered as the existing payoutsTo_ to the new customer
uint256 _dividendsExtra = _dividendsAssumed;
// update the new customer's payoutsTo_; cast _dividendsExtra to int256 first because payoutsTo is int256
payoutsTo_[_customerAddress] += (int256) (_dividendsExtra);
// add tokens to the pool, update the tokenSupply_
tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens);
_tokenLeft = SafeMath.sub(totalToken, tokenSupply_);
totalEthereumBalance1 = SafeMath.add(totalEthereumBalance1, _taxedEthereum);
// send to community
_communityAddress.transfer(_communityDistribution);
// update circulating supply & the ledger address for the customer
tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
// fire event
emit OnTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens, tokenSupply_, _tokenLeft);
}
/**
* Calculate Token price based on an amount of incoming ethereum
*/
function ethereumToTokens_(uint256 _ethereum)
internal
pure
returns(uint256)
{
require (_ethereum > 0);
uint256 _tokenPriceInitial = tokenPriceInitial_;
uint256 _tokensReceived = SafeMath.mul(_ethereum, magnitude) / _tokenPriceInitial;
return _tokensReceived;
}
/**
* Calculate token sell value.
*/
function tokensToEthereum_(uint256 _tokens)
internal
pure
returns(uint256)
{
uint256 tokens_ = _tokens;
uint256 _etherReceived = SafeMath.mul (tokenPriceInitial_, tokens_) / magnitude;
return _etherReceived;
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
|
data setup distribution as dividend to token holders sent to community address prevents overflow in the case that the pyramid somehow magically starts being used by everyone in the world minimum purchase 1 token profitPerShare calculation assuming the _dividends are only distributed to the holders before the new customer the tokenSupply_ here is the supply without considering the new customer's buying amount
|
function purchaseTokensAfter(uint256 _incomingEthereum)
private
{
address _customerAddress = msg.sender;
uint256 _dividends = SafeMath.mul(_incomingEthereum, dividendFee_) / 100;
uint256 _communityDistribution = SafeMath.mul(_incomingEthereum, toCommunity_) / 100;
uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, SafeMath.add(_communityDistribution, _dividends));
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
require((_amountOfTokens >= 1e18) && (SafeMath.add(_amountOfTokens,tokenSupply_) > tokenSupply_));
if (tokenSupply_ == 0){
uint256 profitPerShareNew_ = 0;
profitPerShareNew_ = SafeMath.mul(_dividends, magnitude) / (tokenSupply_);
}
_tokenLeft = SafeMath.sub(totalToken, tokenSupply_);
totalEthereumBalance1 = SafeMath.add(totalEthereumBalance1, _taxedEthereum);
}
| 1,061,968 |
pragma solidity >=0.8.0 <0.9.0;
//SPDX-License-Identifier: MIT
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/utils/structs/EnumerableMap.sol";
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./Items.sol";
import "./StakeManager.sol";
import "hardhat/console.sol";
abstract contract ContextMixin {
function msgSender() internal view returns (address payable sender) {
if (msg.sender == address(this)) {
bytes memory array = msg.data;
uint256 index = msg.data.length;
assembly {
// Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those.
sender := and(
mload(add(array, index)),
0xffffffffffffffffffffffffffffffffffffffff
)
}
} else {
sender = payable(msg.sender);
}
return sender;
}
}
contract Accounts is
ERC721,
ERC721URIStorage,
ContextMixin,
Ownable
{
address private ACCOUNT_MANAGER;
address private MARKETPLACE_OPERATOR;
StakeManager private stakeManager;
using Counters for Counters.Counter;
using EnumerableMap for EnumerableMap.UintToAddressMap;
Counters.Counter private _tokenIds;
EnumerableMap.UintToAddressMap private _accountOwner;
Items public itemsContract;
struct ItemInventory {
uint256 amount;
}
struct Account {
address owner;
uint256 accountId; //account nft id
uint256[] items;
mapping(uint256 => ItemInventory) inventory;
bool deleted;
}
mapping(uint256 => mapping(address => Account)) public account;
mapping(address => uint256) public players;
event AccountCreated(address player);
event AccountSwapped(address newPlayer, address oldPlayer);
event AccountDeleted(address player);
event ItemReceived(address player, uint256 tokenId, uint256 itemId);
constructor(Items _items, StakeManager _stakeManager) ERC721("LaVAccounts", "LaVAccounts") {
itemsContract = _items;
stakeManager = _stakeManager;
ACCOUNT_MANAGER = owner();
}
receive() external payable {}
function setAccountManager(address accountManager) public onlyOwner {
ACCOUNT_MANAGER = accountManager;
}
function setMarketplaceOperator(address marketplaceOperator)
public
onlyOwner
{
MARKETPLACE_OPERATOR = marketplaceOperator;
}
function createAccount(
address player,
string memory playerTokenURI,
uint256 accountType
) external onlyOwner returns (uint256) {
_tokenIds.increment();
uint256 newItemId = _tokenIds.current();
_safeMint(player, newItemId);
_setTokenURI(newItemId, playerTokenURI);
_accountOwner.set(newItemId, player);
players[player] = newItemId;
initAccountItems(player, newItemId, accountType);
account[newItemId][player].owner = player;
account[newItemId][player].accountId = newItemId;
emit AccountCreated(player);
return newItemId;
}
function deleteAccount(address player, uint256 tokenId) external onlyOwner {
require(
_isApprovedOrOwner(_msgSender(), tokenId),
"LaVie: can't burn account not owned"
);
_burn(tokenId);
deleteAccountItems(player, tokenId);
delete account[tokenId][player];
account[tokenId][player].deleted = true;
delete players[player];
_accountOwner.remove(tokenId);
emit AccountDeleted(player);
}
function tokenURI(uint256 tokenId)
public
view
override(ERC721, ERC721URIStorage)
returns (string memory)
{
return super.tokenURI(tokenId);
}
function getAccountOwner(uint256 tokenId) public view returns (address) {
return _accountOwner.get(tokenId);
}
function transferFrom(
address from,
address to,
uint256 tokenId
) public override {
require(!stakeManager.isStakingBool(from),"La Vie: Unstake first!");
super.transferFrom(from, to, tokenId);
changeAccountOwnership(from, tokenId, to);
_accountOwner.set(tokenId, to);
}
function _burn(uint256 tokenId)
internal
override(ERC721, ERC721URIStorage)
{
super._burn(tokenId);
}
function exists(uint256 tokenId) public view returns (bool) {
return super._exists(tokenId);
}
function initAccountItems(
address player,
uint256 accountId,
uint256 accountType
) private onlyOwner {
if (accountType == 3) {
//assuming items are pre-minted
//initiate w/ 3 basic items and 1 rare
//knife, brass knuckles, bat (1,5,9)
//rare item should be random? Init chainlink random #
uint256[] memory ids = new uint256[](3);
uint256[] memory amounts = new uint256[](3);
ids[0] = 1;
ids[1] = 5;
ids[2] = 9;
amounts[0] = 1;
amounts[1] = 1;
amounts[2] = 1;
transferItemsFromGameToAccount(player, accountId, ids, amounts);
} else if (accountType == 2) {
//assuming items are pre-minted
//initiate w/ 2 basic items
//knife, bat
//itemsContract.safeBatchTransferFrom(address(itemsContract), player, [1, 9], [1, 1], "");
uint256[] memory ids = new uint256[](2);
uint256[] memory amounts = new uint256[](2);
ids[0] = 1;
ids[1] = 9;
amounts[0] = 1;
amounts[1] = 1;
transferItemsFromGameToAccount(player, accountId, ids, amounts);
} else {
//skip
//basic accounts, tier 1 do not get any items.
}
}
function transferItemsFromGameToAccount(
address player,
uint256 accountId,
uint256[] memory ids,
uint256[] memory amounts
) private onlyOwner {
itemsContract.transferBatchFromGame(
address(itemsContract),
player,
ids,
amounts,
"0x0"
);
account[accountId][player].items = ids;
for (uint256 i = 0; i < ids.length; ++i) {
account[accountId][player].inventory[ids[i]].amount = amounts[i];
}
}
function changeAccountOwnership(
address oldPlayer,
uint256 accountId,
address newPlayer
) private {
uint256[] memory itemCount = getItemAmounts(oldPlayer, accountId);
itemsContract.transferBatchFromGame(
oldPlayer,
newPlayer,
account[accountId][oldPlayer].items,
itemCount,
"0x0"
);
account[accountId][newPlayer].owner = newPlayer;
account[accountId][newPlayer].accountId = account[accountId][oldPlayer]
.accountId;
account[accountId][newPlayer].items = account[accountId][oldPlayer]
.items;
account[accountId][newPlayer].deleted = account[accountId][oldPlayer]
.deleted;
uint256[] memory ids = account[accountId][newPlayer].items;
for (uint256 i = 0; i < ids.length; ++i) {
account[accountId][newPlayer].inventory[ids[i]].amount = account[
accountId
][oldPlayer].inventory[ids[i]].amount;
}
delete account[accountId][oldPlayer];
account[accountId][oldPlayer].deleted = true;
players[newPlayer] = players[oldPlayer];
players[oldPlayer] = 0;
emit AccountSwapped(oldPlayer, newPlayer);
}
function deleteAccountItems(address player, uint256 accountId)
private
onlyOwner
{
uint256[] memory itemCount = getItemAmounts(player, accountId);
itemsContract.burnBatch(
player,
account[accountId][player].items,
itemCount
);
}
function playerReceivesItemFromGame(
address player,
uint256 accountId,
uint256 itemId
) public onlyOwner {
itemsContract.transferFromGame(
address(itemsContract),
player,
itemId,
1,
"0x0"
);
addItemToAccount(player, accountId, itemId, 1);
}
function playerReceivesMultItemFromGame(
address player,
uint256 accountId,
uint256[] memory itemIds
) public onlyOwner {
for (uint256 i = 0; i < itemIds.length; i++) {
playerReceivesItemFromGame(player, accountId, itemIds[i]);
}
}
function playerReceivesItemFromMarket(
address fromPlayer,
address toPlayer,
uint256 itemId,
uint256 amount
) public {
require(
_msgSender() == address(itemsContract),
"La Vie: Function callable only on trade."
);
uint256 fromAccountId = players[fromPlayer];
uint256 toAccountId = players[toPlayer];
addItemToAccount(toPlayer, toAccountId, itemId, amount);
deleteItemFromAccount(fromPlayer, fromAccountId, itemId, amount);
}
function playerReceivesMultItemFromMarket(
address fromPlayer,
address toPlayer,
uint256[] memory itemIds,
uint256[] memory amounts
) public {
require(
_msgSender() == address(itemsContract),
"La Vie: Function callable only on trade."
);
for (uint256 i = 0; i < itemIds.length; i++) {
playerReceivesItemFromMarket(
fromPlayer,
toPlayer,
itemIds[i],
amounts[i]
);
}
}
function addItemToAccount(
address player,
uint256 accountId,
uint256 itemId,
uint256 amount
) internal {
if(account[accountId][player].inventory[itemId].amount == 0) {
account[accountId][player].items.push(itemId);
}
account[accountId][player].inventory[itemId].amount += amount;
emit ItemReceived(player, accountId, itemId);
}
function deleteItemFromAccount(
address player,
uint256 accountId,
uint256 itemId,
uint256 amount
) internal {
uint256 arrLength = account[accountId][player].items.length;
for (uint256 i = 0; i < arrLength; i++) {
if (account[accountId][player].items[i] == itemId) {
if (i == arrLength - 1) {
delete account[accountId][player].items[i];
} else {
account[accountId][player].items[i] = account[accountId][
player
].items[arrLength - 1];
delete account[accountId][player].items[arrLength - 1];
}
break;
}
}
account[accountId][player].items.pop();
account[accountId][player].inventory[itemId].amount -= amount;
}
function getItemAmounts(address player, uint256 accountId)
private
view
returns (uint256[] memory)
{
uint256[] memory ids = account[accountId][player].items;
uint256[] memory amounts = new uint256[](ids.length);
for (uint256 i = 0; i < ids.length; ++i) {
amounts[i] = account[accountId][player].inventory[ids[i]].amount;
}
return amounts;
}
function itemExists(uint256 itemId) public view returns (bool) {
return itemsContract.exists(itemId);
}
function isApprovedForAll(address _owner, address _operator)
public
view
override
returns (bool isOperator)
{
// if OpenSea's ERC721 Proxy Address is detected, auto-return true
if (
_operator == address(MARKETPLACE_OPERATOR) ||
_operator == address(ACCOUNT_MANAGER)
) {
return true;
}
// otherwise, use the default ERC721.isApprovedForAll()
return super.isApprovedForAll(_owner, _operator);
}
function _msgSender() internal view override returns (address sender) {
return ContextMixin.msgSender();
}
function GetPlayerIdAndData(address player) view external returns(address, uint256, uint256[] memory) {
uint256 playerId = players[player];
return (
account[playerId][player].owner,
account[playerId][player].accountId,
account[playerId][player].items
);
}
function setTokenUri(uint256 tokenId, string memory playerTokenURI) public onlyOwner {
require(exists(tokenId));
super._setTokenURI(tokenId, playerTokenURI);
}
}
|
assuming items are pre-mintedinitiate w/ 3 basic items and 1 rareknife, brass knuckles, bat (1,5,9)rare item should be random? Init chainlink random assuming items are pre-mintedinitiate w/ 2 basic itemsknife, batitemsContract.safeBatchTransferFrom(address(itemsContract), player, [1, 9], [1, 1], "");skipbasic accounts, tier 1 do not get any items.
|
function initAccountItems(
address player,
uint256 accountId,
uint256 accountType
) private onlyOwner {
if (accountType == 3) {
uint256[] memory ids = new uint256[](3);
uint256[] memory amounts = new uint256[](3);
ids[0] = 1;
ids[1] = 5;
ids[2] = 9;
amounts[0] = 1;
amounts[1] = 1;
amounts[2] = 1;
transferItemsFromGameToAccount(player, accountId, ids, amounts);
uint256[] memory ids = new uint256[](2);
uint256[] memory amounts = new uint256[](2);
ids[0] = 1;
ids[1] = 9;
amounts[0] = 1;
amounts[1] = 1;
transferItemsFromGameToAccount(player, accountId, ids, amounts);
}
}
| 12,951,878 |
pragma solidity ^0.8.0;
interface ISupplyController {
function mintIncentive(address addr) external;
function mintableIncentive(address addr) external view returns (uint);
function mint(address token, address owner, uint amount) external;
function changeSupplyController(address newSupplyController) external;
}
interface IADXToken {
function transfer(address to, uint256 amount) external returns (bool);
function transferFrom(address from, address to, uint256 amount) external returns (bool);
function approve(address spender, uint256 amount) external returns (bool);
function balanceOf(address spender) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function totalSupply() external returns (uint);
function supplyController() external view returns (ISupplyController);
function changeSupplyController(address newSupplyController) external;
function mint(address owner, uint amount) external;
}
interface IADXLoyaltyPoolToken {
function mintIncentive() external;
function setIncentive(uint newIncentive) external;
function ADXToken() external view returns (IADXToken);
}
interface IChainlinkSimple {
function latestAnswer() external view returns (uint);
}
// NOTE: If this needs to be upgraded, we just deploy a new instance and remove the governance rights
// of the old instance and set rights for the new instance
contract ADXLoyaltyPoolIncentiveController {
IChainlinkSimple public constant ADXUSDOracle = IChainlinkSimple(0x231e764B44b2C1b7Ca171fa8021A24ed520Cde10);
IADXLoyaltyPoolToken public immutable loyaltyPool;
constructor(IADXLoyaltyPoolToken lpt) {
loyaltyPool = lpt;
}
function adjustIncentive() external {
// Mint the current incurred incentive before changing the rate,
// otherwise new rate would be applied for the entire period since the last mint
loyaltyPool.mintIncentive();
// At some point we might enable bonus periods:
// if (block.timestamp < ...) { ... }
// Or overinflation protection
// if (loyaltyPool.ADXToken().totalSupply() > ...) { ... }
// Reset the rate based on the price from the Chainlink oracle
uint price = ADXUSDOracle.latestAnswer();
require(price > 0, 'INVALID_ANSWER');
if (price < 0.05*10**8) {
loyaltyPool.setIncentive(uint(0.05*10**18));
} else if (price < 0.10*10**8) {
loyaltyPool.setIncentive(uint(0.10*10**18));
} else if (price < 0.20*10**8) {
loyaltyPool.setIncentive(uint(0.20*10**18));
} else if (price < 0.35*10**8) {
loyaltyPool.setIncentive(uint(0.25*10**18));
} else if (price < 0.50*10**8) {
loyaltyPool.setIncentive(uint(0.30*10**18));
} else if (price < 1.00*10**8) {
loyaltyPool.setIncentive(uint(0.35*10**18));
} else if (price < 2.00*10**8) {
loyaltyPool.setIncentive(uint(0.38*10**18));
} else if (price < 2.50*10**8) {
loyaltyPool.setIncentive(uint(0.40*10**18));
} else {
loyaltyPool.setIncentive(uint(0.45*10**18));
}
}
}
|
Mint the current incurred incentive before changing the rate, otherwise new rate would be applied for the entire period since the last mint At some point we might enable bonus periods: if (block.timestamp < ...) { ... } Or overinflation protection if (loyaltyPool.ADXToken().totalSupply() > ...) { ... } Reset the rate based on the price from the Chainlink oracle
|
function adjustIncentive() external {
loyaltyPool.mintIncentive();
uint price = ADXUSDOracle.latestAnswer();
require(price > 0, 'INVALID_ANSWER');
if (price < 0.05*10**8) {
loyaltyPool.setIncentive(uint(0.05*10**18));
loyaltyPool.setIncentive(uint(0.10*10**18));
loyaltyPool.setIncentive(uint(0.20*10**18));
loyaltyPool.setIncentive(uint(0.25*10**18));
loyaltyPool.setIncentive(uint(0.30*10**18));
loyaltyPool.setIncentive(uint(0.35*10**18));
loyaltyPool.setIncentive(uint(0.38*10**18));
loyaltyPool.setIncentive(uint(0.40*10**18));
loyaltyPool.setIncentive(uint(0.45*10**18));
}
}
| 5,982,121 |
// File: contracts/interfaces/IERC20.sol
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
* From https://github.com/OpenZeppelin/openzeppelin-contracts
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: contracts/interfaces/IStakedAave.sol
pragma solidity 0.6.12;
interface IStakedAave {
function stake(address to, uint256 amount) external;
function redeem(address to, uint256 amount) external;
function cooldown() external;
function claimRewards(address to, uint256 amount) external;
}
// File: contracts/interfaces/ITransferHook.sol
pragma solidity 0.6.12;
interface ITransferHook {
function onTransfer(address from, address to, uint256 amount) external;
}
// File: contracts/lib/Context.sol
pragma solidity 0.6.12;
/**
* @dev From https://github.com/OpenZeppelin/openzeppelin-contracts
* 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 virtual view returns (address payable) {
return msg.sender;
}
function _msgData() internal virtual view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: contracts/interfaces/IERC20Detailed.sol
pragma solidity 0.6.12;
/**
* @dev Interface for ERC20 including metadata
**/
interface IERC20Detailed is IERC20 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
}
// File: contracts/lib/SafeMath.sol
pragma solidity 0.6.12;
/**
* @dev From https://github.com/OpenZeppelin/openzeppelin-contracts
* 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) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, 'SafeMath: modulo by zero');
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: contracts/lib/ERC20.sol
pragma solidity 0.6.12;
/**
* @title ERC20
* @notice Basic ERC20 implementation
* @author Aave
**/
contract ERC20 is Context, IERC20, IERC20Detailed {
using SafeMath for uint256;
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(
string memory name,
string memory symbol,
uint8 decimals
) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
/**
* @return the name of the token
**/
function name() public override view returns (string memory) {
return _name;
}
/**
* @return the symbol of the token
**/
function symbol() public override view returns (string memory) {
return _symbol;
}
/**
* @return the decimals of the token
**/
function decimals() public override view returns (uint8) {
return _decimals;
}
/**
* @return the total supply of the token
**/
function totalSupply() public override view returns (uint256) {
return _totalSupply;
}
/**
* @return the balance of the token
**/
function balanceOf(address account) public override view returns (uint256) {
return _balances[account];
}
/**
* @dev executes a transfer of tokens from msg.sender to recipient
* @param recipient the recipient of the tokens
* @param amount the amount of tokens being transferred
* @return true if the transfer succeeds, false otherwise
**/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev returns the allowance of spender on the tokens owned by owner
* @param owner the owner of the tokens
* @param spender the user allowed to spend the owner's tokens
* @return the amount of owner's tokens spender is allowed to spend
**/
function allowance(address owner, address spender)
public
virtual
override
view
returns (uint256)
{
return _allowances[owner][spender];
}
/**
* @dev allows spender to spend the tokens owned by msg.sender
* @param spender the user allowed to spend msg.sender tokens
* @return true
**/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev executes a transfer of token from sender to recipient, if msg.sender is allowed to do so
* @param sender the owner of the tokens
* @param recipient the recipient of the tokens
* @param amount the amount of tokens being transferred
* @return true if the transfer succeeds, false otherwise
**/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(
sender,
_msgSender(),
_allowances[sender][_msgSender()].sub(amount, 'ERC20: transfer amount exceeds allowance')
);
return true;
}
/**
* @dev increases the allowance of spender to spend msg.sender tokens
* @param spender the user allowed to spend on behalf of msg.sender
* @param addedValue the amount being added to the allowance
* @return true
**/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev decreases the allowance of spender to spend msg.sender tokens
* @param spender the user allowed to spend on behalf of msg.sender
* @param subtractedValue the amount being subtracted to the allowance
* @return true
**/
function decreaseAllowance(address spender, uint256 subtractedValue)
public
virtual
returns (bool)
{
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].sub(
subtractedValue,
'ERC20: decreased allowance below zero'
)
);
return true;
}
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), 'ERC20: transfer from the zero address');
require(recipient != address(0), 'ERC20: transfer to the zero address');
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, 'ERC20: transfer amount exceeds balance');
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), 'ERC20: mint to the zero address');
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), 'ERC20: burn from the zero address');
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, 'ERC20: burn amount exceeds balance');
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
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);
}
function _setName(string memory newName) internal {
_name = newName;
}
function _setSymbol(string memory newSymbol) internal {
_symbol = newSymbol;
}
function _setDecimals(uint8 newDecimals) internal {
_decimals = newDecimals;
}
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
// File: contracts/lib/ERC20WithSnapshot.sol
pragma solidity 0.6.12;
/**
* @title ERC20WithSnapshot
* @notice ERC20 including snapshots of balances on transfer-related actions
* @author Aave
**/
contract ERC20WithSnapshot is ERC20 {
/// @dev snapshot of a value on a specific block, used for balances
struct Snapshot {
uint128 blockNumber;
uint128 value;
}
mapping (address => mapping (uint256 => Snapshot)) public _snapshots;
mapping (address => uint256) public _countsSnapshots;
/// @dev reference to the Aave governance contract to call (if initialized) on _beforeTokenTransfer
/// !!! IMPORTANT The Aave governance is considered a trustable contract, being its responsibility
/// to control all potential reentrancies by calling back the this contract
ITransferHook public _aaveGovernance;
event SnapshotDone(address owner, uint128 oldValue, uint128 newValue);
constructor(string memory name, string memory symbol, uint8 decimals) public ERC20(name, symbol, decimals) {}
function _setAaveGovernance(ITransferHook aaveGovernance) internal virtual {
_aaveGovernance = aaveGovernance;
}
/**
* @dev Writes a snapshot for an owner of tokens
* @param owner The owner of the tokens
* @param oldValue The value before the operation that is gonna be executed after the snapshot
* @param newValue The value after the operation
*/
function _writeSnapshot(address owner, uint128 oldValue, uint128 newValue) internal virtual {
uint128 currentBlock = uint128(block.number);
uint256 ownerCountOfSnapshots = _countsSnapshots[owner];
mapping (uint256 => Snapshot) storage snapshotsOwner = _snapshots[owner];
// Doing multiple operations in the same block
if (ownerCountOfSnapshots != 0 && snapshotsOwner[ownerCountOfSnapshots.sub(1)].blockNumber == currentBlock) {
snapshotsOwner[ownerCountOfSnapshots.sub(1)].value = newValue;
} else {
snapshotsOwner[ownerCountOfSnapshots] = Snapshot(currentBlock, newValue);
_countsSnapshots[owner] = ownerCountOfSnapshots.add(1);
}
emit SnapshotDone(owner, oldValue, newValue);
}
/**
* @dev Writes a snapshot before any operation involving transfer of value: _transfer, _mint and _burn
* - On _transfer, it writes snapshots for both "from" and "to"
* - On _mint, only for _to
* - On _burn, only for _from
* @param from the from address
* @param to the to address
* @param amount the amount to transfer
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal override {
if (from == to) {
return;
}
if (from != address(0)) {
uint256 fromBalance = balanceOf(from);
_writeSnapshot(from, uint128(fromBalance), uint128(fromBalance.sub(amount)));
}
if (to != address(0)) {
uint256 toBalance = balanceOf(to);
_writeSnapshot(to, uint128(toBalance), uint128(toBalance.add(amount)));
}
// caching the aave governance address to avoid multiple state loads
ITransferHook aaveGovernance = _aaveGovernance;
if (aaveGovernance != ITransferHook(0)) {
aaveGovernance.onTransfer(from, to, amount);
}
}
}
// File: contracts/lib/Address.sol
pragma solidity 0.6.12;
/**
* @dev Collection of functions related to the address type
* From https://github.com/OpenZeppelin/openzeppelin-contracts
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly {
codehash := extcodehash(account)
}
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, 'Address: insufficient balance');
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{value: amount}('');
require(success, 'Address: unable to send value, recipient may have reverted');
}
}
// File: contracts/lib/SafeERC20.sol
pragma solidity 0.6.12;
/**
* @title SafeERC20
* @dev From https://github.com/OpenZeppelin/openzeppelin-contracts
* 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));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: contracts/utils/VersionedInitializable.sol
pragma solidity 0.6.12;
/**
* @title VersionedInitializable
*
* @dev Helper contract to support initializer functions. To use it, replace
* the constructor with a function that has the `initializer` modifier.
* WARNING: Unlike constructors, initializer functions must be manually
* invoked. This applies both to deploying an Initializable contract, as well
* as extending an Initializable contract via inheritance.
* WARNING: When used with inheritance, manual care must be taken to not invoke
* a parent initializer twice, or ensure that all initializers are idempotent,
* because this is not dealt with automatically as with constructors.
*
* @author Aave, inspired by the OpenZeppelin Initializable contract
*/
abstract contract VersionedInitializable {
/**
* @dev Indicates that the contract has been initialized.
*/
uint256 internal lastInitializedRevision = 0;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
uint256 revision = getRevision();
require(
revision > lastInitializedRevision,
'Contract instance has already been initialized'
);
lastInitializedRevision = revision;
_;
}
/// @dev returns the revision number of the contract.
/// Needs to be defined in the inherited class as a constant.
function getRevision() internal virtual pure returns (uint256);
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
// File: contracts/lib/DistributionTypes.sol
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
library DistributionTypes {
struct AssetConfigInput {
uint128 emissionPerSecond;
uint256 totalStaked;
address underlyingAsset;
}
struct UserStakeInput {
address underlyingAsset;
uint256 stakedByUser;
uint256 totalStaked;
}
}
// File: contracts/interfaces/IAaveDistributionManager.sol
pragma solidity 0.6.12;
interface IAaveDistributionManager {
function configureAssets(DistributionTypes.AssetConfigInput[] calldata assetsConfigInput) external;
}
// File: contracts/stake/AaveDistributionManager.sol
pragma solidity 0.6.12;
/**
* @title AaveDistributionManager
* @notice Accounting contract to manage multiple staking distributions
* @author Aave
**/
contract AaveDistributionManager is IAaveDistributionManager {
using SafeMath for uint256;
struct AssetData {
uint128 emissionPerSecond;
uint128 lastUpdateTimestamp;
uint256 index;
mapping(address => uint256) users;
}
uint256 public immutable DISTRIBUTION_END;
address public immutable EMISSION_MANAGER;
uint8 public constant PRECISION = 18;
mapping(address => AssetData) public assets;
event AssetConfigUpdated(address indexed asset, uint256 emission);
event AssetIndexUpdated(address indexed asset, uint256 index);
event UserIndexUpdated(address indexed user, address indexed asset, uint256 index);
constructor(address emissionManager, uint256 distributionDuration) public {
DISTRIBUTION_END = block.timestamp.add(distributionDuration);
EMISSION_MANAGER = emissionManager;
}
/**
* @dev Configures the distribution of rewards for a list of assets
* @param assetsConfigInput The list of configurations to apply
**/
function configureAssets(DistributionTypes.AssetConfigInput[] calldata assetsConfigInput) external override {
require(msg.sender == EMISSION_MANAGER, 'ONLY_EMISSION_MANAGER');
for (uint256 i = 0; i < assetsConfigInput.length; i++) {
AssetData storage assetConfig = assets[assetsConfigInput[i].underlyingAsset];
_updateAssetStateInternal(
assetsConfigInput[i].underlyingAsset,
assetConfig,
assetsConfigInput[i].totalStaked
);
assetConfig.emissionPerSecond = assetsConfigInput[i].emissionPerSecond;
emit AssetConfigUpdated(
assetsConfigInput[i].underlyingAsset,
assetsConfigInput[i].emissionPerSecond
);
}
}
/**
* @dev Updates the state of one distribution, mainly rewards index and timestamp
* @param underlyingAsset The address used as key in the distribution, for example sAAVE or the aTokens addresses on Aave
* @param assetConfig Storage pointer to the distribution's config
* @param totalStaked Current total of staked assets for this distribution
* @return The new distribution index
**/
function _updateAssetStateInternal(
address underlyingAsset,
AssetData storage assetConfig,
uint256 totalStaked
) internal returns (uint256) {
uint256 oldIndex = assetConfig.index;
uint128 lastUpdateTimestamp = assetConfig.lastUpdateTimestamp;
if (block.timestamp == lastUpdateTimestamp) {
return oldIndex;
}
uint256 newIndex = _getAssetIndex(
oldIndex,
assetConfig.emissionPerSecond,
lastUpdateTimestamp,
totalStaked
);
if (newIndex != oldIndex) {
assetConfig.index = newIndex;
emit AssetIndexUpdated(underlyingAsset, newIndex);
}
assetConfig.lastUpdateTimestamp = uint128(block.timestamp);
return newIndex;
}
/**
* @dev Updates the state of an user in a distribution
* @param user The user's address
* @param asset The address of the reference asset of the distribution
* @param stakedByUser Amount of tokens staked by the user in the distribution at the moment
* @param totalStaked Total tokens staked in the distribution
* @return The accrued rewards for the user until the moment
**/
function _updateUserAssetInternal(
address user,
address asset,
uint256 stakedByUser,
uint256 totalStaked
) internal returns (uint256) {
AssetData storage assetData = assets[asset];
uint256 userIndex = assetData.users[user];
uint256 accruedRewards = 0;
uint256 newIndex = _updateAssetStateInternal(asset, assetData, totalStaked);
if (userIndex != newIndex) {
if (stakedByUser != 0) {
accruedRewards = _getRewards(stakedByUser, newIndex, userIndex);
}
assetData.users[user] = newIndex;
emit UserIndexUpdated(user, asset, newIndex);
}
return accruedRewards;
}
/**
* @dev Used by "frontend" stake contracts to update the data of an user when claiming rewards from there
* @param user The address of the user
* @param stakes List of structs of the user data related with his stake
* @return The accrued rewards for the user until the moment
**/
function _claimRewards(address user, DistributionTypes.UserStakeInput[] memory stakes)
internal
returns (uint256)
{
uint256 accruedRewards = 0;
for (uint256 i = 0; i < stakes.length; i++) {
accruedRewards = accruedRewards.add(
_updateUserAssetInternal(
user,
stakes[i].underlyingAsset,
stakes[i].stakedByUser,
stakes[i].totalStaked
)
);
}
return accruedRewards;
}
/**
* @dev Return the accrued rewards for an user over a list of distribution
* @param user The address of the user
* @param stakes List of structs of the user data related with his stake
* @return The accrued rewards for the user until the moment
**/
function _getUnclaimedRewards(address user, DistributionTypes.UserStakeInput[] memory stakes)
internal
view
returns (uint256)
{
uint256 accruedRewards = 0;
for (uint256 i = 0; i < stakes.length; i++) {
AssetData storage assetConfig = assets[stakes[i].underlyingAsset];
uint256 assetIndex = _getAssetIndex(
assetConfig.index,
assetConfig.emissionPerSecond,
assetConfig.lastUpdateTimestamp,
stakes[i].totalStaked
);
accruedRewards = accruedRewards.add(
_getRewards(stakes[i].stakedByUser, assetIndex, assetConfig.users[user])
);
}
return accruedRewards;
}
/**
* @dev Internal function for the calculation of user's rewards on a distribution
* @param principalUserBalance Amount staked by the user on a distribution
* @param reserveIndex Current index of the distribution
* @param userIndex Index stored for the user, representation his staking moment
* @return The rewards
**/
function _getRewards(
uint256 principalUserBalance,
uint256 reserveIndex,
uint256 userIndex
) internal pure returns (uint256) {
return principalUserBalance.mul(reserveIndex.sub(userIndex)).div(10**uint256(PRECISION));
}
/**
* @dev Calculates the next value of an specific distribution index, with validations
* @param currentIndex Current index of the distribution
* @param emissionPerSecond Representing the total rewards distributed per second per asset unit, on the distribution
* @param lastUpdateTimestamp Last moment this distribution was updated
* @param totalBalance of tokens considered for the distribution
* @return The new index.
**/
function _getAssetIndex(
uint256 currentIndex,
uint256 emissionPerSecond,
uint128 lastUpdateTimestamp,
uint256 totalBalance
) internal view returns (uint256) {
if (
emissionPerSecond == 0 ||
totalBalance == 0 ||
lastUpdateTimestamp == block.timestamp ||
lastUpdateTimestamp >= DISTRIBUTION_END
) {
return currentIndex;
}
uint256 currentTimestamp = block.timestamp > DISTRIBUTION_END
? DISTRIBUTION_END
: block.timestamp;
uint256 timeDelta = currentTimestamp.sub(lastUpdateTimestamp);
return
emissionPerSecond.mul(timeDelta).mul(10**uint256(PRECISION)).div(totalBalance).add(
currentIndex
);
}
/**
* @dev Returns the data of an user on a distribution
* @param user Address of the user
* @param asset The address of the reference asset of the distribution
* @return The new index
**/
function getUserAssetData(address user, address asset) public view returns (uint256) {
return assets[asset].users[user];
}
}
// File: contracts/stake/StakedToken.sol
pragma solidity 0.6.12;
/**
* @title StakedToken
* @notice Contract to stake Aave token, tokenize the position and get rewards, inheriting from a distribution manager contract
* @author Aave
**/
contract StakedToken is IStakedAave, ERC20WithSnapshot, VersionedInitializable, AaveDistributionManager {
using SafeERC20 for IERC20;
uint256 public constant REVISION = 1;
IERC20 public immutable STAKED_TOKEN;
IERC20 public immutable REWARD_TOKEN;
uint256 public immutable COOLDOWN_SECONDS;
/// @notice Seconds available to redeem once the cooldown period is fullfilled
uint256 public immutable UNSTAKE_WINDOW;
/// @notice Address to pull from the rewards, needs to have approved this contract
address public immutable REWARDS_VAULT;
mapping(address => uint256) public stakerRewardsToClaim;
mapping(address => uint256) public stakersCooldowns;
event Staked(address indexed from, address indexed onBehalfOf, uint256 amount);
event Redeem(address indexed from, address indexed to, uint256 amount);
event RewardsAccrued(address user, uint256 amount);
event RewardsClaimed(address indexed from, address indexed to, uint256 amount);
event Cooldown(address indexed user);
constructor(
IERC20 stakedToken,
IERC20 rewardToken,
uint256 cooldownSeconds,
uint256 unstakeWindow,
address rewardsVault,
address emissionManager,
uint128 distributionDuration,
string memory name,
string memory symbol,
uint8 decimals
) public ERC20WithSnapshot(name, symbol, decimals) AaveDistributionManager(emissionManager, distributionDuration) {
STAKED_TOKEN = stakedToken;
REWARD_TOKEN = rewardToken;
COOLDOWN_SECONDS = cooldownSeconds;
UNSTAKE_WINDOW = unstakeWindow;
REWARDS_VAULT = rewardsVault;
}
/**
* @dev Called by the proxy contract
**/
function initialize(ITransferHook aaveGovernance, string calldata name, string calldata symbol, uint8 decimals) external initializer {
_setName(name);
_setSymbol(symbol);
_setDecimals(decimals);
_setAaveGovernance(aaveGovernance);
}
function stake(address onBehalfOf, uint256 amount) external override {
require(amount != 0, 'INVALID_ZERO_AMOUNT');
uint256 balanceOfUser = balanceOf(onBehalfOf);
uint256 accruedRewards = _updateUserAssetInternal(
onBehalfOf,
address(this),
balanceOfUser,
totalSupply()
);
if (accruedRewards != 0) {
emit RewardsAccrued(onBehalfOf, accruedRewards);
stakerRewardsToClaim[onBehalfOf] = stakerRewardsToClaim[onBehalfOf].add(accruedRewards);
}
stakersCooldowns[onBehalfOf] = getNextCooldownTimestamp(0, amount, onBehalfOf, balanceOfUser);
_mint(onBehalfOf, amount);
IERC20(STAKED_TOKEN).safeTransferFrom(msg.sender, address(this), amount);
emit Staked(msg.sender, onBehalfOf, amount);
}
/**
* @dev Redeems staked tokens, and stop earning rewards
* @param to Address to redeem to
* @param amount Amount to redeem
**/
function redeem(address to, uint256 amount) external override {
require(amount != 0, 'INVALID_ZERO_AMOUNT');
//solium-disable-next-line
uint256 cooldownStartTimestamp = stakersCooldowns[msg.sender];
require(
block.timestamp > cooldownStartTimestamp.add(COOLDOWN_SECONDS),
'INSUFFICIENT_COOLDOWN'
);
require(
block.timestamp.sub(cooldownStartTimestamp.add(COOLDOWN_SECONDS)) <= UNSTAKE_WINDOW,
'UNSTAKE_WINDOW_FINISHED'
);
uint256 balanceOfMessageSender = balanceOf(msg.sender);
uint256 amountToRedeem = (amount > balanceOfMessageSender) ? balanceOfMessageSender : amount;
_updateCurrentUnclaimedRewards(msg.sender, balanceOfMessageSender, true);
_burn(msg.sender, amountToRedeem);
if (balanceOfMessageSender.sub(amountToRedeem) == 0) {
stakersCooldowns[msg.sender] = 0;
}
IERC20(STAKED_TOKEN).safeTransfer(to, amountToRedeem);
emit Redeem(msg.sender, to, amountToRedeem);
}
/**
* @dev Activates the cooldown period to unstake
* - It can't be called if the user is not staking
**/
function cooldown() external override {
require(balanceOf(msg.sender) != 0, "INVALID_BALANCE_ON_COOLDOWN");
//solium-disable-next-line
stakersCooldowns[msg.sender] = block.timestamp;
emit Cooldown(msg.sender);
}
/**
* @dev Claims an `amount` of `REWARD_TOKEN` to the address `to`
* @param to Address to stake for
* @param amount Amount to stake
**/
function claimRewards(address to, uint256 amount) external override {
uint256 newTotalRewards = _updateCurrentUnclaimedRewards(
msg.sender,
balanceOf(msg.sender),
false
);
uint256 amountToClaim = (amount == type(uint256).max) ? newTotalRewards : amount;
stakerRewardsToClaim[msg.sender] = newTotalRewards.sub(amountToClaim, "INVALID_AMOUNT");
REWARD_TOKEN.safeTransferFrom(REWARDS_VAULT, to, amountToClaim);
emit RewardsClaimed(msg.sender, to, amountToClaim);
}
/**
* @dev Internal ERC20 _transfer of the tokenized staked tokens
* @param from Address to transfer from
* @param to Address to transfer to
* @param amount Amount to transfer
**/
function _transfer(
address from,
address to,
uint256 amount
) internal override {
uint256 balanceOfFrom = balanceOf(from);
// Sender
_updateCurrentUnclaimedRewards(from, balanceOfFrom, true);
// Recipient
if (from != to) {
uint256 balanceOfTo = balanceOf(to);
_updateCurrentUnclaimedRewards(to, balanceOfTo, true);
uint256 previousSenderCooldown = stakersCooldowns[from];
stakersCooldowns[to] = getNextCooldownTimestamp(previousSenderCooldown, amount, to, balanceOfTo);
// if cooldown was set and whole balance of sender was transferred - clear cooldown
if (balanceOfFrom == amount && previousSenderCooldown != 0) {
stakersCooldowns[from] = 0;
}
}
super._transfer(from, to, amount);
}
/**
* @dev Updates the user state related with his accrued rewards
* @param user Address of the user
* @param userBalance The current balance of the user
* @param updateStorage Boolean flag used to update or not the stakerRewardsToClaim of the user
* @return The unclaimed rewards that were added to the total accrued
**/
function _updateCurrentUnclaimedRewards(
address user,
uint256 userBalance,
bool updateStorage
) internal returns (uint256) {
uint256 accruedRewards = _updateUserAssetInternal(
user,
address(this),
userBalance,
totalSupply()
);
uint256 unclaimedRewards = stakerRewardsToClaim[user].add(accruedRewards);
if (accruedRewards != 0) {
if (updateStorage) {
stakerRewardsToClaim[user] = unclaimedRewards;
}
emit RewardsAccrued(user, accruedRewards);
}
return unclaimedRewards;
}
/**
* @dev Calculates the how is gonna be a new cooldown timestamp depending on the sender/receiver situation
* - If the timestamp of the sender is "better" or the timestamp of the recipient is 0, we take the one of the recipient
* - Weighted average of from/to cooldown timestamps if:
* # The sender doesn't have the cooldown activated (timestamp 0).
* # The sender timestamp is expired
* # The sender has a "worse" timestamp
* - If the receiver's cooldown timestamp expired (too old), the next is 0
* @param fromCooldownTimestamp Cooldown timestamp of the sender
* @param amountToReceive Amount
* @param toAddress Address of the recipient
* @param toBalance Current balance of the receiver
* @return The new cooldown timestamp
**/
function getNextCooldownTimestamp(
uint256 fromCooldownTimestamp,
uint256 amountToReceive,
address toAddress,
uint256 toBalance
) public returns (uint256) {
uint256 toCooldownTimestamp = stakersCooldowns[toAddress];
if (toCooldownTimestamp == 0) {
return 0;
}
uint256 minimalValidCooldownTimestamp = block.timestamp.sub(COOLDOWN_SECONDS).sub(
UNSTAKE_WINDOW
);
if (minimalValidCooldownTimestamp > toCooldownTimestamp) {
toCooldownTimestamp = 0;
} else {
uint256 fromCooldownTimestamp = (minimalValidCooldownTimestamp > fromCooldownTimestamp)
? block.timestamp
: fromCooldownTimestamp;
if (fromCooldownTimestamp < toCooldownTimestamp) {
return toCooldownTimestamp;
} else {
toCooldownTimestamp = (
amountToReceive.mul(fromCooldownTimestamp).add(toBalance.mul(toCooldownTimestamp))
)
.div(amountToReceive.add(toBalance));
}
}
stakersCooldowns[toAddress] = toCooldownTimestamp;
return toCooldownTimestamp;
}
/**
* @dev Return the total rewards pending to claim by an staker
* @param staker The staker address
* @return The rewards
*/
function getTotalRewardsBalance(address staker) external view returns (uint256) {
DistributionTypes.UserStakeInput[] memory userStakeInputs
= new DistributionTypes.UserStakeInput[](1);
userStakeInputs[0] = DistributionTypes.UserStakeInput({
underlyingAsset: address(this),
stakedByUser: balanceOf(staker),
totalStaked: totalSupply()
});
return stakerRewardsToClaim[staker].add(_getUnclaimedRewards(staker, userStakeInputs));
}
/**
* @dev returns the revision of the implementation contract
* @return The revision
*/
function getRevision() internal override pure returns (uint256) {
return REVISION;
}
}
// File: contracts/stake/StakedAave.sol
pragma solidity 0.6.12;
/**
* @title StakedAave
* @notice StakedToken with AAVE token as staked token
* @author Aave
**/
contract StakedAave is StakedToken {
string internal constant NAME = 'Staked Aave';
string internal constant SYMBOL = 'stkAAVE';
uint8 internal constant DECIMALS = 18;
constructor(
IERC20 stakedToken,
IERC20 rewardToken,
uint256 cooldownSeconds,
uint256 unstakeWindow,
address rewardsVault,
address emissionManager,
uint128 distributionDuration
) public StakedToken(
stakedToken,
rewardToken,
cooldownSeconds,
unstakeWindow,
rewardsVault,
emissionManager,
distributionDuration,
NAME,
SYMBOL,
DECIMALS) {}
}
|
Writes a snapshot before any operation involving transfer of value: _transfer, _mint and _burn - On _transfer, it writes snapshots for both "from" and "to" - On _mint, only for _to - On _burn, only for _from from the from address to the to address amount the amount to transfer/
|
function _beforeTokenTransfer(address from, address to, uint256 amount) internal override {
if (from == to) {
return;
}
if (from != address(0)) {
uint256 fromBalance = balanceOf(from);
_writeSnapshot(from, uint128(fromBalance), uint128(fromBalance.sub(amount)));
}
if (to != address(0)) {
uint256 toBalance = balanceOf(to);
_writeSnapshot(to, uint128(toBalance), uint128(toBalance.add(amount)));
}
if (aaveGovernance != ITransferHook(0)) {
aaveGovernance.onTransfer(from, to, amount);
}
}
| 340,294 |
./full_match/5/0x1AB7ce989437c22a2528cAc2d26811D286e5f2a1/sources/contracts/FishyScam.sol
|
Phishers are using bait to attract fishers add a fiosh on a defined url add a big big fish on an url
|
interface PhisherAPI {
function addBigFish(string calldata _url) external payable;
function addPaSquale(string calldata _url) external payable;
pragma solidity ^0.8.15;
}
| 1,903,738 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/math/Math.sol";
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "./libraries/DecimalsConverter.sol";
import "./interfaces/IContractsRegistry.sol";
import "./interfaces/helpers/IPriceFeed.sol";
import "./interfaces/IClaimVoting.sol";
import "./interfaces/IPolicyBookRegistry.sol";
import "./interfaces/IReputationSystem.sol";
import "./interfaces/IReinsurancePool.sol";
import "./interfaces/IPolicyBook.sol";
import "./interfaces/tokens/IVBMI.sol";
import "./abstract/AbstractDependant.sol";
import "./Globals.sol";
contract ClaimVoting is IClaimVoting, Initializable, AbstractDependant {
using SafeMath for uint256;
using Math for uint256;
using EnumerableSet for EnumerableSet.UintSet;
IPriceFeed public priceFeed;
IERC20 public bmiToken;
IReinsurancePool public reinsurancePool;
IVBMI public vBMI;
IClaimingRegistry public claimingRegistry;
IPolicyBookRegistry public policyBookRegistry;
IReputationSystem public reputationSystem;
uint256 public stblDecimals;
uint256 public constant PERCENTAGE_50 = 50 * PRECISION;
uint256 public constant APPROVAL_PERCENTAGE = 66 * PRECISION;
uint256 public constant PENALTY_THRESHOLD = 11 * PRECISION;
uint256 public constant QUORUM = 10 * PRECISION;
uint256 public constant CALCULATION_REWARD_PER_DAY = PRECISION;
// claim index -> info
mapping(uint256 => VotingResult) internal _votings;
// voter -> claim indexes
mapping(address => EnumerableSet.UintSet) internal _myNotCalculatedVotes;
// voter -> voting indexes
mapping(address => EnumerableSet.UintSet) internal _myVotes;
// voter -> claim index -> vote index
mapping(address => mapping(uint256 => uint256)) internal _allVotesToIndex;
// vote index -> voting instance
mapping(uint256 => VotingInst) internal _allVotesByIndexInst;
EnumerableSet.UintSet internal _allVotesIndexes;
uint256 private _voteIndex;
event AnonymouslyVoted(uint256 claimIndex);
event VoteExposed(uint256 claimIndex, address voter, uint256 suggestedClaimAmount);
event VoteCalculated(uint256 claimIndex, address voter, VoteStatus status);
event RewardsForVoteCalculationSent(address voter, uint256 bmiAmount);
event RewardsForClaimCalculationSent(address calculator, uint256 bmiAmount);
event ClaimCalculated(uint256 claimIndex, address calculator);
modifier onlyPolicyBook() {
require(policyBookRegistry.isPolicyBook(msg.sender), "CV: Not a PolicyBook");
_;
}
function _isVoteAwaitingCalculation(uint256 index) internal view returns (bool) {
uint256 claimIndex = _allVotesByIndexInst[index].claimIndex;
return (_allVotesByIndexInst[index].status == VoteStatus.EXPOSED_PENDING &&
!claimingRegistry.isClaimPending(claimIndex));
}
function _isVoteAwaitingExposure(uint256 index) internal view returns (bool) {
uint256 claimIndex = _allVotesByIndexInst[index].claimIndex;
return (_allVotesByIndexInst[index].status == VoteStatus.ANONYMOUS_PENDING &&
claimingRegistry.isClaimExposablyVotable(claimIndex));
}
function _isVoteExpired(uint256 index) internal view returns (bool) {
uint256 claimIndex = _allVotesByIndexInst[index].claimIndex;
return (_allVotesByIndexInst[index].status == VoteStatus.ANONYMOUS_PENDING &&
!claimingRegistry.isClaimVotable(claimIndex));
}
function __ClaimVoting_init() external initializer {
_voteIndex = 1;
}
function setDependencies(IContractsRegistry _contractsRegistry)
external
override
onlyInjectorOrZero
{
priceFeed = IPriceFeed(_contractsRegistry.getPriceFeedContract());
claimingRegistry = IClaimingRegistry(_contractsRegistry.getClaimingRegistryContract());
policyBookRegistry = IPolicyBookRegistry(
_contractsRegistry.getPolicyBookRegistryContract()
);
reputationSystem = IReputationSystem(_contractsRegistry.getReputationSystemContract());
reinsurancePool = IReinsurancePool(_contractsRegistry.getReinsurancePoolContract());
vBMI = IVBMI(_contractsRegistry.getVBMIContract());
bmiToken = IERC20(_contractsRegistry.getBMIContract());
stblDecimals = ERC20(_contractsRegistry.getUSDTContract()).decimals();
}
/// @notice this function needs user's BMI approval of this address (check policybook)
function initializeVoting(
address claimer,
string calldata evidenceURI,
uint256 coverTokens,
bool appeal
) external override onlyPolicyBook {
require(coverTokens > 0, "CV: Claimer has no coverage");
// this checks claim duplicate && appeal logic
uint256 claimIndex =
claimingRegistry.submitClaim(claimer, msg.sender, evidenceURI, coverTokens, appeal);
uint256 onePercentInBMIToLock =
priceFeed.howManyBMIsInUSDT(
DecimalsConverter.convertFrom18(coverTokens.div(100), stblDecimals)
);
bmiToken.transferFrom(claimer, address(this), onePercentInBMIToLock); // needed approval
// reinsurancePrice variable was added later after a SC Upgrade and if user
// had bought policy before it was implemented, his value would be 0.
// So if it is zero, we should get it from protocol percentage fee only
// reinsurancePrice is equal to (paid * protocol percentage) - distributorFee.
// If user bought policy before upgrade, correct value is (paid * protocol).
IPolicyBook.PolicyHolder memory policyHolder = IPolicyBook(msg.sender).userStats(claimer);
uint256 reinsuranceTokensAmount = policyHolder.reinsurancePrice;
if (reinsuranceTokensAmount == 0) {
reinsuranceTokensAmount = policyHolder.paid.mul(20 * PRECISION).div(PERCENTAGE_100);
}
reinsuranceTokensAmount = Math.min(reinsuranceTokensAmount, coverTokens.div(100));
_votings[claimIndex].withdrawalAmount = coverTokens;
_votings[claimIndex].lockedBMIAmount = onePercentInBMIToLock;
_votings[claimIndex].reinsuranceTokensAmount = reinsuranceTokensAmount;
}
/// @dev check in BMIStaking when withdrawing, if true -> can withdraw
function canWithdraw(address user) external view override returns (bool) {
return _myNotCalculatedVotes[user].length() == 0;
}
/// @dev check when anonymously voting, if true -> can vote
function canVote(address user) public view override returns (bool) {
uint256 notCalculatedLength = _myNotCalculatedVotes[user].length();
for (uint256 i = 0; i < notCalculatedLength; i++) {
if (
_isVoteAwaitingCalculation(
_allVotesToIndex[user][_myNotCalculatedVotes[user].at(i)]
)
) {
return false;
}
}
return true;
}
function countVotes(address user) external view override returns (uint256) {
return _myVotes[user].length();
}
function voteStatus(uint256 index) public view override returns (VoteStatus) {
require(_allVotesIndexes.contains(index), "CV: Vote doesn't exist");
if (_isVoteAwaitingCalculation(index)) {
return VoteStatus.AWAITING_CALCULATION;
} else if (_isVoteAwaitingExposure(index)) {
return VoteStatus.AWAITING_EXPOSURE;
} else if (_isVoteExpired(index)) {
return VoteStatus.EXPIRED;
}
return _allVotesByIndexInst[index].status;
}
/// @dev use with claimingRegistry.countPendingClaims()
function whatCanIVoteFor(uint256 offset, uint256 limit)
external
view
override
returns (uint256 _claimsCount, PublicClaimInfo[] memory _votablesInfo)
{
uint256 to = (offset.add(limit)).min(claimingRegistry.countPendingClaims()).max(offset);
bool trustedVoter = reputationSystem.isTrustedVoter(msg.sender);
_claimsCount = 0;
_votablesInfo = new PublicClaimInfo[](to - offset);
for (uint256 i = offset; i < to; i++) {
uint256 index = claimingRegistry.pendingClaimIndexAt(i);
if (
_allVotesToIndex[msg.sender][index] == 0 &&
claimingRegistry.claimOwner(index) != msg.sender &&
claimingRegistry.isClaimAnonymouslyVotable(index) &&
(!claimingRegistry.isClaimAppeal(index) || trustedVoter)
) {
IClaimingRegistry.ClaimInfo memory claimInfo = claimingRegistry.claimInfo(index);
_votablesInfo[_claimsCount].claimIndex = index;
_votablesInfo[_claimsCount].claimer = claimInfo.claimer;
_votablesInfo[_claimsCount].policyBookAddress = claimInfo.policyBookAddress;
_votablesInfo[_claimsCount].evidenceURI = claimInfo.evidenceURI;
_votablesInfo[_claimsCount].appeal = claimInfo.appeal;
_votablesInfo[_claimsCount].claimAmount = claimInfo.claimAmount;
_votablesInfo[_claimsCount].time = claimInfo.dateSubmitted;
_votablesInfo[_claimsCount].time = _votablesInfo[_claimsCount]
.time
.add(claimingRegistry.anonymousVotingDuration(index))
.sub(block.timestamp);
_claimsCount++;
}
}
}
/// @dev use with claimingRegistry.countClaims()
function allClaims(uint256 offset, uint256 limit)
external
view
override
returns (AllClaimInfo[] memory _allClaimsInfo)
{
uint256 to = (offset.add(limit)).min(claimingRegistry.countClaims()).max(offset);
_allClaimsInfo = new AllClaimInfo[](to - offset);
for (uint256 i = offset; i < to; i++) {
uint256 index = claimingRegistry.claimIndexAt(i);
IClaimingRegistry.ClaimInfo memory claimInfo = claimingRegistry.claimInfo(index);
_allClaimsInfo[i - offset].publicClaimInfo.claimIndex = index;
_allClaimsInfo[i - offset].publicClaimInfo.claimer = claimInfo.claimer;
_allClaimsInfo[i - offset].publicClaimInfo.policyBookAddress = claimInfo
.policyBookAddress;
_allClaimsInfo[i - offset].publicClaimInfo.evidenceURI = claimInfo.evidenceURI;
_allClaimsInfo[i - offset].publicClaimInfo.appeal = claimInfo.appeal;
_allClaimsInfo[i - offset].publicClaimInfo.claimAmount = claimInfo.claimAmount;
_allClaimsInfo[i - offset].publicClaimInfo.time = claimInfo.dateSubmitted;
_allClaimsInfo[i - offset].finalVerdict = claimInfo.status;
if (
_allClaimsInfo[i - offset].finalVerdict == IClaimingRegistry.ClaimStatus.ACCEPTED
) {
_allClaimsInfo[i - offset].finalClaimAmount = _votings[index]
.votedAverageWithdrawalAmount;
}
if (claimingRegistry.canClaimBeCalculatedByAnyone(index)) {
_allClaimsInfo[i - offset].bmiCalculationReward = _getBMIRewardForCalculation(
index
);
}
}
}
/// @dev use with claimingRegistry.countPolicyClaimerClaims()
function myClaims(uint256 offset, uint256 limit)
external
view
override
returns (MyClaimInfo[] memory _myClaimsInfo)
{
uint256 to =
(offset.add(limit)).min(claimingRegistry.countPolicyClaimerClaims(msg.sender)).max(
offset
);
_myClaimsInfo = new MyClaimInfo[](to - offset);
for (uint256 i = offset; i < to; i++) {
uint256 index = claimingRegistry.claimOfOwnerIndexAt(msg.sender, i);
IClaimingRegistry.ClaimInfo memory claimInfo = claimingRegistry.claimInfo(index);
_myClaimsInfo[i - offset].index = index;
_myClaimsInfo[i - offset].policyBookAddress = claimInfo.policyBookAddress;
_myClaimsInfo[i - offset].evidenceURI = claimInfo.evidenceURI;
_myClaimsInfo[i - offset].appeal = claimInfo.appeal;
_myClaimsInfo[i - offset].claimAmount = claimInfo.claimAmount;
_myClaimsInfo[i - offset].finalVerdict = claimInfo.status;
if (_myClaimsInfo[i - offset].finalVerdict == IClaimingRegistry.ClaimStatus.ACCEPTED) {
_myClaimsInfo[i - offset].finalClaimAmount = _votings[index]
.votedAverageWithdrawalAmount;
} else if (
_myClaimsInfo[i - offset].finalVerdict ==
IClaimingRegistry.ClaimStatus.AWAITING_CALCULATION
) {
_myClaimsInfo[i - offset].bmiCalculationReward = _getBMIRewardForCalculation(
index
);
}
}
}
/// @dev use with countVotes()
function myVotes(uint256 offset, uint256 limit)
external
view
override
returns (MyVoteInfo[] memory _myVotesInfo)
{
uint256 to = (offset.add(limit)).min(_myVotes[msg.sender].length()).max(offset);
_myVotesInfo = new MyVoteInfo[](to - offset);
for (uint256 i = offset; i < to; i++) {
VotingInst storage myVote = _allVotesByIndexInst[_myVotes[msg.sender].at(i)];
uint256 index = myVote.claimIndex;
IClaimingRegistry.ClaimInfo memory claimInfo = claimingRegistry.claimInfo(index);
_myVotesInfo[i - offset].allClaimInfo.publicClaimInfo.claimIndex = index;
_myVotesInfo[i - offset].allClaimInfo.publicClaimInfo.claimer = claimInfo.claimer;
_myVotesInfo[i - offset].allClaimInfo.publicClaimInfo.policyBookAddress = claimInfo
.policyBookAddress;
_myVotesInfo[i - offset].allClaimInfo.publicClaimInfo.evidenceURI = claimInfo
.evidenceURI;
_myVotesInfo[i - offset].allClaimInfo.publicClaimInfo.appeal = claimInfo.appeal;
_myVotesInfo[i - offset].allClaimInfo.publicClaimInfo.claimAmount = claimInfo
.claimAmount;
_myVotesInfo[i - offset].allClaimInfo.publicClaimInfo.time = claimInfo.dateSubmitted;
_myVotesInfo[i - offset].allClaimInfo.finalVerdict = claimInfo.status;
if (
_myVotesInfo[i - offset].allClaimInfo.finalVerdict ==
IClaimingRegistry.ClaimStatus.ACCEPTED
) {
_myVotesInfo[i - offset].allClaimInfo.finalClaimAmount = _votings[index]
.votedAverageWithdrawalAmount;
}
_myVotesInfo[i - offset].suggestedAmount = myVote.suggestedAmount;
_myVotesInfo[i - offset].status = voteStatus(_myVotes[msg.sender].at(i));
if (_myVotesInfo[i - offset].status == VoteStatus.ANONYMOUS_PENDING) {
_myVotesInfo[i - offset].time = claimInfo
.dateSubmitted
.add(claimingRegistry.anonymousVotingDuration(index))
.sub(block.timestamp);
} else if (_myVotesInfo[i - offset].status == VoteStatus.AWAITING_EXPOSURE) {
_myVotesInfo[i - offset].encryptedVote = myVote.encryptedVote;
_myVotesInfo[i - offset].time = claimInfo
.dateSubmitted
.add(claimingRegistry.votingDuration(index))
.sub(block.timestamp);
}
}
}
/// @dev use with countVotes()
function myVotesUpdates(uint256 offset, uint256 limit)
external
view
override
returns (
uint256 _votesUpdatesCount,
uint256[] memory _claimIndexes,
VotesUpdatesInfo memory _myVotesUpdatesInfo
)
{
uint256 to = (offset.add(limit)).min(_myVotes[msg.sender].length()).max(offset);
_votesUpdatesCount = 0;
_claimIndexes = new uint256[](to - offset);
uint256 stblAmount;
uint256 bmiAmount;
uint256 bmiPenaltyAmount;
uint256 newReputation;
for (uint256 i = offset; i < to; i++) {
uint256 claimIndex = _allVotesByIndexInst[_myVotes[msg.sender].at(i)].claimIndex;
if (
_myNotCalculatedVotes[msg.sender].contains(claimIndex) &&
_isVoteAwaitingCalculation(_allVotesToIndex[msg.sender][claimIndex])
) {
_claimIndexes[_votesUpdatesCount] = claimIndex;
uint256 oldReputation = reputationSystem.reputation(msg.sender);
if (
_votings[claimIndex].votedYesPercentage >= PERCENTAGE_50 &&
_allVotesByIndexInst[_allVotesToIndex[msg.sender][claimIndex]]
.suggestedAmount >
0
) {
(stblAmount, bmiAmount, newReputation) = _calculateMajorityYesVote(
claimIndex,
msg.sender,
oldReputation
);
_myVotesUpdatesInfo.reputationChange += int256(
newReputation.sub(oldReputation)
);
} else if (
_votings[claimIndex].votedYesPercentage < PERCENTAGE_50 &&
_allVotesByIndexInst[_allVotesToIndex[msg.sender][claimIndex]]
.suggestedAmount ==
0
) {
(bmiAmount, newReputation) = _calculateMajorityNoVote(
claimIndex,
msg.sender,
oldReputation
);
_myVotesUpdatesInfo.reputationChange += int256(
newReputation.sub(oldReputation)
);
} else {
(bmiPenaltyAmount, newReputation) = _calculateMinorityVote(
claimIndex,
msg.sender,
oldReputation
);
_myVotesUpdatesInfo.reputationChange -= int256(
oldReputation.sub(newReputation)
);
_myVotesUpdatesInfo.stakeChange -= int256(bmiPenaltyAmount);
}
_myVotesUpdatesInfo.bmiReward = _myVotesUpdatesInfo.bmiReward.add(bmiAmount);
_myVotesUpdatesInfo.stblReward = _myVotesUpdatesInfo.stblReward.add(stblAmount);
_votesUpdatesCount++;
}
}
}
function _calculateAverages(
uint256 claimIndex,
uint256 stakedBMI,
uint256 suggestedClaimAmount,
uint256 reputationWithPrecision,
bool votedFor
) internal {
VotingResult storage info = _votings[claimIndex];
if (votedFor) {
uint256 votedPower = info.votedYesStakedBMIAmountWithReputation;
uint256 voterPower = stakedBMI.mul(reputationWithPrecision);
uint256 totalPower = votedPower.add(voterPower);
uint256 votedSuggestedPrice = info.votedAverageWithdrawalAmount.mul(votedPower);
uint256 voterSuggestedPrice = suggestedClaimAmount.mul(voterPower);
info.votedAverageWithdrawalAmount = votedSuggestedPrice.add(voterSuggestedPrice).div(
totalPower
);
info.votedYesStakedBMIAmountWithReputation = totalPower;
} else {
info.votedNoStakedBMIAmountWithReputation = info
.votedNoStakedBMIAmountWithReputation
.add(stakedBMI.mul(reputationWithPrecision));
}
info.allVotedStakedBMIAmount = info.allVotedStakedBMIAmount.add(stakedBMI);
}
function _modifyExposedVote(
address voter,
uint256 claimIndex,
uint256 suggestedClaimAmount,
uint256 stakedBMI,
bool accept
) internal {
uint256 index = _allVotesToIndex[voter][claimIndex];
_myNotCalculatedVotes[voter].add(claimIndex);
_allVotesByIndexInst[index].finalHash = 0;
delete _allVotesByIndexInst[index].encryptedVote;
_allVotesByIndexInst[index].suggestedAmount = suggestedClaimAmount;
_allVotesByIndexInst[index].stakedBMIAmount = stakedBMI;
_allVotesByIndexInst[index].accept = accept;
_allVotesByIndexInst[index].status = VoteStatus.EXPOSED_PENDING;
}
function _addAnonymousVote(
address voter,
uint256 claimIndex,
bytes32 finalHash,
string memory encryptedVote
) internal {
_myVotes[voter].add(_voteIndex);
_allVotesByIndexInst[_voteIndex].claimIndex = claimIndex;
_allVotesByIndexInst[_voteIndex].finalHash = finalHash;
_allVotesByIndexInst[_voteIndex].encryptedVote = encryptedVote;
_allVotesByIndexInst[_voteIndex].voter = voter;
_allVotesByIndexInst[_voteIndex].voterReputation = reputationSystem.reputation(voter);
// No need to set default ANONYMOUS_PENDING status
_allVotesToIndex[voter][claimIndex] = _voteIndex;
_allVotesIndexes.add(_voteIndex);
_voteIndex++;
}
function anonymouslyVoteBatch(
uint256[] calldata claimIndexes,
bytes32[] calldata finalHashes,
string[] calldata encryptedVotes
) external override {
require(canVote(msg.sender), "CV: There are awaiting votes");
require(
claimIndexes.length == finalHashes.length &&
claimIndexes.length == encryptedVotes.length,
"CV: Length mismatches"
);
for (uint256 i = 0; i < claimIndexes.length; i++) {
uint256 claimIndex = claimIndexes[i];
require(
claimingRegistry.isClaimAnonymouslyVotable(claimIndex),
"CV: Anonymous voting is over"
);
require(
claimingRegistry.claimOwner(claimIndex) != msg.sender,
"CV: Voter is the claimer"
);
require(
!claimingRegistry.isClaimAppeal(claimIndex) ||
reputationSystem.isTrustedVoter(msg.sender),
"CV: Not a trusted voter"
);
require(
_allVotesToIndex[msg.sender][claimIndex] == 0,
"CV: Already voted for this claim"
);
_addAnonymousVote(msg.sender, claimIndex, finalHashes[i], encryptedVotes[i]);
emit AnonymouslyVoted(claimIndex);
}
}
function exposeVoteBatch(
uint256[] calldata claimIndexes,
uint256[] calldata suggestedClaimAmounts,
bytes32[] calldata hashedSignaturesOfClaims
) external override {
require(
claimIndexes.length == suggestedClaimAmounts.length &&
claimIndexes.length == hashedSignaturesOfClaims.length,
"CV: Length mismatches"
);
uint256 stakedBMI = vBMI.balanceOf(msg.sender); // use canWithdaw function in vBMI staking
require(stakedBMI > 0, "CV: 0 staked BMI");
for (uint256 i = 0; i < claimIndexes.length; i++) {
uint256 claimIndex = claimIndexes[i];
uint256 voteIndex = _allVotesToIndex[msg.sender][claimIndex];
require(_allVotesIndexes.contains(voteIndex), "CV: Vote doesn't exist");
require(_isVoteAwaitingExposure(voteIndex), "CV: Vote is not awaiting");
bytes32 finalHash =
keccak256(
abi.encodePacked(
hashedSignaturesOfClaims[i],
_allVotesByIndexInst[voteIndex].encryptedVote,
suggestedClaimAmounts[i]
)
);
require(_allVotesByIndexInst[voteIndex].finalHash == finalHash, "CV: Data mismatches");
require(
_votings[claimIndex].withdrawalAmount >= suggestedClaimAmounts[i],
"CV: Amount succeds coverage"
);
bool voteFor = (suggestedClaimAmounts[i] > 0);
_calculateAverages(
claimIndex,
stakedBMI,
suggestedClaimAmounts[i],
_allVotesByIndexInst[voteIndex].voterReputation,
voteFor
);
_modifyExposedVote(
msg.sender,
claimIndex,
suggestedClaimAmounts[i],
stakedBMI,
voteFor
);
emit VoteExposed(claimIndex, msg.sender, suggestedClaimAmounts[i]);
}
}
function _getRewardRatio(
uint256 claimIndex,
address voter,
uint256 votedStakedBMIAmountWithReputation
) internal view returns (uint256) {
uint256 voteIndex = _allVotesToIndex[voter][claimIndex];
uint256 voterBMI = _allVotesByIndexInst[voteIndex].stakedBMIAmount;
uint256 voterReputation = _allVotesByIndexInst[voteIndex].voterReputation;
return
voterBMI.mul(voterReputation).mul(PERCENTAGE_100).div(
votedStakedBMIAmountWithReputation
);
}
function _calculateMajorityYesVote(
uint256 claimIndex,
address voter,
uint256 oldReputation
)
internal
view
returns (
uint256 _stblAmount,
uint256 _bmiAmount,
uint256 _newReputation
)
{
VotingResult storage info = _votings[claimIndex];
uint256 voterRatio =
_getRewardRatio(claimIndex, voter, info.votedYesStakedBMIAmountWithReputation);
if (claimingRegistry.claimStatus(claimIndex) == IClaimingRegistry.ClaimStatus.ACCEPTED) {
// calculate STBL reward tokens sent to the voter (from reinsurance)
_stblAmount = info.reinsuranceTokensAmount.mul(voterRatio).div(PERCENTAGE_100);
} else {
// calculate BMI reward tokens sent to the voter (from 1% locked)
_bmiAmount = info.lockedBMIAmount.mul(voterRatio).div(PERCENTAGE_100);
}
_newReputation = reputationSystem.getNewReputation(oldReputation, info.votedYesPercentage);
}
function _calculateMajorityNoVote(
uint256 claimIndex,
address voter,
uint256 oldReputation
) internal view returns (uint256 _bmiAmount, uint256 _newReputation) {
VotingResult storage info = _votings[claimIndex];
uint256 voterRatio =
_getRewardRatio(claimIndex, voter, info.votedNoStakedBMIAmountWithReputation);
// calculate BMI reward tokens sent to the voter (from 1% locked)
_bmiAmount = info.lockedBMIAmount.mul(voterRatio).div(PERCENTAGE_100);
_newReputation = reputationSystem.getNewReputation(
oldReputation,
PERCENTAGE_100.sub(info.votedYesPercentage)
);
}
function _calculateMinorityVote(
uint256 claimIndex,
address voter,
uint256 oldReputation
) internal view returns (uint256 _bmiPenalty, uint256 _newReputation) {
uint256 minorityPercentageWithPrecision =
Math.min(
_votings[claimIndex].votedYesPercentage,
PERCENTAGE_100.sub(_votings[claimIndex].votedYesPercentage)
);
if (minorityPercentageWithPrecision < PENALTY_THRESHOLD) {
// calculate confiscated staked stkBMI tokens sent to reinsurance pool
_bmiPenalty = Math.min(
vBMI.balanceOf(voter),
_allVotesByIndexInst[_allVotesToIndex[voter][claimIndex]]
.stakedBMIAmount
.mul(PENALTY_THRESHOLD.sub(minorityPercentageWithPrecision))
.div(PERCENTAGE_100)
);
}
_newReputation = reputationSystem.getNewReputation(
oldReputation,
minorityPercentageWithPrecision
);
}
function calculateVoterResultBatch(uint256[] calldata claimIndexes) external override {
uint256 reputation = reputationSystem.reputation(msg.sender);
for (uint256 i = 0; i < claimIndexes.length; i++) {
uint256 claimIndex = claimIndexes[i];
require(claimingRegistry.claimExists(claimIndex), "CV: Claim doesn't exist");
uint256 voteIndex = _allVotesToIndex[msg.sender][claimIndex];
require(_allVotesIndexes.contains(voteIndex), "CV: Vote doesn't exist");
require(voteIndex != 0, "CV: No vote on this claim");
require(_isVoteAwaitingCalculation(voteIndex), "CV: Vote is not awaiting");
uint256 stblAmount;
uint256 bmiAmount;
VoteStatus status;
if (
_votings[claimIndex].votedYesPercentage >= PERCENTAGE_50 &&
_allVotesByIndexInst[voteIndex].suggestedAmount > 0
) {
(stblAmount, bmiAmount, reputation) = _calculateMajorityYesVote(
claimIndex,
msg.sender,
reputation
);
reinsurancePool.withdrawSTBLTo(msg.sender, stblAmount);
bmiToken.transfer(msg.sender, bmiAmount);
emit RewardsForVoteCalculationSent(msg.sender, bmiAmount);
status = VoteStatus.MAJORITY;
} else if (
_votings[claimIndex].votedYesPercentage < PERCENTAGE_50 &&
_allVotesByIndexInst[voteIndex].suggestedAmount == 0
) {
(bmiAmount, reputation) = _calculateMajorityNoVote(
claimIndex,
msg.sender,
reputation
);
bmiToken.transfer(msg.sender, bmiAmount);
emit RewardsForVoteCalculationSent(msg.sender, bmiAmount);
status = VoteStatus.MAJORITY;
} else {
(bmiAmount, reputation) = _calculateMinorityVote(
claimIndex,
msg.sender,
reputation
);
vBMI.slashUserTokens(msg.sender, bmiAmount);
status = VoteStatus.MINORITY;
}
_allVotesByIndexInst[voteIndex].status = status;
_myNotCalculatedVotes[msg.sender].remove(claimIndex);
emit VoteCalculated(claimIndex, msg.sender, status);
}
reputationSystem.setNewReputation(msg.sender, reputation);
}
function _getBMIRewardForCalculation(uint256 claimIndex) internal view returns (uint256) {
uint256 lockedBMIs = _votings[claimIndex].lockedBMIAmount;
uint256 timeElapsed =
claimingRegistry.claimSubmittedTime(claimIndex).add(
claimingRegistry.anyoneCanCalculateClaimResultAfter(claimIndex)
);
if (claimingRegistry.canClaimBeCalculatedByAnyone(claimIndex)) {
timeElapsed = block.timestamp.sub(timeElapsed);
} else {
timeElapsed = timeElapsed.sub(block.timestamp);
}
return
Math.min(
lockedBMIs,
lockedBMIs.mul(timeElapsed.mul(CALCULATION_REWARD_PER_DAY.div(1 days))).div(
PERCENTAGE_100
)
);
}
function _sendRewardsForCalculationTo(uint256 claimIndex, address calculator) internal {
uint256 reward = _getBMIRewardForCalculation(claimIndex);
_votings[claimIndex].lockedBMIAmount = _votings[claimIndex].lockedBMIAmount.sub(reward);
bmiToken.transfer(calculator, reward);
emit RewardsForClaimCalculationSent(calculator, reward);
}
function calculateVotingResultBatch(uint256[] calldata claimIndexes) external override {
uint256 totalSupplyVBMI = vBMI.totalSupply();
for (uint256 i = 0; i < claimIndexes.length; i++) {
uint256 claimIndex = claimIndexes[i];
address claimer = claimingRegistry.claimOwner(claimIndex);
// claim existence is checked in claimStatus function
require(
claimingRegistry.claimStatus(claimIndex) ==
IClaimingRegistry.ClaimStatus.AWAITING_CALCULATION,
"CV: Claim is not awaiting"
);
// TODO invert order condition to prevent duplicate storage hits
require(
claimingRegistry.canClaimBeCalculatedByAnyone(claimIndex) || claimer == msg.sender,
"CV: Not allowed to calculate"
);
_sendRewardsForCalculationTo(claimIndex, msg.sender);
emit ClaimCalculated(claimIndex, msg.sender);
uint256 allVotedVBMI = _votings[claimIndex].allVotedStakedBMIAmount;
// if no votes or not an appeal and voted < 10% supply of vBMI
if (
allVotedVBMI == 0 ||
((totalSupplyVBMI == 0 ||
totalSupplyVBMI.mul(QUORUM).div(PERCENTAGE_100) > allVotedVBMI) &&
!claimingRegistry.isClaimAppeal(claimIndex))
) {
// reject & use locked BMI for rewards
claimingRegistry.rejectClaim(claimIndex);
} else {
uint256 votedYesPower = _votings[claimIndex].votedYesStakedBMIAmountWithReputation;
uint256 votedNoPower = _votings[claimIndex].votedNoStakedBMIAmountWithReputation;
uint256 totalPower = votedYesPower.add(votedNoPower);
_votings[claimIndex].votedYesPercentage = votedYesPower.mul(PERCENTAGE_100).div(
totalPower
);
if (_votings[claimIndex].votedYesPercentage >= APPROVAL_PERCENTAGE) {
// approve + send STBL & return locked BMI to the claimer
claimingRegistry.acceptClaim(claimIndex);
bmiToken.transfer(claimer, _votings[claimIndex].lockedBMIAmount);
} else {
// reject & use locked BMI for rewards
claimingRegistry.rejectClaim(claimIndex);
}
}
IPolicyBook(claimingRegistry.claimPolicyBook(claimIndex)).commitClaim(
claimer,
_votings[claimIndex].votedAverageWithdrawalAmount,
block.timestamp,
claimingRegistry.claimStatus(claimIndex) // ACCEPTED, REJECTED_CAN_APPEAL, REJECTED
);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
uint256 constant SECONDS_IN_THE_YEAR = 365 * 24 * 60 * 60; // 365 days * 24 hours * 60 minutes * 60 seconds
uint256 constant DAYS_IN_THE_YEAR = 365;
uint256 constant MAX_INT = type(uint256).max;
uint256 constant DECIMALS18 = 10**18;
uint256 constant PRECISION = 10**25;
uint256 constant PERCENTAGE_100 = 100 * PRECISION;
uint256 constant BLOCKS_PER_DAY = 6450;
uint256 constant BLOCKS_PER_YEAR = BLOCKS_PER_DAY * 365;
uint256 constant APY_TOKENS = DECIMALS18;
uint256 constant PROTOCOL_PERCENTAGE = 20 * PRECISION;
uint256 constant DEFAULT_REBALANCING_THRESHOLD = 10**23;
uint256 constant EPOCH_DAYS_AMOUNT = 7;
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
import "../interfaces/IContractsRegistry.sol";
abstract contract AbstractDependant {
/// @dev keccak256(AbstractDependant.setInjector(address)) - 1
bytes32 private constant _INJECTOR_SLOT =
0xd6b8f2e074594ceb05d47c27386969754b6ad0c15e5eb8f691399cd0be980e76;
modifier onlyInjectorOrZero() {
address _injector = injector();
require(_injector == address(0) || _injector == msg.sender, "Dependant: Not an injector");
_;
}
function setInjector(address _injector) external onlyInjectorOrZero {
bytes32 slot = _INJECTOR_SLOT;
assembly {
sstore(slot, _injector)
}
}
/// @dev has to apply onlyInjectorOrZero() modifier
function setDependencies(IContractsRegistry) external virtual;
function injector() public view returns (address _injector) {
bytes32 slot = _INJECTOR_SLOT;
assembly {
_injector := sload(slot)
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
import "./IClaimingRegistry.sol";
interface IClaimVoting {
enum VoteStatus {
ANONYMOUS_PENDING,
AWAITING_EXPOSURE,
EXPIRED,
EXPOSED_PENDING,
AWAITING_CALCULATION,
MINORITY,
MAJORITY
}
struct VotingResult {
uint256 withdrawalAmount;
uint256 lockedBMIAmount;
uint256 reinsuranceTokensAmount;
uint256 votedAverageWithdrawalAmount;
uint256 votedYesStakedBMIAmountWithReputation;
uint256 votedNoStakedBMIAmountWithReputation;
uint256 allVotedStakedBMIAmount;
uint256 votedYesPercentage;
}
struct VotingInst {
uint256 claimIndex;
bytes32 finalHash;
string encryptedVote;
address voter;
uint256 voterReputation;
uint256 suggestedAmount;
uint256 stakedBMIAmount;
bool accept;
VoteStatus status;
}
struct MyClaimInfo {
uint256 index;
address policyBookAddress;
string evidenceURI;
bool appeal;
uint256 claimAmount;
IClaimingRegistry.ClaimStatus finalVerdict;
uint256 finalClaimAmount;
uint256 bmiCalculationReward;
}
struct PublicClaimInfo {
uint256 claimIndex;
address claimer;
address policyBookAddress;
string evidenceURI;
bool appeal;
uint256 claimAmount;
uint256 time;
}
struct AllClaimInfo {
PublicClaimInfo publicClaimInfo;
IClaimingRegistry.ClaimStatus finalVerdict;
uint256 finalClaimAmount;
uint256 bmiCalculationReward;
}
struct MyVoteInfo {
AllClaimInfo allClaimInfo;
string encryptedVote;
uint256 suggestedAmount;
VoteStatus status;
uint256 time;
}
struct VotesUpdatesInfo {
uint256 bmiReward;
uint256 stblReward;
int256 reputationChange;
int256 stakeChange;
}
/// @notice starts the voting process
function initializeVoting(
address claimer,
string calldata evidenceURI,
uint256 coverTokens,
bool appeal
) external;
/// @notice returns true if the user has no PENDING votes
function canWithdraw(address user) external view returns (bool);
/// @notice returns true if the user has no AWAITING_CALCULATION votes
function canVote(address user) external view returns (bool);
/// @notice returns how many votes the user has
function countVotes(address user) external view returns (uint256);
/// @notice returns status of the vote
function voteStatus(uint256 index) external view returns (VoteStatus);
/// @notice returns a list of claims that are votable for msg.sender
function whatCanIVoteFor(uint256 offset, uint256 limit)
external
returns (uint256 _claimsCount, PublicClaimInfo[] memory _votablesInfo);
/// @notice returns info list of ALL claims
function allClaims(uint256 offset, uint256 limit)
external
view
returns (AllClaimInfo[] memory _allClaimsInfo);
/// @notice returns info list of claims of msg.sender
function myClaims(uint256 offset, uint256 limit)
external
view
returns (MyClaimInfo[] memory _myClaimsInfo);
/// @notice returns info list of claims that are voted by msg.sender
function myVotes(uint256 offset, uint256 limit)
external
view
returns (MyVoteInfo[] memory _myVotesInfo);
/// @notice returns an array of votes that can be calculated + update information
function myVotesUpdates(uint256 offset, uint256 limit)
external
view
returns (
uint256 _votesUpdatesCount,
uint256[] memory _claimIndexes,
VotesUpdatesInfo memory _myVotesUpdatesInfo
);
/// @notice anonymously votes (result used later in exposeVote())
/// @notice the claims have to be PENDING, the voter can vote only once for a specific claim
/// @param claimIndexes are the indexes of the claims the voter is voting on
/// (each one is unique for each claim and appeal)
/// @param finalHashes are the hashes produced by the encryption algorithm.
/// They will be verified onchain in expose function
/// @param encryptedVotes are the AES encrypted values that represent the actual vote
function anonymouslyVoteBatch(
uint256[] calldata claimIndexes,
bytes32[] calldata finalHashes,
string[] calldata encryptedVotes
) external;
/// @notice exposes votes of anonymous votings
/// @notice the vote has to be voted anonymously prior
/// @param claimIndexes are the indexes of the claims to expose votes for
/// @param suggestedClaimAmounts are the actual vote values.
/// They must match the decrypted values in anonymouslyVoteBatch function
/// @param hashedSignaturesOfClaims are the validation data needed to construct proper finalHashes
function exposeVoteBatch(
uint256[] calldata claimIndexes,
uint256[] calldata suggestedClaimAmounts,
bytes32[] calldata hashedSignaturesOfClaims
) external;
/// @notice calculates results of votes
function calculateVoterResultBatch(uint256[] calldata claimIndexes) external;
/// @notice calculates results of claims
function calculateVotingResultBatch(uint256[] calldata claimIndexes) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
import "./IPolicyBookFabric.sol";
interface IClaimingRegistry {
enum ClaimStatus {
CAN_CLAIM,
UNCLAIMABLE,
PENDING,
AWAITING_CALCULATION,
REJECTED_CAN_APPEAL,
REJECTED,
ACCEPTED
}
struct ClaimInfo {
address claimer;
address policyBookAddress;
string evidenceURI;
uint256 dateSubmitted;
uint256 dateEnded;
bool appeal;
ClaimStatus status;
uint256 claimAmount;
}
/// @notice returns anonymous voting duration
function anonymousVotingDuration(uint256 index) external view returns (uint256);
/// @notice returns the whole voting duration
function votingDuration(uint256 index) external view returns (uint256);
/// @notice returns how many time should pass before anyone could calculate a claim result
function anyoneCanCalculateClaimResultAfter(uint256 index) external view returns (uint256);
/// @notice returns true if a user can buy new policy of specified PolicyBook
function canBuyNewPolicy(address buyer, address policyBookAddress)
external
view
returns (bool);
/// @notice submits new PolicyBook claim for the user
function submitClaim(
address user,
address policyBookAddress,
string calldata evidenceURI,
uint256 cover,
bool appeal
) external returns (uint256);
/// @notice returns true if the claim with this index exists
function claimExists(uint256 index) external view returns (bool);
/// @notice returns claim submition time
function claimSubmittedTime(uint256 index) external view returns (uint256);
/// @notice returns claim end time or zero in case it is pending
function claimEndTime(uint256 index) external view returns (uint256);
/// @notice returns true if the claim is anonymously votable
function isClaimAnonymouslyVotable(uint256 index) external view returns (bool);
/// @notice returns true if the claim is exposably votable
function isClaimExposablyVotable(uint256 index) external view returns (bool);
/// @notice returns true if claim is anonymously votable or exposably votable
function isClaimVotable(uint256 index) external view returns (bool);
/// @notice returns true if a claim can be calculated by anyone
function canClaimBeCalculatedByAnyone(uint256 index) external view returns (bool);
/// @notice returns true if this claim is pending or awaiting
function isClaimPending(uint256 index) external view returns (bool);
/// @notice returns how many claims the holder has
function countPolicyClaimerClaims(address user) external view returns (uint256);
/// @notice returns how many pending claims are there
function countPendingClaims() external view returns (uint256);
/// @notice returns how many claims are there
function countClaims() external view returns (uint256);
/// @notice returns a claim index of it's claimer and an ordinal number
function claimOfOwnerIndexAt(address claimer, uint256 orderIndex)
external
view
returns (uint256);
/// @notice returns pending claim index by its ordinal index
function pendingClaimIndexAt(uint256 orderIndex) external view returns (uint256);
/// @notice returns claim index by its ordinal index
function claimIndexAt(uint256 orderIndex) external view returns (uint256);
/// @notice returns current active claim index by policybook and claimer
function claimIndex(address claimer, address policyBookAddress)
external
view
returns (uint256);
/// @notice returns true if the claim is appealed
function isClaimAppeal(uint256 index) external view returns (bool);
/// @notice returns current status of a claim
function policyStatus(address claimer, address policyBookAddress)
external
view
returns (ClaimStatus);
/// @notice returns current status of a claim
function claimStatus(uint256 index) external view returns (ClaimStatus);
/// @notice returns the claim owner (claimer)
function claimOwner(uint256 index) external view returns (address);
/// @notice returns the claim PolicyBook
function claimPolicyBook(uint256 index) external view returns (address);
/// @notice returns claim info by its index
function claimInfo(uint256 index) external view returns (ClaimInfo memory _claimInfo);
function getAllPendingClaimsAmount() external view returns (uint256 _totalClaimsAmount);
function getClaimableAmounts(uint256[] memory _claimIndexes) external view returns (uint256);
/// @notice marks the user's claim as Accepted
function acceptClaim(uint256 index) external;
/// @notice marks the user's claim as Rejected
function rejectClaim(uint256 index) external;
/// @notice Update Image Uri in case it contains material that is ilegal
/// or offensive.
/// @dev Only the owner of the PolicyBookAdmin can erase/update evidenceUri.
/// @param _claimIndex Claim Index that is going to be updated
/// @param _newEvidenceURI New evidence uri. It can be blank.
function updateImageUriOfClaim(uint256 _claimIndex, string calldata _newEvidenceURI) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
interface IContractsRegistry {
function getUniswapRouterContract() external view returns (address);
function getUniswapBMIToETHPairContract() external view returns (address);
function getUniswapBMIToUSDTPairContract() external view returns (address);
function getSushiswapRouterContract() external view returns (address);
function getSushiswapBMIToETHPairContract() external view returns (address);
function getSushiswapBMIToUSDTPairContract() external view returns (address);
function getSushiSwapMasterChefV2Contract() external view returns (address);
function getWETHContract() external view returns (address);
function getUSDTContract() external view returns (address);
function getBMIContract() external view returns (address);
function getPriceFeedContract() external view returns (address);
function getPolicyBookRegistryContract() external view returns (address);
function getPolicyBookFabricContract() external view returns (address);
function getBMICoverStakingContract() external view returns (address);
function getBMICoverStakingViewContract() external view returns (address);
function getLegacyRewardsGeneratorContract() external view returns (address);
function getRewardsGeneratorContract() external view returns (address);
function getBMIUtilityNFTContract() external view returns (address);
function getNFTStakingContract() external view returns (address);
function getLiquidityMiningContract() external view returns (address);
function getClaimingRegistryContract() external view returns (address);
function getPolicyRegistryContract() external view returns (address);
function getLiquidityRegistryContract() external view returns (address);
function getClaimVotingContract() external view returns (address);
function getReinsurancePoolContract() external view returns (address);
function getLeveragePortfolioViewContract() external view returns (address);
function getCapitalPoolContract() external view returns (address);
function getPolicyBookAdminContract() external view returns (address);
function getPolicyQuoteContract() external view returns (address);
function getLegacyBMIStakingContract() external view returns (address);
function getBMIStakingContract() external view returns (address);
function getSTKBMIContract() external view returns (address);
function getVBMIContract() external view returns (address);
function getLegacyLiquidityMiningStakingContract() external view returns (address);
function getLiquidityMiningStakingETHContract() external view returns (address);
function getLiquidityMiningStakingUSDTContract() external view returns (address);
function getReputationSystemContract() external view returns (address);
function getAaveProtocolContract() external view returns (address);
function getAaveLendPoolAddressProvdierContract() external view returns (address);
function getAaveATokenContract() external view returns (address);
function getCompoundProtocolContract() external view returns (address);
function getCompoundCTokenContract() external view returns (address);
function getCompoundComptrollerContract() external view returns (address);
function getYearnProtocolContract() external view returns (address);
function getYearnVaultContract() external view returns (address);
function getYieldGeneratorContract() external view returns (address);
function getShieldMiningContract() external view returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
interface ILeveragePortfolio {
enum LeveragePortfolio {USERLEVERAGEPOOL, REINSURANCEPOOL}
struct LevFundsFactors {
uint256 netMPL;
uint256 netMPLn;
address policyBookAddr;
// uint256 poolTotalLiquidity;
// uint256 poolUR;
// uint256 minUR;
}
function targetUR() external view returns (uint256);
function d_ProtocolConstant() external view returns (uint256);
function a_ProtocolConstant() external view returns (uint256);
function max_ProtocolConstant() external view returns (uint256);
/// @notice deploy lStable from user leverage pool or reinsurance pool using 2 formulas: access by policybook.
/// @param leveragePoolType LeveragePortfolio is determine the pool which call the function
function deployLeverageStableToCoveragePools(LeveragePortfolio leveragePoolType)
external
returns (uint256);
/// @notice deploy the vStable from RP in v2 and for next versions it will be from RP and LP : access by policybook.
function deployVirtualStableToCoveragePools() external returns (uint256);
/// @notice set the threshold % for re-evaluation of the lStable provided across all Coverage pools : access by owner
/// @param threshold uint256 is the reevaluatation threshold
function setRebalancingThreshold(uint256 threshold) external;
/// @notice set the protocol constant : access by owner
/// @param _targetUR uint256 target utitlization ration
/// @param _d_ProtocolConstant uint256 D protocol constant
/// @param _a_ProtocolConstant uint256 A protocol constant
/// @param _max_ProtocolConstant uint256 the max % included
function setProtocolConstant(
uint256 _targetUR,
uint256 _d_ProtocolConstant,
uint256 _a_ProtocolConstant,
uint256 _max_ProtocolConstant
) external;
/// @notice calc M factor by formual M = min( abs((1/ (Tur-UR))*d) /a, max)
/// @param poolUR uint256 utitilization ratio for a coverage pool
/// @return uint256 M facotr
//function calcM(uint256 poolUR) external returns (uint256);
/// @return uint256 the amount of vStable stored in the pool
function totalLiquidity() external view returns (uint256);
/// @notice add the portion of 80% of premium to user leverage pool where the leverage provide lstable : access policybook
/// add the 20% of premium + portion of 80% of premium where reisnurance pool participate in coverage pools (vStable) : access policybook
/// @param epochsNumber uint256 the number of epochs which the policy holder will pay a premium for
/// @param premiumAmount uint256 the premium amount which is a portion of 80% of the premium
function addPolicyPremium(uint256 epochsNumber, uint256 premiumAmount) external;
/// @notice Used to get a list of coverage pools which get leveraged , use with count()
/// @return _coveragePools a list containing policybook addresses
function listleveragedCoveragePools(uint256 offset, uint256 limit)
external
view
returns (address[] memory _coveragePools);
/// @notice get count of coverage pools which get leveraged
function countleveragedCoveragePools() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
import "./IPolicyBookFabric.sol";
import "./IClaimingRegistry.sol";
import "./IPolicyBookFacade.sol";
interface IPolicyBook {
enum WithdrawalStatus {NONE, PENDING, READY, EXPIRED}
struct PolicyHolder {
uint256 coverTokens;
uint256 startEpochNumber;
uint256 endEpochNumber;
uint256 paid;
uint256 reinsurancePrice;
}
struct WithdrawalInfo {
uint256 withdrawalAmount;
uint256 readyToWithdrawDate;
bool withdrawalAllowed;
}
struct BuyPolicyParameters {
address buyer;
address holder;
uint256 epochsNumber;
uint256 coverTokens;
uint256 distributorFee;
address distributor;
}
function policyHolders(address _holder)
external
view
returns (
uint256,
uint256,
uint256,
uint256,
uint256
);
function policyBookFacade() external view returns (IPolicyBookFacade);
function setPolicyBookFacade(address _policyBookFacade) external;
function EPOCH_DURATION() external view returns (uint256);
function stblDecimals() external view returns (uint256);
function READY_TO_WITHDRAW_PERIOD() external view returns (uint256);
function whitelisted() external view returns (bool);
function epochStartTime() external view returns (uint256);
// @TODO: should we let DAO to change contract address?
/// @notice Returns address of contract this PolicyBook covers, access: ANY
/// @return _contract is address of covered contract
function insuranceContractAddress() external view returns (address _contract);
/// @notice Returns type of contract this PolicyBook covers, access: ANY
/// @return _type is type of contract
function contractType() external view returns (IPolicyBookFabric.ContractType _type);
function totalLiquidity() external view returns (uint256);
function totalCoverTokens() external view returns (uint256);
// /// @notice return MPL for user leverage pool
// function userleveragedMPL() external view returns (uint256);
// /// @notice return MPL for reinsurance pool
// function reinsurancePoolMPL() external view returns (uint256);
// function bmiRewardMultiplier() external view returns (uint256);
function withdrawalsInfo(address _userAddr)
external
view
returns (
uint256 _withdrawalAmount,
uint256 _readyToWithdrawDate,
bool _withdrawalAllowed
);
function __PolicyBook_init(
address _insuranceContract,
IPolicyBookFabric.ContractType _contractType,
string calldata _description,
string calldata _projectSymbol
) external;
function whitelist(bool _whitelisted) external;
function getEpoch(uint256 time) external view returns (uint256);
/// @notice get STBL equivalent
function convertBMIXToSTBL(uint256 _amount) external view returns (uint256);
/// @notice get BMIX equivalent
function convertSTBLToBMIX(uint256 _amount) external view returns (uint256);
/// @notice submits new claim of the policy book
function submitClaimAndInitializeVoting(string calldata evidenceURI) external;
/// @notice submits new appeal claim of the policy book
function submitAppealAndInitializeVoting(string calldata evidenceURI) external;
/// @notice updates info on claim acceptance
function commitClaim(
address claimer,
uint256 claimAmount,
uint256 claimEndTime,
IClaimingRegistry.ClaimStatus status
) external;
/// @notice forces an update of RewardsGenerator multiplier
function forceUpdateBMICoverStakingRewardMultiplier() external;
/// @notice function to get precise current cover and liquidity
function getNewCoverAndLiquidity()
external
view
returns (uint256 newTotalCoverTokens, uint256 newTotalLiquidity);
/// @notice view function to get precise policy price
/// @param _epochsNumber is number of epochs to cover
/// @param _coverTokens is number of tokens to cover
/// @param _buyer address of the user who buy the policy
/// @return totalSeconds is number of seconds to cover
/// @return totalPrice is the policy price which will pay by the buyer
function getPolicyPrice(
uint256 _epochsNumber,
uint256 _coverTokens,
address _buyer
)
external
view
returns (
uint256 totalSeconds,
uint256 totalPrice,
uint256 pricePercentage
);
/// @notice Let user to buy policy by supplying stable coin, access: ANY
/// @param _buyer who is transferring funds
/// @param _holder who owns coverage
/// @param _epochsNumber period policy will cover
/// @param _coverTokens amount paid for the coverage
/// @param _distributorFee distributor fee (commission). It can't be greater than PROTOCOL_PERCENTAGE
/// @param _distributor if it was sold buy a whitelisted distributor, it is distributor address to receive fee (commission)
function buyPolicy(
address _buyer,
address _holder,
uint256 _epochsNumber,
uint256 _coverTokens,
uint256 _distributorFee,
address _distributor
) external returns (uint256, uint256);
function updateEpochsInfo() external;
function secondsToEndCurrentEpoch() external view returns (uint256);
/// @notice Let eligible contracts add liqiudity for another user by supplying stable coin
/// @param _liquidityHolderAddr is address of address to assign cover
/// @param _liqudityAmount is amount of stable coin tokens to secure
function addLiquidityFor(address _liquidityHolderAddr, uint256 _liqudityAmount) external;
/// @notice Let user to add liquidity by supplying stable coin, access: ANY
/// @param _liquidityBuyerAddr address the one that transfer funds
/// @param _liquidityHolderAddr address the one that owns liquidity
/// @param _liquidityAmount uint256 amount to be added on behalf the sender
/// @param _stakeSTBLAmount uint256 the staked amount if add liq and stake
function addLiquidity(
address _liquidityBuyerAddr,
address _liquidityHolderAddr,
uint256 _liquidityAmount,
uint256 _stakeSTBLAmount
) external;
function getAvailableBMIXWithdrawableAmount(address _userAddr) external view returns (uint256);
function getWithdrawalStatus(address _userAddr) external view returns (WithdrawalStatus);
function requestWithdrawal(uint256 _tokensToWithdraw, address _user) external;
// function requestWithdrawalWithPermit(
// uint256 _tokensToWithdraw,
// uint8 _v,
// bytes32 _r,
// bytes32 _s
// ) external;
function unlockTokens() external;
/// @notice Let user to withdraw deposited liqiudity, access: ANY
function withdrawLiquidity(address sender) external returns (uint256);
function getAPY() external view returns (uint256);
/// @notice Getting user stats, access: ANY
function userStats(address _user) external view returns (PolicyHolder memory);
/// @notice Getting number stats, access: ANY
/// @return _maxCapacities is a max token amount that a user can buy
/// @return _totalSTBLLiquidity is PolicyBook's liquidity
/// @return _totalLeveragedLiquidity is PolicyBook's leveraged liquidity
/// @return _stakedSTBL is how much stable coin are staked on this PolicyBook
/// @return _annualProfitYields is its APY
/// @return _annualInsuranceCost is percentage of cover tokens that is required to be paid for 1 year of insurance
function numberStats()
external
view
returns (
uint256 _maxCapacities,
uint256 _totalSTBLLiquidity,
uint256 _totalLeveragedLiquidity,
uint256 _stakedSTBL,
uint256 _annualProfitYields,
uint256 _annualInsuranceCost,
uint256 _bmiXRatio
);
/// @notice Getting info, access: ANY
/// @return _symbol is the symbol of PolicyBook (bmiXCover)
/// @return _insuredContract is an addres of insured contract
/// @return _contractType is a type of insured contract
/// @return _whitelisted is a state of whitelisting
function info()
external
view
returns (
string memory _symbol,
address _insuredContract,
IPolicyBookFabric.ContractType _contractType,
bool _whitelisted
);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
interface IPolicyBookFabric {
enum ContractType {CONTRACT, STABLECOIN, SERVICE, EXCHANGE, VARIOUS}
/// @notice Create new Policy Book contract, access: ANY
/// @param _contract is Contract to create policy book for
/// @param _contractType is Contract to create policy book for
/// @param _description is bmiXCover token desription for this policy book
/// @param _projectSymbol replaces x in bmiXCover token symbol
/// @param _initialDeposit is an amount user deposits on creation (addLiquidity())
/// @return _policyBook is address of created contract
function create(
address _contract,
ContractType _contractType,
string calldata _description,
string calldata _projectSymbol,
uint256 _initialDeposit,
address _shieldMiningToken
) external returns (address);
function createLeveragePools(
ContractType _contractType,
string calldata _description,
string calldata _projectSymbol
) external returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
import "./IPolicyBook.sol";
import "./ILeveragePortfolio.sol";
interface IPolicyBookFacade {
/// @notice Let user to buy policy by supplying stable coin, access: ANY
/// @param _epochsNumber period policy will cover
/// @param _coverTokens amount paid for the coverage
function buyPolicy(uint256 _epochsNumber, uint256 _coverTokens) external;
/// @param _holder who owns coverage
/// @param _epochsNumber period policy will cover
/// @param _coverTokens amount paid for the coverage
function buyPolicyFor(
address _holder,
uint256 _epochsNumber,
uint256 _coverTokens
) external;
function policyBook() external view returns (IPolicyBook);
function userLiquidity(address account) external view returns (uint256);
/// @notice virtual funds deployed by reinsurance pool
function VUreinsurnacePool() external view returns (uint256);
/// @notice leverage funds deployed by reinsurance pool
function LUreinsurnacePool() external view returns (uint256);
/// @notice leverage funds deployed by user leverage pool
function LUuserLeveragePool(address userLeveragePool) external view returns (uint256);
/// @notice total leverage funds deployed to the pool sum of (VUreinsurnacePool,LUreinsurnacePool,LUuserLeveragePool)
function totalLeveragedLiquidity() external view returns (uint256);
function userleveragedMPL() external view returns (uint256);
function reinsurancePoolMPL() external view returns (uint256);
function rebalancingThreshold() external view returns (uint256);
function safePricingModel() external view returns (bool);
/// @notice policyBookFacade initializer
/// @param pbProxy polciybook address upgreadable cotnract.
function __PolicyBookFacade_init(
address pbProxy,
address liquidityProvider,
uint256 initialDeposit
) external;
/// @param _epochsNumber period policy will cover
/// @param _coverTokens amount paid for the coverage
/// @param _distributor if it was sold buy a whitelisted distributor, it is distributor address to receive fee (commission)
function buyPolicyFromDistributor(
uint256 _epochsNumber,
uint256 _coverTokens,
address _distributor
) external;
/// @param _buyer who is buying the coverage
/// @param _epochsNumber period policy will cover
/// @param _coverTokens amount paid for the coverage
/// @param _distributor if it was sold buy a whitelisted distributor, it is distributor address to receive fee (commission)
function buyPolicyFromDistributorFor(
address _buyer,
uint256 _epochsNumber,
uint256 _coverTokens,
address _distributor
) external;
/// @notice Let user to add liquidity by supplying stable coin, access: ANY
/// @param _liquidityAmount is amount of stable coin tokens to secure
function addLiquidity(uint256 _liquidityAmount) external;
/// @notice Let user to add liquidity by supplying stable coin, access: ANY
/// @param _user the one taht add liquidity
/// @param _liquidityAmount is amount of stable coin tokens to secure
function addLiquidityFromDistributorFor(address _user, uint256 _liquidityAmount) external;
/// @notice Let user to add liquidity by supplying stable coin and stake it,
/// @dev access: ANY
function addLiquidityAndStake(uint256 _liquidityAmount, uint256 _stakeSTBLAmount) external;
/// @notice Let user to withdraw deposited liqiudity, access: ANY
function withdrawLiquidity() external;
/// @notice fetches all the pools data
/// @return uint256 VUreinsurnacePool
/// @return uint256 LUreinsurnacePool
/// @return uint256 LUleveragePool
/// @return uint256 user leverage pool address
function getPoolsData()
external
view
returns (
uint256,
uint256,
uint256,
address
);
/// @notice deploy leverage funds (RP lStable, ULP lStable)
/// @param deployedAmount uint256 the deployed amount to be added or substracted from the total liquidity
/// @param leveragePool whether user leverage or reinsurance leverage
function deployLeverageFundsAfterRebalance(
uint256 deployedAmount,
ILeveragePortfolio.LeveragePortfolio leveragePool
) external;
/// @notice deploy virtual funds (RP vStable)
/// @param deployedAmount uint256 the deployed amount to be added to the liquidity
function deployVirtualFundsAfterRebalance(uint256 deployedAmount) external;
/// @notice set the MPL for the user leverage and the reinsurance leverage
/// @param _userLeverageMPL uint256 value of the user leverage MPL
/// @param _reinsuranceLeverageMPL uint256 value of the reinsurance leverage MPL
function setMPLs(uint256 _userLeverageMPL, uint256 _reinsuranceLeverageMPL) external;
/// @notice sets the rebalancing threshold value
/// @param _newRebalancingThreshold uint256 rebalancing threshhold value
function setRebalancingThreshold(uint256 _newRebalancingThreshold) external;
/// @notice sets the rebalancing threshold value
/// @param _safePricingModel bool is pricing model safe (true) or not (false)
function setSafePricingModel(bool _safePricingModel) external;
/// @notice returns how many BMI tokens needs to approve in order to submit a claim
function getClaimApprovalAmount(address user) external view returns (uint256);
/// @notice upserts a withdraw request
/// @dev prevents adding a request if an already pending or ready request is open.
/// @param _tokensToWithdraw uint256 amount of tokens to withdraw
function requestWithdrawal(uint256 _tokensToWithdraw) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
import "./IPolicyBookFabric.sol";
interface IPolicyBookRegistry {
struct PolicyBookStats {
string symbol;
address insuredContract;
IPolicyBookFabric.ContractType contractType;
uint256 maxCapacity;
uint256 totalSTBLLiquidity;
uint256 totalLeveragedLiquidity;
uint256 stakedSTBL;
uint256 APY;
uint256 annualInsuranceCost;
uint256 bmiXRatio;
bool whitelisted;
}
function policyBooksByInsuredAddress(address insuredContract) external view returns (address);
function policyBookFacades(address facadeAddress) external view returns (address);
/// @notice Adds PolicyBook to registry, access: PolicyFabric
function add(
address insuredContract,
IPolicyBookFabric.ContractType contractType,
address policyBook,
address facadeAddress
) external;
function whitelist(address policyBookAddress, bool whitelisted) external;
/// @notice returns required allowances for the policybooks
function getPoliciesPrices(
address[] calldata policyBooks,
uint256[] calldata epochsNumbers,
uint256[] calldata coversTokens
) external view returns (uint256[] memory _durations, uint256[] memory _allowances);
/// @notice Buys a batch of policies
function buyPolicyBatch(
address[] calldata policyBooks,
uint256[] calldata epochsNumbers,
uint256[] calldata coversTokens
) external;
/// @notice Checks if provided address is a PolicyBook
function isPolicyBook(address policyBook) external view returns (bool);
/// @notice Checks if provided address is a policyBookFacade
function isPolicyBookFacade(address _facadeAddress) external view returns (bool);
/// @notice Checks if provided address is a user leverage pool
function isUserLeveragePool(address policyBookAddress) external view returns (bool);
/// @notice Returns number of registered PolicyBooks with certain contract type
function countByType(IPolicyBookFabric.ContractType contractType)
external
view
returns (uint256);
/// @notice Returns number of registered PolicyBooks, access: ANY
function count() external view returns (uint256);
function countByTypeWhitelisted(IPolicyBookFabric.ContractType contractType)
external
view
returns (uint256);
function countWhitelisted() external view returns (uint256);
/// @notice Listing registered PolicyBooks with certain contract type, access: ANY
/// @return _policyBooksArr is array of registered PolicyBook addresses with certain contract type
function listByType(
IPolicyBookFabric.ContractType contractType,
uint256 offset,
uint256 limit
) external view returns (address[] memory _policyBooksArr);
/// @notice Listing registered PolicyBooks, access: ANY
/// @return _policyBooksArr is array of registered PolicyBook addresses
function list(uint256 offset, uint256 limit)
external
view
returns (address[] memory _policyBooksArr);
function listByTypeWhitelisted(
IPolicyBookFabric.ContractType contractType,
uint256 offset,
uint256 limit
) external view returns (address[] memory _policyBooksArr);
function listWhitelisted(uint256 offset, uint256 limit)
external
view
returns (address[] memory _policyBooksArr);
/// @notice Listing registered PolicyBooks with stats and certain contract type, access: ANY
function listWithStatsByType(
IPolicyBookFabric.ContractType contractType,
uint256 offset,
uint256 limit
) external view returns (address[] memory _policyBooksArr, PolicyBookStats[] memory _stats);
/// @notice Listing registered PolicyBooks with stats, access: ANY
function listWithStats(uint256 offset, uint256 limit)
external
view
returns (address[] memory _policyBooksArr, PolicyBookStats[] memory _stats);
function listWithStatsByTypeWhitelisted(
IPolicyBookFabric.ContractType contractType,
uint256 offset,
uint256 limit
) external view returns (address[] memory _policyBooksArr, PolicyBookStats[] memory _stats);
function listWithStatsWhitelisted(uint256 offset, uint256 limit)
external
view
returns (address[] memory _policyBooksArr, PolicyBookStats[] memory _stats);
/// @notice Getting stats from policy books, access: ANY
/// @param policyBooks is list of PolicyBooks addresses
function stats(address[] calldata policyBooks)
external
view
returns (PolicyBookStats[] memory _stats);
/// @notice Return existing Policy Book contract, access: ANY
/// @param insuredContract is contract address to lookup for created IPolicyBook
function policyBookFor(address insuredContract) external view returns (address);
/// @notice Getting stats from policy books, access: ANY
/// @param insuredContracts is list of insuredContracts in registry
function statsByInsuredContracts(address[] calldata insuredContracts)
external
view
returns (PolicyBookStats[] memory _stats);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
interface IReinsurancePool {
function withdrawBMITo(address to, uint256 amount) external;
function withdrawSTBLTo(address to, uint256 amount) external;
/// @notice add the interest amount from defi protocol : access defi protocols
/// @param intrestAmount uint256 the interest amount from defi protocols
function addInterestFromDefiProtocols(uint256 intrestAmount) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
interface IReputationSystem {
/// @notice sets new reputation for the voter
function setNewReputation(address voter, uint256 newReputation) external;
/// @notice returns voter's new reputation
function getNewReputation(address voter, uint256 percentageWithPrecision)
external
view
returns (uint256);
/// @notice alternative way of knowing new reputation
function getNewReputation(uint256 voterReputation, uint256 percentageWithPrecision)
external
pure
returns (uint256);
/// @notice returns true if the user voted at least once
function hasVotedOnce(address user) external view returns (bool);
/// @notice returns true if user's reputation is grater than or equal to trusted voter threshold
function isTrustedVoter(address user) external view returns (bool);
/// @notice this function returns reputation threshold multiplied by 10**25
function getTrustedVoterReputationThreshold() external view returns (uint256);
/// @notice this function returns reputation multiplied by 10**25
function reputation(address user) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
interface IPriceFeed {
function howManyBMIsInUSDT(uint256 usdtAmount) external view returns (uint256);
function howManyUSDTsInBMI(uint256 bmiAmount) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
import "../../interfaces/tokens/erc20permit-upgradeable/IERC20PermitUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
interface IVBMI is IERC20Upgradeable, IERC20PermitUpgradeable {
function lockStkBMI(uint256 amount) external;
function unlockStkBMI(uint256 amount) external;
function slashUserTokens(address user, uint256 amount) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* COPIED FROM https://github.com/OpenZeppelin/openzeppelin-contracts-upgradeable/tree/release-v3.4/contracts/drafts
* @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
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
/// @notice the intention of this library is to be able to easily convert
/// one amount of tokens with N decimal places
/// to another amount with M decimal places
library DecimalsConverter {
using SafeMath for uint256;
function convert(
uint256 amount,
uint256 baseDecimals,
uint256 destinationDecimals
) internal pure returns (uint256) {
if (baseDecimals > destinationDecimals) {
amount = amount.div(10**(baseDecimals - destinationDecimals));
} else if (baseDecimals < destinationDecimals) {
amount = amount.mul(10**(destinationDecimals - baseDecimals));
}
return amount;
}
function convertTo18(uint256 amount, uint256 baseDecimals) internal pure returns (uint256) {
return convert(amount, baseDecimals, 18);
}
function convertFrom18(uint256 amount, uint256 destinationDecimals)
internal
pure
returns (uint256)
{
return convert(amount, 18, destinationDecimals);
}
}
// 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;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.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.7.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);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "../../GSN/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.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.7.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) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256`
* (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
|
use with countVotes()
|
function myVotesUpdates(uint256 offset, uint256 limit)
external
view
override
returns (
uint256 _votesUpdatesCount,
uint256[] memory _claimIndexes,
VotesUpdatesInfo memory _myVotesUpdatesInfo
)
{
uint256 to = (offset.add(limit)).min(_myVotes[msg.sender].length()).max(offset);
_votesUpdatesCount = 0;
_claimIndexes = new uint256[](to - offset);
uint256 stblAmount;
uint256 bmiAmount;
uint256 bmiPenaltyAmount;
uint256 newReputation;
for (uint256 i = offset; i < to; i++) {
uint256 claimIndex = _allVotesByIndexInst[_myVotes[msg.sender].at(i)].claimIndex;
if (
_myNotCalculatedVotes[msg.sender].contains(claimIndex) &&
_isVoteAwaitingCalculation(_allVotesToIndex[msg.sender][claimIndex])
) {
_claimIndexes[_votesUpdatesCount] = claimIndex;
uint256 oldReputation = reputationSystem.reputation(msg.sender);
if (
_votings[claimIndex].votedYesPercentage >= PERCENTAGE_50 &&
_allVotesByIndexInst[_allVotesToIndex[msg.sender][claimIndex]]
.suggestedAmount >
0
) {
(stblAmount, bmiAmount, newReputation) = _calculateMajorityYesVote(
claimIndex,
msg.sender,
oldReputation
);
_myVotesUpdatesInfo.reputationChange += int256(
newReputation.sub(oldReputation)
);
} else if (
_votings[claimIndex].votedYesPercentage < PERCENTAGE_50 &&
_allVotesByIndexInst[_allVotesToIndex[msg.sender][claimIndex]]
.suggestedAmount ==
0
) {
(bmiAmount, newReputation) = _calculateMajorityNoVote(
claimIndex,
msg.sender,
oldReputation
);
_myVotesUpdatesInfo.reputationChange += int256(
newReputation.sub(oldReputation)
);
(bmiPenaltyAmount, newReputation) = _calculateMinorityVote(
claimIndex,
msg.sender,
oldReputation
);
_myVotesUpdatesInfo.reputationChange -= int256(
oldReputation.sub(newReputation)
);
_myVotesUpdatesInfo.stakeChange -= int256(bmiPenaltyAmount);
}
_myVotesUpdatesInfo.bmiReward = _myVotesUpdatesInfo.bmiReward.add(bmiAmount);
_myVotesUpdatesInfo.stblReward = _myVotesUpdatesInfo.stblReward.add(stblAmount);
_votesUpdatesCount++;
}
}
}
| 588,951 |
./full_match/9001/0xaE77c9aD4af61fAec96f04bD6723F6F6A804a567/sources/src/Facets/CalldataVerificationFacet.sol
|
Extracts the generic swap parameters from the calldata data The calldata to extract the generic swap parameters from return sendingAssetId The sending asset id extracted from the calldata return amount The amount extracted from the calldata return receiver The receiver extracted from the calldata return receivingAssetId The receiving asset id extracted from the calldata return receivingAmount The receiving amount extracted from the calldata standardizedCall
|
function extractGenericSwapParameters(
bytes calldata data
)
public
pure
returns (
address sendingAssetId,
uint256 amount,
address receiver,
address receivingAssetId,
uint256 receivingAmount
)
{
LibSwap.SwapData[] memory swapData;
bytes memory callData = data;
if (
abi.decode(data, (bytes4)) ==
StandardizedCallFacet.standardizedCall.selector
) {
callData = abi.decode(data[4:], (bytes));
}
(, , , receiver, receivingAmount, swapData) = abi.decode(
callData.slice(4, callData.length - 4),
(bytes32, string, string, address, uint256, LibSwap.SwapData[])
);
sendingAssetId = swapData[0].sendingAssetId;
amount = swapData[0].fromAmount;
receivingAssetId = swapData[swapData.length - 1].receivingAssetId;
return (
sendingAssetId,
amount,
receiver,
receivingAssetId,
receivingAmount
);
}
| 11,535,020 |
pragma solidity ^0.4.18;
// ----------------------------------------------------------------------------
// 'Zakat' token contract
//
// Deployed to : 0x2DbFF826739090C3fBB1BDc3107601E785b288c6
// Symbol : Zakah
// Name : Zakat Token
// Total supply: 200000000
// Decimals : 18
//
// "Alms are for the poor and the needy, and those employed to administer the (funds); for those whose hearts have been (recently) reconciled (to Truth); for those in bondage and in debt; in the cause of Allah; and for the wayfarer: (thus is it) ordained by Allah, and Allah is full of knowledge and wisdom."
// — Qur'an, Sura 9 (Al-Tawba), ayat 60
// (c) by Moritz Neto & Daniel Bar with BokkyPooBah / Bok Consulting Pty Ltd Au 2017. The MIT Licence.
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// Safe maths
// ----------------------------------------------------------------------------
contract SafeMath {
function safeAdd(uint a, uint b) internal pure returns (uint c) {
c = a + b;
require(c >= a);
}
function safeSub(uint a, uint b) internal pure returns (uint c) {
require(b <= a);
c = a - b;
}
function safeMul(uint a, uint b) internal pure returns (uint c) {
c = a * b;
require(a == 0 || c / a == b);
}
function safeDiv(uint a, uint b) internal pure returns (uint c) {
require(b > 0);
c = a / b;
}
}
// ----------------------------------------------------------------------------
// ERC Token Standard #20 Interface
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// ----------------------------------------------------------------------------
contract ERC20Interface {
function totalSupply() public constant returns (uint);
function balanceOf(address tokenOwner) public constant returns (uint balance);
function allowance(address tokenOwner, address spender) public constant returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
// ----------------------------------------------------------------------------
// Contract function to receive approval and execute function in one call
//
// Borrowed from MiniMeToken
// ----------------------------------------------------------------------------
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 tokens, address token, bytes data) public;
}
// ----------------------------------------------------------------------------
// Owned contract
// ----------------------------------------------------------------------------
contract Owned {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed _from, address indexed _to);
function Owned() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner);
OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
// ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and assisted
// token transfers
// ----------------------------------------------------------------------------
contract Zakat is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
uint public startDate;
uint public bonusEnds;
uint public endDate;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
function Zakat() public {
symbol = "Zakah";
name = "Zakat Token";
decimals = 18;
bonusEnds = now + 5 weeks;
endDate = now + 52 weeks;
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account `tokenOwner`
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to `to` account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer `tokens` from the `from` account to the `to` account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the `from` account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account. The `spender` contract function
// `receiveApproval(...)` is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// 1200 Zakah Tokens per 1 ETH
// ------------------------------------------------------------------------
function () public payable {
require(now >= startDate && now <= endDate);
uint tokens;
if (now <= bonusEnds) {
tokens = msg.value * 1400;
} else {
tokens = msg.value * 1200;
}
balances[msg.sender] = safeAdd(balances[msg.sender], tokens);
_totalSupply = safeAdd(_totalSupply, tokens);
Transfer(address(0), msg.sender, tokens);
owner.transfer(msg.value);
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
}
|
------------------------------------------------------------------------ 1200 Zakah Tokens per 1 ETH ------------------------------------------------------------------------
|
function () public payable {
require(now >= startDate && now <= endDate);
uint tokens;
if (now <= bonusEnds) {
tokens = msg.value * 1400;
tokens = msg.value * 1200;
}
balances[msg.sender] = safeAdd(balances[msg.sender], tokens);
_totalSupply = safeAdd(_totalSupply, tokens);
Transfer(address(0), msg.sender, tokens);
owner.transfer(msg.value);
}
| 10,580,520 |
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
contract CoreUniLotterySettings
{
// Percentage calculations.
// As Solidity doesn't have floats, we have to use integers for
// percentage arithmetics.
// We set 1 percent to be equal to 1,000,000 - thus, we
// simulate 6 decimal points when computing percentages.
uint32 public constant PERCENT = 10 ** 6;
uint32 constant BASIS_POINT = PERCENT / 100;
uint32 constant _100PERCENT = 100 * PERCENT;
/** The UniLottery Owner's address.
*
* In the current version, The Owner has rights to:
* - Take up to 10% profit from every lottery.
* - Pool liquidity into the pool and remove it.
* - Start lotteries in auto or manual mode.
*/
// Public Testnets: 0xb13CB9BECcB034392F4c9Db44E23C3Fb5fd5dc63
// MainNet: 0x1Ae51bec001a4fA4E3b06A5AF2e0df33A79c01e2
address payable public constant OWNER_ADDRESS =
address( uint160( 0x1Ae51bec001a4fA4E3b06A5AF2e0df33A79c01e2 ) );
// Maximum lottery fee the owner can imburse on transfers.
uint32 constant MAX_OWNER_LOTTERY_FEE = 1 * PERCENT;
// Minimum amout of profit percentage that must be distributed
// to lottery winners.
uint32 constant MIN_WINNER_PROFIT_SHARE = 40 * PERCENT;
// Min & max profits the owner can take from lottery net profit.
uint32 constant MIN_OWNER_PROFITS = 3 * PERCENT;
uint32 constant MAX_OWNER_PROFITS = 10 * PERCENT;
// Min & max amount of lottery profits that the pool must get.
uint32 constant MIN_POOL_PROFITS = 10 * PERCENT;
uint32 constant MAX_POOL_PROFITS = 60 * PERCENT;
// Maximum lifetime of a lottery - 1 month (4 weeks).
uint32 constant MAX_LOTTERY_LIFETIME = 4 weeks;
// Callback gas requirements for a lottery's ending callback,
// and for the Pool's Scheduled Callback.
// Must be determined empirically.
uint32 constant LOTTERY_RAND_CALLBACK_GAS = 200000;
uint32 constant AUTO_MODE_SCHEDULED_CALLBACK_GAS = 3800431;
}
interface IUniswapRouter
{
// Get Factory and WETH addresses.
function factory() external pure returns (address);
function WETH() external pure returns (address);
// Create/add to a liquidity pair using ETH.
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline )
external
payable
returns (
uint amountToken,
uint amountETH,
uint liquidity
);
// Remove liquidity pair.
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline )
external
returns (
uint amountETH
);
// Get trade output amount, given an input.
function getAmountsOut(
uint amountIn,
address[] memory path )
external view
returns (
uint[] memory amounts
);
// Get trade input amount, given an output.
function getAmountsIn(
uint amountOut,
address[] memory path )
external view
returns (
uint[] memory amounts
);
}
interface IUniswapFactory
{
function getPair(
address tokenA,
address tokenB )
external view
returns ( address pair );
}
contract UniLotteryConfigGenerator
{
function getConfig()
external pure
returns( Lottery.LotteryConfig memory cfg )
{
cfg.initialFunds = 10 ether;
}
}
contract UniLotteryLotteryFactory
{
// Uniswap Router address on this network - passed to Lotteries on
// construction.
//ddress payable immutable uniRouterAddress;
// Delegate Contract for the Lottery, containing all logic code
// needed for deploying LotteryStubs.
// Deployed only once, on construction.
address payable immutable delegateContract;
// The Pool Address.
address payable poolAddress;
// The Lottery Storage Factory address, that the Lottery contracts use.
UniLotteryStorageFactory lotteryStorageFactory;
// Pool-Only modifier.
modifier poolOnly
{
require( msg.sender == poolAddress );
_;
}
// Constructor.
// Set the Uniswap Address, and deploy&lock the Delegate Code contract.
//
constructor( /*address payable _uniRouter*/ ) public
{
//uniRouterAddress = _uniRouter;
delegateContract = address( uint160( address( new Lottery() ) ) );
}
// Initialization function.
// Set the poolAddress as msg.sender, and lock it.
// Also, set the Lottery Storage Factory contract instance address.
function initialize( address _storageFactoryAddress )
external
{
require( poolAddress == address( 0 ) );
// Set the Pool's Address.
// Lock it. No more calls to this function will be executed.
poolAddress = msg.sender;
// Set the Storage Factory, and initialize it!
lotteryStorageFactory =
UniLotteryStorageFactory( _storageFactoryAddress );
lotteryStorageFactory.initialize();
}
/**
* Deploy a new Lottery Stub from the specified config.
* @param config - Lottery Config to be used (passed by the pool).
* @return newLottery - the newly deployed lottery stub.
*/
function createNewLottery(
Lottery.LotteryConfig memory config,
address randomnessProvider )
public
poolOnly
returns( address payable newLottery )
{
// Create new Lottery Storage, using storage factory.
// Populate the stub, by calling the "construct" function.
LotteryStub stub = new LotteryStub( delegateContract );
Lottery( address( stub ) ).construct(
config, poolAddress, randomnessProvider,
lotteryStorageFactory.createNewStorage() );
return address( stub );
}
}
contract LotteryStub
{
// ============ ERC20 token contract's storage ============ //
// ------- Slot ------- //
// Balances of token holders.
mapping (address => uint256) private _balances;
// ------- Slot ------- //
// Allowances of spenders for a specific token owner.
mapping (address => mapping (address => uint256)) private _allowances;
// ------- Slot ------- //
// Total supply of the token.
uint256 private _totalSupply;
// ============== Lottery contract's storage ============== //
// ------- Initial Slots ------- //
// The config which is passed to constructor.
Lottery.LotteryConfig internal cfg;
// ------- Slot ------- //
// The Lottery Storage contract, which stores all holder data,
// such as scores, referral tree data, etc.
LotteryStorage /*public*/ lotStorage;
// ------- Slot ------- //
// Pool address. Set on constructor from msg.sender.
address payable /*public*/ poolAddress;
// ------- Slot ------- //
// Randomness Provider address.
address /*public*/ randomnessProvider;
// ------- Slot ------- //
// Exchange address. In Uniswap mode, it's the Uniswap liquidity
// pair's address, where trades execute.
address /*public*/ exchangeAddress;
// Start date.
uint32 /*public*/ startDate;
// Completion (Mining Phase End) date.
uint32 /*public*/ completionDate;
// The date when Randomness Provider was called, requesting a
// random seed for the lottery finish.
// Also, when this variable becomes Non-Zero, it indicates that we're
// on Ending Stage Part One: waiting for the random seed.
uint32 finish_timeRandomSeedRequested;
// ------- Slot ------- //
// WETH address. Set by calling Router's getter, on constructor.
address WETHaddress;
// Is the WETH first or second token in our Uniswap Pair?
bool uniswap_ethFirst;
// If we are, or were before, on finishing stage, this is the
// probability of lottery going to Ending Stage on this transaction.
uint32 finishProbablity;
// Re-Entrancy Lock (Mutex).
// We protect for reentrancy in the Fund Transfer functions.
bool reEntrancyMutexLocked;
// On which stage we are currently.
uint8 /*public*/ lotteryStage;
// Indicator for whether the lottery fund gains have passed a
// minimum fund gain requirement.
// After that time point (when this bool is set), the token sells
// which could drop the fund value below the requirement, would
// be denied.
bool fundGainRequirementReached;
// The current step of the Mining Stage.
uint16 miningStep;
// If we're currently on Special Transfer Mode - that is, we allow
// direct transfers between parties even in NON-ACTIVE state.
bool specialTransferModeEnabled;
// ------- Slot ------- //
// Per-Transaction Pseudo-Random hash value (transferHashValue).
// This value is computed on every token transfer, by keccak'ing
// the last (current) transferHashValue, msg.sender, now, and
// transaction count.
//
// This is used on Finishing Stage, as a pseudo-random number,
// which is used to check if we should end the lottery (move to
// Ending Stage).
uint256 transferHashValue;
// ------- Slot ------- //
// On lottery end, get & store the lottery total ETH return
// (including initial funds), and profit amount.
uint128 /*public*/ ending_totalReturn;
uint128 /*public*/ ending_profitAmount;
// ------- Slot ------- //
// The mapping that contains TRUE for addresses that already claimed
// their lottery winner prizes.
// Used only in COMPLETION, on claimWinnerPrize(), to check if
// msg.sender has already claimed his prize.
mapping( address => bool ) /*public*/ prizeClaimersAddresses;
// =================== OUR CONTRACT'S OWN STORAGE =================== //
// The address of the delegate contract, containing actual logic.
address payable immutable public __delegateContract;
// =================== Functions =================== //
// Constructor.
// Just set the delegate's address.
constructor( address payable _delegateAddr )
public
{
__delegateContract = _delegateAddr;
}
// Fallback payable function, which delegates any call to our
// contract, into the delegate contract.
fallback()
external payable
{
// DelegateCall the delegate code contract.
( bool success, bytes memory data ) =
__delegateContract.delegatecall( msg.data );
// Use inline assembly to be able to return value from the fallback.
// (by default, returning a value from fallback is not possible,
// but it's still possible to manually copy data to the
// return buffer.
assembly
{
// delegatecall returns 0 (false) on error.
// Add 32 bytes to "data" pointer, because first slot (32 bytes)
// contains the length, and we use return value's length
// from returndatasize() opcode.
switch success
case 0 { revert( add( data, 32 ), returndatasize() ) }
default { return( add( data, 32 ), returndatasize() ) }
}
}
// Receive ether function.
receive() external payable
{ }
}
contract LotteryStorageStub
{
// =============== LotteryStorage contract's storage ================ //
// --------- Slot --------- //
// The Lottery address that this storage belongs to.
// Is set by the "initialize()", called by corresponding Lottery.
address lottery;
// The Random Seed, that was passed to us from Randomness Provider,
// or generated alternatively.
uint64 randomSeed;
// The actual number of winners that there will be. Set after
// completing the Winner Selection Algorithm.
uint16 numberOfWinners;
// Bool indicating if Winner Selection Algorithm has been executed.
bool algorithmCompleted;
// --------- Slot --------- //
// Winner Algorithm config. Specified in Initialization().
LotteryStorage.WinnerAlgorithmConfig algConfig;
// --------- Slot --------- //
// The Min-Max holder score storage.
LotteryStorage.MinMaxHolderScores minMaxScores;
// --------- Slot --------- //
// Array of holders.
address[] /*public*/ holders;
// --------- Slot --------- //
// Holder array indexes mapping, for O(1) array element access.
mapping( address => uint ) holderIndexes;
// --------- Slot --------- //
// Mapping of holder data.
mapping( address => LotteryStorage.HolderData ) /*public*/ holderData;
// --------- Slot --------- //
// Mapping of referral IDs to addresses of holders who generated
// those IDs.
mapping( uint256 => address ) referrers;
// --------- Slot --------- //
// The array of final-sorted winners (set after Winner Selection
// Algorithm completes), that contains the winners' indexes
// in the "holders" array, to save space.
//
// Notice that by using uint16, we can fit 16 items into one slot!
// So, if there are 160 winners, we only take up 10 slots, so
// only 20,000 * 10 = 200,000 gas gets consumed!
//
LotteryStorage.WinnerIndexStruct[] sortedWinnerIndexes;
// =================== OUR CONTRACT'S OWN STORAGE =================== //
// The address of the delegate contract, containing actual logic.
address immutable public __delegateContract;
// =================== Functions =================== //
// Constructor.
// Just set the delegate's address.
constructor( address _delegateAddr )
public
{
__delegateContract = _delegateAddr;
}
// Fallback function, which delegates any call to our
// contract, into the delegate contract.
fallback()
external
{
// DelegateCall the delegate code contract.
( bool success, bytes memory data ) =
__delegateContract.delegatecall( msg.data );
// Use inline assembly to be able to return value from the fallback.
// (by default, returning a value from fallback is not possible,
// but it's still possible to manually copy data to the
// return buffer.
assembly
{
// delegatecall returns 0 (false) on error.
// Add 32 bytes to "data" pointer, because first slot (32 bytes)
// contains the length, and we use return value's length
// from returndatasize() opcode.
switch success
case 0 { revert( add( data, 32 ), returndatasize() ) }
default { return( add( data, 32 ), returndatasize() ) }
}
}
}
interface IUniLotteryPool
{
function lotteryFinish( uint totalReturn, uint profitAmount )
external payable;
}
interface IRandomnessProvider
{
function requestRandomSeedForLotteryFinish() external;
}
contract LotteryStorage is CoreUniLotterySettings
{
// ==================== Structs & Constants ==================== //
// Struct of holder data & scores.
struct HolderData
{
// --------- Slot --------- //
// If this holder has generated his own referral ID, this is
// that ID. If he hasn't generated an ID, this is zero.
uint256 referralID;
// --------- Slot --------- //
// If this holder provided a valid referral ID, this is the
// address of a referrer - the user who generated the said
// referral ID.
address referrer;
// --------- Slot --------- //
// The intermediate score factor variables.
// Ether contributed: ( buys - sells ). Can be negative.
int80 etherContributed;
// Time x ether factor: (relativeTxTime * etherAmount).
int80 timeFactors;
// Token balance score factor of this holder - we use int,
// for easier computation of player scores in our algorithms.
int80 tokenBalance;
// Number of all child referrees, including multi-level ones.
// Updated by traversing child->parent way, incrementing
// every node's counter by one.
// Used in Winner Selection Algorithm, to determine how much
// to divide the accumulated referree scores by.
uint16 referreeCount;
// --------- Slot --------- //
// Accumulated referree score factors - ether contributed by
// all referrees, time factors, and token balances of all
// referrees.
// Can be negative!
int80 referree_etherContributed;
int80 referree_timeFactors;
int80 referree_tokenBalance;
// Bonus score points, which can be given in certain events,
// such as when player registers a valid referral ID.
int16 bonusScore;
}
// Final Score (end lottery score * randomValue) structure.
struct FinalScore
{
address addr; // 20 bytes \
uint16 holderIndex; // 2 bytes | = 30 bytes => 1 slot.
uint64 score; // 8 bytes /
}
// Winner Indexes structure - used to efficiently store Winner
// indexes in holder's array, after completing the Winner Selection
// Algorithm.
// To save Space, we store these in a struct, with uint16 array
// with 16 items - so this struct takes up excactly 1 slot.
struct WinnerIndexStruct
{
uint16[ 16 ] indexes;
}
// A structure which is used by Winner Selection algorithm,
// which is a subset of the LotteryConfig structure, containing
// only items necessary for executing the Winner Selection algorigm.
// More detailed member description can be found in LotteryConfig
// structure description.
// Takes up only one slot!
struct WinnerAlgorithmConfig
{
// --------- Slot --------- //
// Individual player max score parts.
int16 maxPlayerScore_etherContributed;
int16 maxPlayerScore_tokenHoldingAmount;
int16 maxPlayerScore_timeFactor;
int16 maxPlayerScore_refferalBonus;
// Number of lottery winners.
uint16 winnerCount;
// Score-To-Random ration data (as a rational ratio number).
// For example if 1:5, then scorePart = 1, and randPart = 5.
uint16 randRatio_scorePart;
uint16 randRatio_randPart;
// The Ending Algorithm type.
uint8 endingAlgoType;
}
// Structure containing the minimum and maximum values of
// holder intermediate scores.
// These values get updated on transfers during ACTIVE stage,
// when holders buy/sell tokens.
// Structure takes up only 2 slots!
//
struct MinMaxHolderScores
{
// --------- Slot --------- //
// Minimum & maximum values for each score factor.
// Updated for holders when they transfer tokens.
// Used in winner selection algorithm, to normalize the scores in
// a single loop, to avoid looping additional time to find min/max.
int80 holderScore_etherContributed_min;
int80 holderScore_etherContributed_max;
int80 holderScore_timeFactors_min;
// --------- Slot --------- //
int80 holderScore_timeFactors_max;
int80 holderScore_tokenBalance_min;
int80 holderScore_tokenBalance_max;
}
// ROOT_REFERRER constant.
// Used to prevent cyclic dependencies on referral tree.
address constant ROOT_REFERRER = address( 1 );
// Precision of division operations.
int constant PRECISION = 10000;
// Random number modulo to use when obtaining random numbers from
// the random seed + nonce, using keccak256.
// This is the maximum available Score Random Factor, plus one.
// By default, 10^9 (one billion).
//
uint constant RANDOM_MODULO = (10 ** 9);
// Maximum number of holders that the MinedWinnerSelection algorithm
// can process. Related to block gas limit.
uint constant MINEDSELECTION_MAX_NUMBER_OF_HOLDERS = 300;
// Maximum number of holders that the WinnerSelfValidation algorithm
// can process. Related to block gas limit.
uint constant SELFVALIDATION_MAX_NUMBER_OF_HOLDERS = 1200;
// ==================== State Variables ==================== //
// --------- Slot --------- //
// The Lottery address that this storage belongs to.
// Is set by the "initialize()", called by corresponding Lottery.
address lottery;
// The Random Seed, that was passed to us from Randomness Provider,
// or generated alternatively.
uint64 randomSeed;
// The actual number of winners that there will be. Set after
// completing the Winner Selection Algorithm.
uint16 numberOfWinners;
// Bool indicating if Winner Selection Algorithm has been executed.
bool algorithmCompleted;
// --------- Slot --------- //
// Winner Algorithm config. Specified in Initialization().
WinnerAlgorithmConfig algConfig;
// --------- Slot --------- //
// The Min-Max holder score storage.
MinMaxHolderScores public minMaxScores;
// --------- Slot --------- //
// Array of holders.
address[] public holders;
// --------- Slot --------- //
// Holder array indexes mapping, for O(1) array element access.
mapping( address => uint ) holderIndexes;
// --------- Slot --------- //
// Mapping of holder data.
mapping( address => HolderData ) public holderData;
// --------- Slot --------- //
// Mapping of referral IDs to addresses of holders who generated
// those IDs.
mapping( uint256 => address ) referrers;
// --------- Slot --------- //
// The array of final-sorted winners (set after Winner Selection
// Algorithm completes), that contains the winners' indexes
// in the "holders" array, to save space.
//
// Notice that by using uint16, we can fit 16 items into one slot!
// So, if there are 160 winners, we only take up 10 slots, so
// only 20,000 * 10 = 200,000 gas gets consumed!
//
WinnerIndexStruct[] sortedWinnerIndexes;
// ============== Internal (Private) Functions ============== //
// Lottery-Only modifier.
modifier lotteryOnly
{
require( msg.sender == address( lottery ) );
_;
}
// ============== [ BEGIN ] LOTTERY QUICKSORT FUNCTIONS ============== //
/**
* QuickSort and QuickSelect algorithm functionality code.
*
* These algorithms are used to find the lottery winners in
* an array of final random-factored scores.
* As the highest-scorers win, we need to sort an array to
* identify them.
*
* For this task, we use QuickSelect to partition array into
* winner part (elements with score larger than X, where X is
* n-th largest element, where n is number of winners),
* and others (non-winners), who are ignored to save computation
* power.
* Then we sort the winner part only, using QuickSort, and
* distribute prizes to winners accordingly.
*/
// Swap function used in QuickSort algorithms.
//
function QSort_swap( FinalScore[] memory list,
uint a, uint b )
internal pure
{
FinalScore memory tmp = list[ a ];
list[ a ] = list[ b ];
list[ b ] = tmp;
}
// Standard Hoare's partition scheme function, used for both
// QuickSort and QuickSelect.
//
function QSort_partition(
FinalScore[] memory list,
int lo, int hi )
internal pure
returns( int newPivotIndex )
{
uint64 pivot = list[ uint( hi + lo ) / 2 ].score;
int i = lo - 1;
int j = hi + 1;
while( true )
{
do {
i++;
} while( list[ uint( i ) ].score > pivot ) ;
do {
j--;
} while( list[ uint( j ) ].score < pivot ) ;
if( i >= j )
return j;
QSort_swap( list, uint( i ), uint( j ) );
}
}
// QuickSelect's Lomuto partition scheme.
//
function QSort_LomutoPartition(
FinalScore[] memory list,
uint left, uint right, uint pivotIndex )
internal pure
returns( uint newPivotIndex )
{
uint pivotValue = list[ pivotIndex ].score;
QSort_swap( list, pivotIndex, right ); // Move pivot to end
uint storeIndex = left;
for( uint i = left; i < right; i++ )
{
if( list[ i ].score > pivotValue ) {
QSort_swap( list, storeIndex, i );
storeIndex++;
}
}
// Move pivot to its final place, and return the pivot's index.
QSort_swap( list, right, storeIndex );
return storeIndex;
}
// QuickSelect algorithm (iterative).
//
function QSort_QuickSelect(
FinalScore[] memory list,
int left, int right, int k )
internal pure
returns( int indexOfK )
{
while( true ) {
if( left == right )
return left;
int pivotIndex = int( QSort_LomutoPartition( list,
uint(left), uint(right), uint(right) ) );
if( k == pivotIndex )
return k;
else if( k < pivotIndex )
right = pivotIndex - 1;
else
left = pivotIndex + 1;
}
}
// Standard QuickSort function.
//
function QSort_QuickSort(
FinalScore[] memory list,
int lo, int hi )
internal pure
{
if( lo < hi ) {
int p = QSort_partition( list, lo, hi );
QSort_QuickSort( list, lo, p );
QSort_QuickSort( list, p + 1, hi );
}
}
// ============== [ END ] LOTTERY QUICKSORT FUNCTIONS ============== //
// ------------ Ending Stage - Winner Selection Algorithm ------------ //
/**
* Compute the individual player score factors for a holder.
* Function split from the below one (ending_Stage_2), to avoid
* "Stack too Deep" errors.
*/
function computeHolderIndividualScores(
WinnerAlgorithmConfig memory cfg,
MinMaxHolderScores memory minMax,
HolderData memory hdata )
internal pure
returns( int individualScore )
{
// Normalize the scores, by subtracting minimum and dividing
// by maximum, to get the score values specified in cfg.
// Use precision of 100, then round.
//
// Notice that we're using int arithmetics, so division
// truncates. That's why we use PRECISION, to simulate
// rounding.
//
// This formula is better explained in example.
// In this example, we use variable abbreviations defined
// below, on formula's right side comments.
//
// Say, values are these in our example:
// e = 4, eMin = 1, eMax = 8, MS = 5, P = 10.
//
// So, let's calculate the score using the formula:
// ( ( ( (4 - 1) * 10 * 5 ) / (8 - 1) ) + (10 / 2) ) / 10 =
// ( ( ( 3 * 10 * 5 ) / 7 ) + 5 ) / 10 =
// ( ( 150 / 7 ) + 5 ) / 10 =
// ( ( 150 / 7 ) + 5 ) / 10 =
// ( 20 + 5 ) / 10 =
// 25 / 10 =
// [ 2.5 ] = 2
//
// So, with truncation, we see that for e = 4, the score
// is 2 out of 5 maximum.
// That's because the minimum ether contributed was 1, and
// maximum was 8.
// So, 4 stays below the middle, and gets a nicely rounded
// score of 2.
// Compute etherContributed.
int score_etherContributed = ( (
( ( hdata.etherContributed - // e
minMax.holderScore_etherContributed_min ) // eMin
* PRECISION * cfg.maxPlayerScore_etherContributed ) // P * MS
/ ( minMax.holderScore_etherContributed_max - // eMax
minMax.holderScore_etherContributed_min ) // eMin
) + (PRECISION / 2) ) / PRECISION;
// Compute timeFactors.
int score_timeFactors = ( (
( ( hdata.timeFactors - // e
minMax.holderScore_timeFactors_min ) // eMin
* PRECISION * cfg.maxPlayerScore_timeFactor ) // P * MS
/ ( minMax.holderScore_timeFactors_max - // eMax
minMax.holderScore_timeFactors_min ) // eMin
) + (PRECISION / 2) ) / PRECISION;
// Compute tokenBalance.
int score_tokenBalance = ( (
( ( hdata.tokenBalance - // e
minMax.holderScore_tokenBalance_min ) // eMin
* PRECISION * cfg.maxPlayerScore_tokenHoldingAmount )
/ ( minMax.holderScore_tokenBalance_max - // eMax
minMax.holderScore_tokenBalance_min ) // eMin
) + (PRECISION / 2) ) / PRECISION;
// Return the accumulated individual score (excluding referrees).
return score_etherContributed + score_timeFactors +
score_tokenBalance;
}
/**
* Split-function, to avoid "Stack-2-Deep" errors.
* Computes a single component of a Referree Score.
*/
/*function priv_computeSingleReferreeComponent(
int _referreeScore_,
int _maxPlayerScore_,
int _holderScore_min_x_refCount,
int _holderScore_max_x_refCount )
internal pure
returns( int score )
{
score = (
( PRECISION * _maxPlayerScore_ *
( _referreeScore_ - _holderScore_min_x_refCount ) )
/
( _holderScore_max_x_refCount - _holderScore_min_x_refCount )
);
}*/
/**
* Compute the unified Referree-Score of a player, who's got
* the accumulated factor-scores of all his referrees in his
* holderData structure.
*
* @param individualToReferralRatio - an int value, computed
* before starting the winner score computation loop, in
* the ending_Stage_2 initial part, to save computation
* time later.
* This is the ratio of the maximum available referral score,
* to the maximum available individual score, as defined in
* the config (for example, if max.ref.score is 20, and
* max.ind.score is 40, then the ratio is 20/40 = 0.5).
*
* We use this ratio to transform the computed accumulated
* referree individual scores to the standard referrer's
* score, by multiplying by that ratio.
*/
function computeReferreeScoresForHolder(
int individualToReferralRatio,
WinnerAlgorithmConfig memory cfg,
MinMaxHolderScores memory minMax,
HolderData memory hdata )
internal pure
returns( int unifiedReferreeScore )
{
// If number of referrees of this HODLer is Zero, then
// his referree score is also zero.
if( hdata.referreeCount == 0 )
return 0;
// Now, compute the Referree's Accumulated Scores.
//
// Here we use the same formula as when computing individual
// scores (in the function above), but we multiply the
// Min & Max known score value by the referree count, because
// the "referree_..." scores are accumulated scores of all
// referrees that that holder has.
// This way, we reach the uniform averaged score of all referrees,
// just like we do with individual scores.
//
// Also, we don't divide them by PRECISION, to accumulate and use
// the max-score-options in the main score computing function.
int refCount = int( hdata.referreeCount );
// Compute etherContributed.
int referreeScore_etherContributed = (
( ( hdata.referree_etherContributed -
minMax.holderScore_etherContributed_min * refCount )
* PRECISION * cfg.maxPlayerScore_etherContributed )
/ ( minMax.holderScore_etherContributed_max * refCount -
minMax.holderScore_etherContributed_min * refCount )
);
// Compute timeFactors.
int referreeScore_timeFactors = (
( ( hdata.referree_timeFactors -
minMax.holderScore_timeFactors_min * refCount )
* PRECISION * cfg.maxPlayerScore_timeFactor )
/ ( minMax.holderScore_timeFactors_max * refCount -
minMax.holderScore_timeFactors_min * refCount )
);
// Compute tokenBalance.
int referreeScore_tokenBalance = (
( ( hdata.referree_tokenBalance -
minMax.holderScore_tokenBalance_min * refCount )
* PRECISION * cfg.maxPlayerScore_tokenHoldingAmount )
/ ( minMax.holderScore_tokenBalance_max * refCount -
minMax.holderScore_tokenBalance_min * refCount )
);
// Accumulate 'em all !
// Then, multiply it by the ratio of all individual max scores
// (maxPlayerScore_etherContributed, timeFactor, tokenBalance),
// to the maxPlayerScore_refferalBonus.
// Use the same precision.
unifiedReferreeScore = int( ( (
( ( referreeScore_etherContributed +
referreeScore_timeFactors +
referreeScore_tokenBalance ) + (PRECISION / 2)
) / PRECISION
) * individualToReferralRatio
) / PRECISION );
}
// =================== PUBLIC FUNCTIONS =================== //
/**
* Update current holder's score with given change values, and
* Propagate the holder's current transfer's score changes
* through the referral chain, updating every parent referrer's
* accumulated referree scores, until the ROOT_REFERRER or zero
* address referrer is encountered.
*/
function updateAndPropagateScoreChanges(
address holder,
int80 etherContributed_change,
int80 timeFactors_change,
int80 tokenBalance_change )
public
lotteryOnly
{
// Update current holder's score.
holderData[ holder ].etherContributed += etherContributed_change;
holderData[ holder ].timeFactors += timeFactors_change;
holderData[ holder ].tokenBalance += tokenBalance_change;
// Check if scores are exceeding current min/max scores,
// and if so, update the min/max scores.
// etherContributed:
if( holderData[ holder ].etherContributed >
minMaxScores.holderScore_etherContributed_max )
minMaxScores.holderScore_etherContributed_max =
holderData[ holder ].etherContributed;
if( holderData[ holder ].etherContributed <
minMaxScores.holderScore_etherContributed_min )
minMaxScores.holderScore_etherContributed_min =
holderData[ holder ].etherContributed;
// timeFactors:
if( holderData[ holder ].timeFactors >
minMaxScores.holderScore_timeFactors_max )
minMaxScores.holderScore_timeFactors_max =
holderData[ holder ].timeFactors;
if( holderData[ holder ].timeFactors <
minMaxScores.holderScore_timeFactors_min )
minMaxScores.holderScore_timeFactors_min =
holderData[ holder ].timeFactors;
// tokenBalance:
if( holderData[ holder ].tokenBalance >
minMaxScores.holderScore_tokenBalance_max )
minMaxScores.holderScore_tokenBalance_max =
holderData[ holder ].tokenBalance;
if( holderData[ holder ].tokenBalance <
minMaxScores.holderScore_tokenBalance_min )
minMaxScores.holderScore_tokenBalance_min =
holderData[ holder ].tokenBalance;
// Propagate the score through the referral chain.
// Dive at maximum to the depth of 10, to avoid "Outta Gas"
// errors.
uint MAX_REFERRAL_DEPTH = 10;
uint depth = 0;
address referrerAddr = holderData[ holder ].referrer;
while( referrerAddr != ROOT_REFERRER &&
referrerAddr != address( 0 ) &&
depth < MAX_REFERRAL_DEPTH )
{
// Update this referrer's accumulated referree scores.
holderData[ referrerAddr ].referree_etherContributed +=
etherContributed_change;
holderData[ referrerAddr ].referree_timeFactors +=
timeFactors_change;
holderData[ referrerAddr ].referree_tokenBalance +=
tokenBalance_change;
// Move to the higher-level referrer.
referrerAddr = holderData[ referrerAddr ].referrer;
depth++;
}
}
/**
* Function executes the Lottery Winner Selection Algorithm,
* and writes the final, sorted array, containing winner rankings.
*
* This function is called from the Lottery's Mining Stage Step 2,
*
* This is the final function that lottery performs actively -
* and arguably the most important - because it determines
* lottery winners through Winner Selection Algorithm.
*
* The random seed must be already set, before calling this function.
*/
function executeWinnerSelectionAlgorithm()
public
lotteryOnly
{
// Copy the Winner Algo Config into memory, to avoid using
// 400-gas costing SLOAD every time we need to load something.
WinnerAlgorithmConfig memory cfg = algConfig;
// Can only be performed if algorithm is MinedWinnerSelection!
require( cfg.endingAlgoType ==
uint8(Lottery.EndingAlgoType.MinedWinnerSelection) );
// Now, we gotta find the winners using a Randomized Score-Based
// Winner Selection Algorithm.
//
// During transfers, all player intermediate scores
// (etherContributed, timeFactors, and tokenBalances) were
// already set in every holder's HolderData structure,
// during operations of updateHolderData_preTransfer() function.
//
// Minimum and maximum values are also known, so normalization
// will be easy.
// All referral tree score data were also properly propagated
// during operations of updateAndPropagateScoreChanges() function.
//
// All we now have to do, is loop through holder array, and
// compute randomized final scores for every holder, into
// the Final Score array.
// Declare the Final Score array - computed for all holders.
uint ARRLEN =
( holders.length > MINEDSELECTION_MAX_NUMBER_OF_HOLDERS ?
MINEDSELECTION_MAX_NUMBER_OF_HOLDERS : holders.length );
FinalScore[] memory finalScores = new FinalScore[] ( ARRLEN );
// Compute the precision-adjusted constant ratio of
// referralBonus max score to the player individual max scores.
int individualToReferralRatio =
( PRECISION * cfg.maxPlayerScore_refferalBonus ) /
( int( cfg.maxPlayerScore_etherContributed ) +
int( cfg.maxPlayerScore_timeFactor ) +
int( cfg.maxPlayerScore_tokenHoldingAmount ) );
// Max available player score.
int maxAvailablePlayerScore = int(
cfg.maxPlayerScore_etherContributed +
cfg.maxPlayerScore_timeFactor +
cfg.maxPlayerScore_tokenHoldingAmount +
cfg.maxPlayerScore_refferalBonus );
// Random Factor of scores, to maintain random-to-determined
// ratio equal to specific value (1:5 for example -
// "randPart" == 5, "scorePart" == 1).
//
// maxAvailablePlayerScore * FACT --- scorePart
// RANDOM_MODULO --- randPart
//
// RANDOM_MODULO * scorePart
// maxAvailablePlayerScore * FACT = -------------------------
// randPart
//
// RANDOM_MODULO * scorePart
// FACT = --------------------------------------
// randPart * maxAvailablePlayerScore
int SCORE_RAND_FACT =
( PRECISION * int(RANDOM_MODULO * cfg.randRatio_scorePart) ) /
( int(cfg.randRatio_randPart) * maxAvailablePlayerScore );
// Fix Min-Max scores, to avoid division by zero, if min == max.
// If min == max, make the difference equal to 1.
MinMaxHolderScores memory minMaxCpy = minMaxScores;
if( minMaxCpy.holderScore_etherContributed_min ==
minMaxCpy.holderScore_etherContributed_max )
minMaxCpy.holderScore_etherContributed_max =
minMaxCpy.holderScore_etherContributed_min + 1;
if( minMaxCpy.holderScore_timeFactors_min ==
minMaxCpy.holderScore_timeFactors_max )
minMaxCpy.holderScore_timeFactors_max =
minMaxCpy.holderScore_timeFactors_min + 1;
if( minMaxCpy.holderScore_tokenBalance_min ==
minMaxCpy.holderScore_tokenBalance_max )
minMaxCpy.holderScore_tokenBalance_max =
minMaxCpy.holderScore_tokenBalance_min + 1;
// Loop through all the holders.
for( uint i = 0; i < ARRLEN; i++ )
{
// Fetch the needed holder data to in-memory hdata variable,
// to save gas on score part computing functions.
HolderData memory hdata;
// Slot 1:
hdata.etherContributed =
holderData[ holders[ i ] ].etherContributed;
hdata.timeFactors =
holderData[ holders[ i ] ].timeFactors;
hdata.tokenBalance =
holderData[ holders[ i ] ].tokenBalance;
hdata.referreeCount =
holderData[ holders[ i ] ].referreeCount;
// Slot 2:
hdata.referree_etherContributed =
holderData[ holders[ i ] ].referree_etherContributed;
hdata.referree_timeFactors =
holderData[ holders[ i ] ].referree_timeFactors;
hdata.referree_tokenBalance =
holderData[ holders[ i ] ].referree_tokenBalance;
hdata.bonusScore =
holderData[ holders[ i ] ].bonusScore;
// Now, add bonus score, and compute total player's score:
// Bonus part, individual score part, and referree score part.
int totalPlayerScore =
hdata.bonusScore
+
computeHolderIndividualScores(
cfg, minMaxCpy, hdata )
+
computeReferreeScoresForHolder(
individualToReferralRatio, cfg,
minMaxCpy, hdata );
// Check if total player score <= 0. If so, make it equal
// to 1, because otherwise randomization won't be possible.
if( totalPlayerScore <= 0 )
totalPlayerScore = 1;
// Now, check if it's not more than max! If so, lowerify.
// This could have happen'd because of bonus.
if( totalPlayerScore > maxAvailablePlayerScore )
totalPlayerScore = maxAvailablePlayerScore;
// Multiply the score by the Random Modulo Adjustment
// Factor, to get fairer ratio of random-to-determined data.
totalPlayerScore = ( totalPlayerScore * SCORE_RAND_FACT ) /
( PRECISION );
// Score is computed!
// Now, randomize it, and add to Final Scores Array.
// We use keccak to generate a random number from random seed,
// using holder's address as a nonce.
uint modulizedRandomNumber = uint(
keccak256( abi.encodePacked( randomSeed, holders[ i ] ) )
) % RANDOM_MODULO;
// Add the random number, to introduce the random factor.
// Ratio of (current) totalPlayerScore to modulizedRandomNumber
// is the same as ratio of randRatio_scorePart to
// randRatio_randPart.
uint endScore = uint( totalPlayerScore ) + modulizedRandomNumber;
// Finally, set this holder's final score data.
finalScores[ i ].addr = holders[ i ];
finalScores[ i ].holderIndex = uint16( i );
finalScores[ i ].score = uint64( endScore );
}
// All final scores are now computed.
// Sort the array, to find out the highest scores!
// Firstly, partition an array to only work on top K scores,
// where K is the number of winners.
// There can be a rare case where specified number of winners is
// more than lottery token holders. We got that covered.
require( finalScores.length > 0 );
uint K = cfg.winnerCount - 1;
if( K > finalScores.length-1 )
K = finalScores.length-1; // Must be THE LAST ELEMENT's INDEX.
// Use QuickSelect to do this.
QSort_QuickSelect( finalScores, 0,
int( finalScores.length - 1 ), int( K ) );
// Now, QuickSort only the first K items, because the rest
// item scores are not high enough to become winners.
QSort_QuickSort( finalScores, 0, int( K ) );
// Now, the winner array is sorted, with the highest scores
// sitting at the first positions!
// Let's set up the winner indexes array, where we'll store
// the winners' indexes in the holders array.
// So, if this array is [8, 2, 3], that means that
// Winner #1 is holders[8], winner #2 is holders[2], and
// winner #3 is holders[3].
// Set the Number Of Winners variable.
numberOfWinners = uint16( K + 1 );
// Now, we can loop through the first numberOfWinners elements, to set
// the holder indexes!
// Loop through 16 elements at a time, to fill the structs.
for( uint offset = 0; offset < numberOfWinners; offset += 16 )
{
WinnerIndexStruct memory windStruct;
uint loopStop = ( offset + 16 > numberOfWinners ?
numberOfWinners : offset + 16 );
for( uint i = offset; i < loopStop; i++ )
{
windStruct.indexes[ i - offset ] =finalScores[ i ].holderIndex;
}
// Push this now-filled struct to the storage array!
sortedWinnerIndexes.push( windStruct );
}
// That's it! We're done!
algorithmCompleted = true;
}
/**
* Add a holder to holders array.
* @param holder - address of a holder to add.
*/
function addHolder( address holder )
public
lotteryOnly
{
// Add it to list, and set index in the mapping.
holders.push( holder );
holderIndexes[ holder ] = holders.length - 1;
}
/**
* Removes the holder 'sender' from the Holders Array.
* However, this holder's HolderData structure persists!
*
* Notice that no index validity checks are performed, so, if
* 'sender' is not present in "holderIndexes" mapping, this
* function will remove the 0th holder instead!
* This is not a problem for us, because Lottery calls this
* function only when it's absolutely certain that 'sender' is
* present in the holders array.
*
* @param sender - address of a holder to remove.
* Named 'sender', because when token sender sends away all
* his tokens, he must then be removed from holders array.
*/
function removeHolder( address sender )
public
lotteryOnly
{
// Get index of the sender address in the holders array.
uint index = holderIndexes[ sender ];
// Remove the sender from array, by copying last element's
// value into the index'th element, where sender was before.
holders[ index ] = holders[ holders.length - 1 ];
// Remove the last element of array, which we've just copied.
holders.pop();
// Update indexes: remove the sender's index from the mapping,
// and change the previoulsy-last element's index to the
// one where we copied it - where sender was before.
delete holderIndexes[ sender ];
holderIndexes[ holders[ index ] ] = index;
}
/**
* Get holder array length.
*/
function getHolderCount()
public view
returns( uint )
{
return holders.length;
}
/**
* Generate a referral ID for a token holder.
* Referral ID is used to refer other wallets into playing our
* lottery.
* - Referrer gets bonus points for every wallet that bought
* lottery tokens and specified his referral ID.
* - Referrees (wallets who got referred by registering a valid
* referral ID, corresponding to some referrer), get some
* bonus points for specifying (registering) a referral ID.
*
* Referral ID is a uint256 number, which is generated by
* keccak256'ing the holder's address, holder's current
* token ballance, and current time.
*/
function generateReferralID( address holder )
public
lotteryOnly
returns( uint256 referralID )
{
// Check if holder has some tokens, and doesn't
// have his own referral ID yet.
require( holderData[ holder ].tokenBalance != 0 );
require( holderData[ holder ].referralID == 0 );
// Generate a referral ID with keccak.
uint256 refID = uint256( keccak256( abi.encodePacked(
holder, holderData[ holder ].tokenBalance, now ) ) );
// Specify the ID as current ID of this holder.
holderData[ holder ].referralID = refID;
// If this holder wasn't referred by anyone (his referrer is
// not set), and he's now generated his own ID, he won't
// be able to register as a referree of someone else
// from now on.
// This is done to prevent circular dependency in referrals.
// Do it by setting a referrer to ROOT_REFERRER address,
// which is an invalid address (address(1)).
if( holderData[ holder ].referrer == address( 0 ) )
holderData[ holder ].referrer = ROOT_REFERRER;
// Create a new referrer with this ID.
referrers[ refID ] = holder;
return refID;
}
/**
* Register a referral for a token holder, using a valid
* referral ID got from a referrer.
* This function is called by a referree, who obtained a
* valid referral ID from some referrer, who previously
* generated it using generateReferralID().
*
* You can only register a referral once!
* When you do so, you get bonus referral points!
*/
function registerReferral(
address holder,
int16 referralRegisteringBonus,
uint256 referralID )
public
lotteryOnly
returns( address _referrerAddress )
{
// Check if this holder has some tokens, and if he hasn't
// registered a referral yet.
require( holderData[ holder ].tokenBalance != 0 );
require( holderData[ holder ].referrer == address( 0 ) );
// Get the referrer's address from his ID, and specify
// it as a referrer of holder.
holderData[ holder ].referrer = referrers[ referralID ];
// Bonus points are added to this holder's score for
// registering a referral!
holderData[ holder ].bonusScore = referralRegisteringBonus;
// Increment number of referrees for every parent referrer,
// by traversing a referral tree child->parent way.
address referrerAddr = holderData[ holder ].referrer;
// Set the return value.
_referrerAddress = referrerAddr;
// Traverse a tree.
while( referrerAddr != ROOT_REFERRER &&
referrerAddr != address( 0 ) )
{
// Increment referree count for this referrrer.
holderData[ referrerAddr ].referreeCount++;
// Update the Referrer Scores of the referrer, adding this
// referree's scores to it's current values.
holderData[ referrerAddr ].referree_etherContributed +=
holderData[ holder ].etherContributed;
holderData[ referrerAddr ].referree_timeFactors +=
holderData[ holder ].timeFactors;
holderData[ referrerAddr ].referree_tokenBalance +=
holderData[ holder ].tokenBalance;
// Move to the higher-level referrer.
referrerAddr = holderData[ referrerAddr ].referrer;
}
return _referrerAddress;
}
/**
* Sets our random seed to some value.
* Should be called from Lottery, after obtaining random seed from
* the Randomness Provider.
*/
function setRandomSeed( uint _seed )
external
lotteryOnly
{
randomSeed = uint64( _seed );
}
/**
* Initialization function.
* Here, we bind our contract to the Lottery contract that
* this Storage belongs to.
* The parent lottery must call this function - hence, we set
* "lottery" to msg.sender.
*
* When this function is called, our contract must be not yet
* initialized - "lottery" address must be Zero!
*
* Here, we also set our Winner Algorithm config, which is a
* subset of LotteryConfig, fitting into 1 storage slot.
*/
function initialize(
WinnerAlgorithmConfig memory _wcfg )
public
{
require( address( lottery ) == address( 0 ) );
// Set the Lottery address (msg.sender can't be zero),
// and thus, set our contract to initialized!
lottery = msg.sender;
// Set the Winner-Algo-Config.
algConfig = _wcfg;
// NOT-NEEDED: Set initial min-max scores: min is INT_MAX.
/*minMaxScores.holderScore_etherContributed_min = int80( 2 ** 78 );
minMaxScores.holderScore_timeFactors_min = int80( 2 ** 78 );
minMaxScores.holderScore_tokenBalance_min = int80( 2 ** 78 );
*/
}
// ==================== Views ==================== //
// Returns the current random seed.
// If the seed hasn't been set yet (or set to 0), returns 0.
//
function getRandomSeed()
external view
returns( uint )
{
return randomSeed;
}
// Check if Winner Selection Algorithm has beed executed.
//
function minedSelection_algorithmAlreadyExecuted()
external view
returns( bool )
{
return algorithmCompleted;
}
/**
* After lottery has completed, this function returns if "addr"
* is one of lottery winners, and the position in winner rankings.
* Function is used to obtain the ranking position before
* calling claimWinnerPrize() on Lottery.
*
* This function should be called off-chain, and then using the
* retrieved data, one can call claimWinnerPrize().
*/
function minedSelection_getWinnerStatus(
address addr )
public view
returns( bool isWinner,
uint32 rankingPosition )
{
// Loop through the whole winner indexes array, trying to
// find if "addr" is one of the winner addresses.
for( uint16 i = 0; i < numberOfWinners; i++ )
{
// Check if holder on this winner ranking's index position
// is addr, if so, good!
uint pos = sortedWinnerIndexes[ i / 16 ].indexes[ i % 16 ];
if( holders[ pos ] == addr )
{
return ( true, i );
}
}
// The "addr" is not a winner.
return ( false, 0 );
}
/**
* Checks if address is on specified winner ranking position.
* Used in Lottery, to check if msg.sender is really the
* winner #rankingPosition, as he claims to be.
*/
function minedSelection_isAddressOnWinnerPosition(
address addr,
uint32 rankingPosition )
external view
returns( bool )
{
if( rankingPosition >= numberOfWinners )
return false;
// Just check if address at "holders" array
// index "sortedWinnerIndexes[ position ]" is really the "addr".
uint pos = sortedWinnerIndexes[ rankingPosition / 16 ]
.indexes[ rankingPosition % 16 ];
return ( holders[ pos ] == addr );
}
/**
* Returns an array of all winner addresses, sorted by their
* ranking position (winner #1 first, #2 second, etc.).
*/
function minedSelection_getAllWinners()
external view
returns( address[] memory )
{
address[] memory winners = new address[] ( numberOfWinners );
for( uint i = 0; i < numberOfWinners; i++ )
{
uint pos = sortedWinnerIndexes[ i / 16 ].indexes[ i % 16 ];
winners[ i ] = holders[ pos ];
}
return winners;
}
/**
* Compute the Lottery Active Stage Score of a token holder.
*
* This function computes the Active Stage (pre-randomization)
* player score, and should generally be used to compute player
* intermediate scores - while lottery is still active or on
* finishing stage, before random random seed is obtained.
*/
function getPlayerActiveStageScore( address holderAddr )
external view
returns( uint playerScore )
{
// Copy the Winner Algo Config into memory, to avoid using
// 400-gas costing SLOAD every time we need to load something.
WinnerAlgorithmConfig memory cfg = algConfig;
// Check if holderAddr is a holder at all!
if( holders[ holderIndexes[ holderAddr ] ] != holderAddr )
return 0;
// Compute the precision-adjusted constant ratio of
// referralBonus max score to the player individual max scores.
int individualToReferralRatio =
( PRECISION * cfg.maxPlayerScore_refferalBonus ) /
( int( cfg.maxPlayerScore_etherContributed ) +
int( cfg.maxPlayerScore_timeFactor ) +
int( cfg.maxPlayerScore_tokenHoldingAmount ) );
// Max available player score.
int maxAvailablePlayerScore = int(
cfg.maxPlayerScore_etherContributed +
cfg.maxPlayerScore_timeFactor +
cfg.maxPlayerScore_tokenHoldingAmount +
cfg.maxPlayerScore_refferalBonus );
// Fix Min-Max scores, to avoid division by zero, if min == max.
// If min == max, make the difference equal to 1.
MinMaxHolderScores memory minMaxCpy = minMaxScores;
if( minMaxCpy.holderScore_etherContributed_min ==
minMaxCpy.holderScore_etherContributed_max )
minMaxCpy.holderScore_etherContributed_max =
minMaxCpy.holderScore_etherContributed_min + 1;
if( minMaxCpy.holderScore_timeFactors_min ==
minMaxCpy.holderScore_timeFactors_max )
minMaxCpy.holderScore_timeFactors_max =
minMaxCpy.holderScore_timeFactors_min + 1;
if( minMaxCpy.holderScore_tokenBalance_min ==
minMaxCpy.holderScore_tokenBalance_max )
minMaxCpy.holderScore_tokenBalance_max =
minMaxCpy.holderScore_tokenBalance_min + 1;
// Now, add bonus score, and compute total player's score:
// Bonus part, individual score part, and referree score part.
int totalPlayerScore =
holderData[ holderAddr ].bonusScore
+
computeHolderIndividualScores(
cfg, minMaxCpy, holderData[ holderAddr ] )
+
computeReferreeScoresForHolder(
individualToReferralRatio, cfg,
minMaxCpy, holderData[ holderAddr ] );
// Check if total player score <= 0. If so, make it equal
// to 1, because otherwise randomization won't be possible.
if( totalPlayerScore <= 0 )
totalPlayerScore = 1;
// Now, check if it's not more than max! If so, lowerify.
// This could have happen'd because of bonus.
if( totalPlayerScore > maxAvailablePlayerScore )
totalPlayerScore = maxAvailablePlayerScore;
// Return the score!
return uint( totalPlayerScore );
}
/**
* Internal sub-procedure of the function below, used to obtain
* a final, randomized score of a Single Holder.
*/
function priv_getSingleHolderScore(
address hold3r,
int individualToReferralRatio,
int maxAvailablePlayerScore,
int SCORE_RAND_FACT,
WinnerAlgorithmConfig memory cfg,
MinMaxHolderScores memory minMaxCpy )
internal view
returns( uint endScore )
{
// Fetch the needed holder data to in-memory hdata variable,
// to save gas on score part computing functions.
HolderData memory hdata;
// Slot 1:
hdata.etherContributed =
holderData[ hold3r ].etherContributed;
hdata.timeFactors =
holderData[ hold3r ].timeFactors;
hdata.tokenBalance =
holderData[ hold3r ].tokenBalance;
hdata.referreeCount =
holderData[ hold3r ].referreeCount;
// Slot 2:
hdata.referree_etherContributed =
holderData[ hold3r ].referree_etherContributed;
hdata.referree_timeFactors =
holderData[ hold3r ].referree_timeFactors;
hdata.referree_tokenBalance =
holderData[ hold3r ].referree_tokenBalance;
hdata.bonusScore =
holderData[ hold3r ].bonusScore;
// Now, add bonus score, and compute total player's score:
// Bonus part, individual score part, and referree score part.
int totalPlayerScore =
hdata.bonusScore
+
computeHolderIndividualScores(
cfg, minMaxCpy, hdata )
+
computeReferreeScoresForHolder(
individualToReferralRatio, cfg,
minMaxCpy, hdata );
// Check if total player score <= 0. If so, make it equal
// to 1, because otherwise randomization won't be possible.
if( totalPlayerScore <= 0 )
totalPlayerScore = 1;
// Now, check if it's not more than max! If so, lowerify.
// This could have happen'd because of bonus.
if( totalPlayerScore > maxAvailablePlayerScore )
totalPlayerScore = maxAvailablePlayerScore;
// Multiply the score by the Random Modulo Adjustment
// Factor, to get fairer ratio of random-to-determined data.
totalPlayerScore = ( totalPlayerScore * SCORE_RAND_FACT ) /
( PRECISION );
// Score is computed!
// Now, randomize it, and add to Final Scores Array.
// We use keccak to generate a random number from random seed,
// using holder's address as a nonce.
uint modulizedRandomNumber = uint(
keccak256( abi.encodePacked( randomSeed, hold3r ) )
) % RANDOM_MODULO;
// Add the random number, to introduce the random factor.
// Ratio of (current) totalPlayerScore to modulizedRandomNumber
// is the same as ratio of randRatio_scorePart to
// randRatio_randPart.
return uint( totalPlayerScore ) + modulizedRandomNumber;
}
/**
* Winner Self-Validation algo-type main function.
* Here, we compute scores for all lottery holders iteratively
* in O(n) time, and thus get the winner ranking position of
* the holder in question.
*
* This function performs essentialy the same steps as the
* Mined-variant (executeWinnerSelectionAlgorithm), but doesn't
* write anything to blockchain.
*
* @param holderAddr - address of a holder whose rank we want to find.
*/
function winnerSelfValidation_getWinnerStatus(
address holderAddr )
internal view
returns( bool isWinner, uint rankingPosition )
{
// Copy the Winner Algo Config into memory, to avoid using
// 400-gas costing SLOAD every time we need to load something.
WinnerAlgorithmConfig memory cfg = algConfig;
// Can only be performed if algorithm is WinnerSelfValidation!
require( cfg.endingAlgoType ==
uint8(Lottery.EndingAlgoType.WinnerSelfValidation) );
// Check if holderAddr is a holder at all!
require( holders[ holderIndexes[ holderAddr ] ] == holderAddr );
// Now, we gotta find the winners using a Randomized Score-Based
// Winner Selection Algorithm.
//
// During transfers, all player intermediate scores
// (etherContributed, timeFactors, and tokenBalances) were
// already set in every holder's HolderData structure,
// during operations of updateHolderData_preTransfer() function.
//
// Minimum and maximum values are also known, so normalization
// will be easy.
// All referral tree score data were also properly propagated
// during operations of updateAndPropagateScoreChanges() function.
//
// All we now have to do, is loop through holder array, and
// compute randomized final scores for every holder.
// Compute the precision-adjusted constant ratio of
// referralBonus max score to the player individual max scores.
int individualToReferralRatio =
( PRECISION * cfg.maxPlayerScore_refferalBonus ) /
( int( cfg.maxPlayerScore_etherContributed ) +
int( cfg.maxPlayerScore_timeFactor ) +
int( cfg.maxPlayerScore_tokenHoldingAmount ) );
// Max available player score.
int maxAvailablePlayerScore = int(
cfg.maxPlayerScore_etherContributed +
cfg.maxPlayerScore_timeFactor +
cfg.maxPlayerScore_tokenHoldingAmount +
cfg.maxPlayerScore_refferalBonus );
// Random Factor of scores, to maintain random-to-determined
// ratio equal to specific value (1:5 for example -
// "randPart" == 5, "scorePart" == 1).
//
// maxAvailablePlayerScore * FACT --- scorePart
// RANDOM_MODULO --- randPart
//
// RANDOM_MODULO * scorePart
// maxAvailablePlayerScore * FACT = -------------------------
// randPart
//
// RANDOM_MODULO * scorePart
// FACT = --------------------------------------
// randPart * maxAvailablePlayerScore
int SCORE_RAND_FACT =
( PRECISION * int(RANDOM_MODULO * cfg.randRatio_scorePart) ) /
( int(cfg.randRatio_randPart) * maxAvailablePlayerScore );
// Fix Min-Max scores, to avoid division by zero, if min == max.
// If min == max, make the difference equal to 1.
MinMaxHolderScores memory minMaxCpy = minMaxScores;
if( minMaxCpy.holderScore_etherContributed_min ==
minMaxCpy.holderScore_etherContributed_max )
minMaxCpy.holderScore_etherContributed_max =
minMaxCpy.holderScore_etherContributed_min + 1;
if( minMaxCpy.holderScore_timeFactors_min ==
minMaxCpy.holderScore_timeFactors_max )
minMaxCpy.holderScore_timeFactors_max =
minMaxCpy.holderScore_timeFactors_min + 1;
if( minMaxCpy.holderScore_tokenBalance_min ==
minMaxCpy.holderScore_tokenBalance_max )
minMaxCpy.holderScore_tokenBalance_max =
minMaxCpy.holderScore_tokenBalance_min + 1;
// How many holders had higher scores than "holderAddr".
// Used to obtain the final winner rank of "holderAddr".
uint numOfHoldersHigherThan = 0;
// The final (randomized) score of "holderAddr".
uint holderAddrsFinalScore = priv_getSingleHolderScore(
holderAddr,
individualToReferralRatio,
maxAvailablePlayerScore,
SCORE_RAND_FACT,
cfg, minMaxCpy );
// Index of holderAddr.
uint holderAddrIndex = holderIndexes[ holderAddr ];
// Loop through all the allowed holders.
for( uint i = 0;
i < ( holders.length < SELFVALIDATION_MAX_NUMBER_OF_HOLDERS ?
holders.length : SELFVALIDATION_MAX_NUMBER_OF_HOLDERS );
i++ )
{
// Skip the holderAddr's index.
if( i == holderAddrIndex )
continue;
// Compute the score using helper function.
uint endScore = priv_getSingleHolderScore(
holders[ i ],
individualToReferralRatio,
maxAvailablePlayerScore,
SCORE_RAND_FACT,
cfg, minMaxCpy );
// Check if score is higher than HolderAddr's, and if so, check.
if( endScore > holderAddrsFinalScore )
numOfHoldersHigherThan++;
}
// All scores are checked!
// Now, we can obtain holderAddr's winner rank based on how
// many scores were above holderAddr's score!
isWinner = ( numOfHoldersHigherThan < cfg.winnerCount );
rankingPosition = numOfHoldersHigherThan;
}
/**
* Rolled-Randomness algo-type main function.
* Here, we only compute the score of the holder in question,
* and compare it to maximum-available final score, divided
* by no-of-winners.
*
* @param holderAddr - address of a holder whose rank we want to find.
*/
function rolledRandomness_getWinnerStatus(
address holderAddr )
internal view
returns( bool isWinner, uint rankingPosition )
{
// Copy the Winner Algo Config into memory, to avoid using
// 400-gas costing SLOAD every time we need to load something.
WinnerAlgorithmConfig memory cfg = algConfig;
// Can only be performed if algorithm is RolledRandomness!
require( cfg.endingAlgoType ==
uint8(Lottery.EndingAlgoType.RolledRandomness) );
// Check if holderAddr is a holder at all!
require( holders[ holderIndexes[ holderAddr ] ] == holderAddr );
// Now, we gotta find the winners using a Randomized Score-Based
// Winner Selection Algorithm.
//
// During transfers, all player intermediate scores
// (etherContributed, timeFactors, and tokenBalances) were
// already set in every holder's HolderData structure,
// during operations of updateHolderData_preTransfer() function.
//
// Minimum and maximum values are also known, so normalization
// will be easy.
// All referral tree score data were also properly propagated
// during operations of updateAndPropagateScoreChanges() function.
//
// All we now have to do, is loop through holder array, and
// compute randomized final scores for every holder.
// Compute the precision-adjusted constant ratio of
// referralBonus max score to the player individual max scores.
int individualToReferralRatio =
( PRECISION * cfg.maxPlayerScore_refferalBonus ) /
( int( cfg.maxPlayerScore_etherContributed ) +
int( cfg.maxPlayerScore_timeFactor ) +
int( cfg.maxPlayerScore_tokenHoldingAmount ) );
// Max available player score.
int maxAvailablePlayerScore = int(
cfg.maxPlayerScore_etherContributed +
cfg.maxPlayerScore_timeFactor +
cfg.maxPlayerScore_tokenHoldingAmount +
cfg.maxPlayerScore_refferalBonus );
// Random Factor of scores, to maintain random-to-determined
// ratio equal to specific value (1:5 for example -
// "randPart" == 5, "scorePart" == 1).
//
// maxAvailablePlayerScore * FACT --- scorePart
// RANDOM_MODULO --- randPart
//
// RANDOM_MODULO * scorePart
// maxAvailablePlayerScore * FACT = -------------------------
// randPart
//
// RANDOM_MODULO * scorePart
// FACT = --------------------------------------
// randPart * maxAvailablePlayerScore
int SCORE_RAND_FACT =
( PRECISION * int(RANDOM_MODULO * cfg.randRatio_scorePart) ) /
( int(cfg.randRatio_randPart) * maxAvailablePlayerScore );
// Fix Min-Max scores, to avoid division by zero, if min == max.
// If min == max, make the difference equal to 1.
MinMaxHolderScores memory minMaxCpy = minMaxScores;
if( minMaxCpy.holderScore_etherContributed_min ==
minMaxCpy.holderScore_etherContributed_max )
minMaxCpy.holderScore_etherContributed_max =
minMaxCpy.holderScore_etherContributed_min + 1;
if( minMaxCpy.holderScore_timeFactors_min ==
minMaxCpy.holderScore_timeFactors_max )
minMaxCpy.holderScore_timeFactors_max =
minMaxCpy.holderScore_timeFactors_min + 1;
if( minMaxCpy.holderScore_tokenBalance_min ==
minMaxCpy.holderScore_tokenBalance_max )
minMaxCpy.holderScore_tokenBalance_max =
minMaxCpy.holderScore_tokenBalance_min + 1;
// The final (randomized) score of "holderAddr".
uint holderAddrsFinalScore = priv_getSingleHolderScore(
holderAddr,
individualToReferralRatio,
maxAvailablePlayerScore,
SCORE_RAND_FACT,
cfg, minMaxCpy );
// Now, compute the Max-Final-Random Score, divide it
// by the Holder Count, and get the ranking by placing this
// holder's score in it's corresponding part.
//
// In this approach, we assume linear randomness distribution.
// In practice, distribution might be a bit different, but this
// approach is the most efficient.
//
// Max-Final-Score (randomized) is the highest available score
// that can be achieved, and is made by adding together the
// maximum availabe Player Score Part and maximum available
// Random Part (equals RANDOM_MODULO).
// These parts have a ratio equal to config-specified
// randRatio_scorePart to randRatio_randPart.
//
// So, if player's active stage's score is low (1), but rand-part
// in ratio is huge, then the score is mostly random, so
// maxFinalScore is close to the RANDOM_MODULO - maximum random
// value that can be rolled.
//
// If, however, we use 1:1 playerScore-to-Random Ratio, then
// playerScore and RandomScore make up equal parts of end score,
// so the maxFinalScore is actually two times larger than
// RANDOM_MODULO, so player needs to score more
// player-points to get larger prizes.
//
// In default configuration, playerScore-to-random ratio is 1:3,
// so there's a good randomness factor, so even the low-scoring
// players can reasonably hope to get larger prizes, but
// the higher is player's active stage score, the more
// chances of scoring a high final score a player gets, with
// the higher-end of player scores basically guaranteeing
// themselves a specific prize amount, if winnerCount is
// big enough to overlap.
int maxRandomPart = int( RANDOM_MODULO - 1 );
int maxPlayerScorePart = ( SCORE_RAND_FACT * maxAvailablePlayerScore )
/ PRECISION;
uint maxFinalScore = uint( maxRandomPart + maxPlayerScorePart );
// Compute the amount that single-holder's virtual part
// might take up in the max-final score.
uint singleHolderPart = maxFinalScore / holders.length;
// Now, compute how many single-holder-parts are there in
// this holder's score.
uint holderAddrScorePartCount = holderAddrsFinalScore /
singleHolderPart;
// The ranking is that number, minus holders length.
// If very high score is scored, default to position 0 (highest).
rankingPosition = (
holderAddrScorePartCount < holders.length ?
holders.length - holderAddrScorePartCount : 0
);
isWinner = ( rankingPosition < cfg.winnerCount );
}
/**
* Genericized, algorithm type-dependent getWinnerStatus function.
*/
function getWinnerStatus(
address addr )
external view
returns( bool isWinner, uint32 rankingPosition )
{
bool _isW;
uint _rp;
if( algConfig.endingAlgoType ==
uint8(Lottery.EndingAlgoType.RolledRandomness) )
{
(_isW, _rp) = rolledRandomness_getWinnerStatus( addr );
return ( _isW, uint32( _rp ) );
}
if( algConfig.endingAlgoType ==
uint8(Lottery.EndingAlgoType.WinnerSelfValidation) )
{
(_isW, _rp) = winnerSelfValidation_getWinnerStatus( addr );
return ( _isW, uint32( _rp ) );
}
if( algConfig.endingAlgoType ==
uint8(Lottery.EndingAlgoType.MinedWinnerSelection) )
{
(_isW, _rp) = minedSelection_getWinnerStatus( addr );
return ( _isW, uint32( _rp ) );
}
}
}
contract UniLotteryStorageFactory
{
// The Pool Address.
address payable poolAddress;
// The Delegate Logic contract, containing all code for
// all LotteryStorage contracts to be deployed.
address immutable delegateContract;
// Pool-Only modifier.
modifier poolOnly
{
require( msg.sender == poolAddress );
_;
}
// Constructor.
// Deploy the Delegate Contract here.
//
constructor() public
{
delegateContract = address( new LotteryStorage() );
}
// Initialization function.
// Set the poolAddress as msg.sender, and lock it.
function initialize()
external
{
require( poolAddress == address( 0 ) );
// Set the Pool's Address.
poolAddress = msg.sender;
}
/**
* Deploy a new Lottery Storage Stub, to be used by it's corresponding
* Lottery Stub, which will be created later, passing this Storage
* we create here.
* @return newStorage - the Lottery Storage Stub contract just deployed.
*/
function createNewStorage()
public
poolOnly
returns( address newStorage )
{
return address( new LotteryStorageStub( delegateContract ) );
}
}
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;
}
}
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
library 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);
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);
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0);//, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0);//, errorMessage);
return a % b;
}
}
contract 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 virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for `sender`'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public 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 virtual {
require(sender != address(0));
require(recipient != address(0));
_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));
_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));
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0));
require(spender != address(0));
_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"));
}
}
interface IUniswapPair is IERC20
{
// Addresses of the first and second pool-kens.
function token0() external view returns (address);
function token1() external view returns (address);
// Get the pair's token pool reserves.
function getReserves()
external view
returns (
uint112 reserve0,
uint112 reserve1,
uint32 blockTimestampLast
);
}
contract Lottery is ERC20, CoreUniLotterySettings
{
// ===================== Events ===================== //
// After initialize() function finishes.
event LotteryInitialized();
// Emitted when lottery active stage ends (Mining Stage starts),
// on Mining Stage Step 1, after transferring profits to their
// respective owners (pool and OWNER_ADDRESS).
event LotteryEnd(
uint128 totalReturn,
uint128 profitAmount
);
// Emitted when on final finish, we call Randomness Provider
// to callback us with random value.
event RandomnessProviderCalled();
// Requirements for finishing stage start have been reached -
// finishing stage has started.
event FinishingStageStarted();
// We were currently on the finishing stage, but some requirement
// is no longer met. We must stop the finishing stage.
event FinishingStageStopped();
// New Referral ID has been generated.
event ReferralIDGenerated(
address referrer,
uint256 id
);
// New referral has been registered with a valid referral ID.
event ReferralRegistered(
address referree,
address referrer,
uint256 id
);
// Fallback funds received.
event FallbackEtherReceiver(
address sender,
uint value
);
// ====================== Structs & Enums ====================== //
// Lottery Stages.
// Described in more detail above, on contract's main doc.
enum STAGE
{
// Initial stage - before the initialize() function is called.
INITIAL,
// Active Stage: On this stage, all token trading occurs.
ACTIVE,
// Finishing stage:
// This is when all finishing criteria are met, and for every
// transfer, we're rolling a pseudo-random number to determine
// if we should end the lottery (move to Ending stage).
FINISHING,
// Ending - Mining Stage:
// This stage starts after we lottery is no longer active,
// finishing stage ends. On this stage, Miners perform the
// Ending Algorithm and other operations.
ENDING_MINING,
// Lottery is completed - this is set after the Mining Stage ends.
// In this stage, Lottery Winners can claim their prizes.
COMPLETION,
// DISABLED stage. Used when we want a lottery contract to be
// absolutely disabled - so no state-modifying functions could
// be called.
// This is used in DelegateCall scenarios, where state-contract
// delegate-calls code contract, to save on deployment costs.
DISABLED
}
// Ending algorithm types enum.
enum EndingAlgoType
{
// 1. Mined Winner Selection Algorithm.
// This algorithm is executed by a Lottery Miner in a single
// transaction, on Mining Step 2.
//
// On that single transaction, all ending scores for all
// holders are computed, and a sorted winner array is formed,
// which is written onto the LotteryStorage state.
// Thus, it's gas expensive, and suitable only for small
// holder numbers (up to 300).
//
// Pros:
// + Guaranteed deterministically specifiable winner prize
// distribution - for example, if we specify that there
// must be 2 winners, of which first gets 60% of prize funds,
// and second gets 40% of prize funds, then it's
// guarateed that prize funds will be distributed just
// like that.
//
// + Low gas cost of prize claims - only ~ 40,000 gas for
// claiming a prize.
//
// Cons:
// - Not scaleable - as the Winner Selection Algorithm is
// executed in a single transaction, it's limited by
// block gas limit - 12,500,000 on the MainNet.
// Thus, the lottery is limited to ~300 holders, and
// max. ~200 winners of those holders.
// So, it's suitable for only express-lotteries, where
// a lottery runs only until ~300 holders are reached.
//
// - High mining costs - if lottery has 300 holders,
// mining transaction takes up whole block gas limit.
//
MinedWinnerSelection,
// 2. Winner Self-Validation Algorithm.
//
// This algorithm does no operations during the Mining Stage
// (except for setting up a Random Seed in Lottery Storage) -
// the winner selection (obtaining a winner rank) is done by
// the winners themselves, when calling the prize claim
// functions.
//
// This algorithm relies on a fact that by the time that
// random seed is obtained, all data needed for winner selection
// is already there - the holder scores of the Active Stage
// (ether contributed, time factors, token balance), and
// the Random Data (random seed + nonce (holder's address)),
// so, there is no need to compute and sort the scores for the
// whole holder array.
//
// It's done like this: the holder checks if he's a winner, using
// a view-function off-chain, and if so, he calls the
// claimWinnerPrize() function, which obtains his winner rank
// on O(n) time, and does no writing to contract states,
// except for prize transfer-related operations.
//
// When computing the winner's rank on LotteryStorage,
// O(n) time is needed, as we loop through the holders array,
// computing ending scores for each holder, using already-known
// data.
// However that means that for every prize claim, all scores of
// all holders must be re-computed.
// Computing a score for a single holder takes roughly 1500 gas
// (400 for 3 slots SLOAD, and ~300 for arithmetic operations).
//
// So, this algorithm makes prize claims more expensive for
// every lottery holder.
// If there's 1000 holders, prize claim takes up 1,500,000 gas,
// so, this algorithm is not suitable for small prizes,
// because gas fee would be higher than the prize amount won.
//
// Pros:
// + Guaranteed deterministically specifiable winner prize
// distribution (same as for algorithm 1).
//
// + No mining costs for winner selection algorithm.
//
// + More scalable than algorithm 1.
//
// Cons:
// - High gas costs of prize claiming, rising with the number
// of lottery holders - 1500 for every lottery holder.
// Thus, suitable for only large prize amounts.
//
WinnerSelfValidation,
// 3. Rolled-Randomness algorithm.
//
// This algorithm is the most cheapest in terms of gas, but
// the winner prize distribution is non-deterministic.
//
// This algorithm doesn't employ miners (no mining costs),
// and doesn't require to compute scores for every holder
// prior to getting a winner's rank, thus is the most scalable.
//
// It works like this: a holder checks his winner status by
// computing only his own randomized score (rolling a random
// number from the random seed, and multiplying it by holder's
// Active Stage score), and computing this randomized-score's
// ratio relative to maximum available randomized score.
// The higher the ratio, the higher the winner rank is.
//
// However, many players can roll very high or low scores, and
// get the same prizes, so it's difficult to make a fair and
// efficient deterministic prize distribution mechanism, so
// we have to fallback to specific heuristic workarounds.
//
// Pros:
// + Scalable: O(1) complexity for computing a winner rank,
// so there can be an unlimited amount of lottery holders,
// and gas costs for winner selection and prize claim would
// still be constant & low.
//
// + Gas-efficient: gas costs for all winner-related operations
// are constant and low, because only single holder's score
// is computed.
//
// + Doesn't require mining - even more gas savings.
//
// Cons:
// + Hard to make a deterministic and fair prize distribution
// mechanism, because of un-known environment - as only
// single holder's score is compared to max-available
// random score, not taking into account other holder
// scores.
//
RolledRandomness
}
/**
* Gas-efficient, minimal config, which specifies only basic,
* most-important and most-used settings.
*/
struct LotteryConfig
{
// ================ Misc Settings =============== //
// --------- Slot --------- //
// Initial lottery funds (initial market cap).
// Specified by pool, and is used to check if initial funds
// transferred to fallback are correct - equal to this value.
uint initialFunds;
// --------- Slot --------- //
// The minimum ETH value of lottery funds, that, once
// reached on an exchange liquidity pool (Uniswap, or our
// contract), must be guaranteed to not shrink below this value.
//
// This is accomplished in _transfer() function, by denying
// all sells that would drop the ETH amount in liquidity pool
// below this value.
//
// But on initial lottery stage, before this minimum requirement
// is reached for the first time, all sells are allowed.
//
// This value is expressed in ETH - total amount of ETH funds
// that we own in Uniswap liquidity pair.
//
// So, if initial funds were 10 ETH, and this is set to 100 ETH,
// after liquidity pool's ETH value reaches 100 ETH, all further
// sells which could drop the liquidity amount below 100 ETH,
// would be denied by require'ing in _transfer() function
// (transactions would be reverted).
//
uint128 fundRequirement_denySells;
// ETH value of our funds that we own in Uniswap Liquidity Pair,
// that's needed to start the Finishing Stage.
uint128 finishCriteria_minFunds;
// --------- Slot --------- //
// Maximum lifetime of a lottery - maximum amount of time
// allowed for lottery to stay active.
// By default, it's two weeks.
// If lottery is still active (hasn't returned funds) after this
// time, lottery will stop on the next token transfer.
uint32 maxLifetime;
// Maximum prize claiming time - for how long the winners
// may be able to claim their prizes after lottery ending.
uint32 prizeClaimTime;
// Token transfer burn rates for buyers, and a default rate for
// sells and non-buy-sell transfers.
uint32 burn_buyerRate;
uint32 burn_defaultRate;
// Maximum amount of tokens (in percentage of initial supply)
// to be allowed to own by a single wallet.
uint32 maxAmountForWallet_percentageOfSupply;
// The required amount of time that must pass after
// the request to Randomness Provider has been made, for
// external actors to be able to initiate alternative
// seed generation algorithm.
uint32 REQUIRED_TIME_WAITING_FOR_RANDOM_SEED;
// ================ Profit Shares =============== //
// "Mined Uniswap Lottery" ending Ether funds, which were obtained
// by removing token liquidity from Uniswap, are transfered to
// these recipient categories:
//
// 1. The Main Pool: Initial funds, plus Pool's profit share.
// 2. The Owner: Owner's profit share.
//
// 3. The Miners: Miner rewards for executing the winner
// selection algorithm stages.
// The more holders there are, the more stages the
// winner selection algorithm must undergo.
// Each Miner, who successfully completed an algorithm
// stage, will get ETH reward equal to:
// (minerProfitShare / totalAlgorithmStages).
//
// 4. The Lottery Winners: All remaining funds are given to
// Lottery Winners, which were determined by executing
// the Winner Selection Algorithm at the end of the lottery
// (Miners executed it).
// The Winners can claim their prizes by calling a
// dedicated function in our contract.
//
// The profit shares of #1 and #2 have controlled value ranges
// specified in CoreUniLotterySettings.
//
// All these shares are expressed as percentages of the
// lottery profit amount (totalReturn - initialFunds).
// Percentages are expressed using the PERCENT constant,
// defined in CoreUniLotterySettings.
//
// Here we specify profit shares of Pool, Owner, and the Miners.
// Winner Prize Fund is all that's left (must be more than 50%
// of all profits).
//
uint32 poolProfitShare;
uint32 ownerProfitShare;
// --------- Slot --------- //
uint32 minerProfitShare;
// =========== Lottery Finish criteria =========== //
// Lottery finish by design is a whole soft stage, that
// starts when criteria for holders and fund gains are met.
// During this stage, for every token transfer, a pseudo-random
// number will be rolled for lottery finish, with increasing
// probability.
//
// There are 2 ways that this probability increase is
// implemented:
// 1. Increasing on every new holder.
// 2. Increasing on every transaction after finish stage
// was initiated.
//
// On every new holder, probability increases more than on
// new transactions.
//
// However, if during this stage some criteria become
// no-longer-met, the finish stage is cancelled.
// This cancel can be implemented by setting finish probability
// to zero, or leaving it as it was, but pausing the finishing
// stage.
// This is controlled by finish_resetProbabilityOnStop flag -
// if not set, probability stays the same, when the finishing
// stage is discontinued.
// ETH value of our funds that we own in Uniswap Liquidity Pair,
// that's needed to start the Finishing Stage.
//
// LOOK ABOVE - arranged for tight-packing.
// Minimum number of token holders required to start the
// finishing stage.
uint32 finishCriteria_minNumberOfHolders;
// Minimum amount of time that lottery must be active.
uint32 finishCriteria_minTimeActive;
// Initial finish probability, when finishing stage was
// just initiated.
uint32 finish_initialProbability;
// Finishing probability increase steps, for every new
// transaction and every new holder.
// If holder number decreases, probability decreases.
uint32 finish_probabilityIncreaseStep_transaction;
uint32 finish_probabilityIncreaseStep_holder;
// =========== Winner selection config =========== //
// Winner selection algorithm settings.
//
// Algorithm is based on score, which is calculated for
// every holder on lottery finish, and is comprised of
// the following parts.
// Each part is normalized to range ( 0 - scorePoints ),
// from smallest to largest value of each holder;
//
// After scores are computed, they are multiplied by
// holder count factor (holderCount / holderCountDivisor),
// and finally, multiplied by safely-generated random values,
// to get end winning scores.
// The top scorers win prizes.
//
// By default setting, max score is 40 points, and it's
// comprised of the following parts:
//
// 1. Ether contributed (when buying from Uniswap or contract).
// Gets added when buying, and subtracted when selling.
// Default: 10 points.
//
// 2. Amount of lottery tokens holder has on finish.
// Default: 5 points.
//
// 3. Ether contributed, multiplied by the relative factor
// of time - that is, "now" minus "lotteryStartTime".
// This way, late buyers can get more points even if
// they get little tokens and don't spend much ether.
// Default: 5 points.
//
// 4. Refferrer bonus. For every player that joined with
// your referral ID, you get (that player's score) / 10
// points! This goes up to specified max score.
// Also, every player who provides a valid referral ID,
// gets 2 points for free!
// Default max bonus: 20 points.
//
int16 maxPlayerScore_etherContributed;
int16 maxPlayerScore_tokenHoldingAmount;
int16 maxPlayerScore_timeFactor;
int16 maxPlayerScore_refferalBonus;
// --------- Slot --------- //
// Score-To-Random ration data (as a rational ratio number).
// For example if 1:5, then scorePart = 1, and randPart = 5.
uint16 randRatio_scorePart;
uint16 randRatio_randPart;
// Time factor divisor - interval of time, in seconds, after
// which time factor is increased by one.
uint16 timeFactorDivisor;
// Bonus score a player should get when registering a valid
// referral code obtained from a referrer.
int16 playerScore_referralRegisteringBonus;
// Are we resetting finish probability when finishing stage
// stops, if some criteria are no longer met?
bool finish_resetProbabilityOnStop;
// =========== Winner Prize Fund Settings =========== //
// There are 2 available modes that we can use to distribute
// winnings: a computable sequence (geometrical progression),
// or an array of winner prize fund share percentages.
// More gas efficient is to use a computable sequence,
// where each winner gets a share equal to (factor * fundsLeft).
// Factor is in range [0.01 - 1.00] - simulated as [1% - 100%].
//
// For example:
// Winner prize fund is 100 ethers, Factor is 1/4 (25%), and
// there are 5 winners total (winnerCount), and sequenced winner
// count is 2 (sequencedWinnerCount).
//
// So, we pre-compute the upper shares, till we arrive to the
// sequenced winner count, in a loop:
// - Winner 1: 0.25 * 100 = 25 eth; 100 - 25 = 75 eth left.
// - Winner 2: 0.25 * 75 ~= 19 eth; 75 - 19 = 56 eth left.
//
// Now, we compute the left-over winner shares, which are
// winners that get their prizes from the funds left after the
// sequence winners.
//
// So, we just divide the leftover funds (56 eth), by 3,
// because winnerCount - sequencedWinnerCount = 3.
// - Winner 3 = 56 / 3 = 18 eth;
// - Winner 4 = 56 / 3 = 18 eth;
// - Winner 5 = 56 / 3 = 18 eth;
//
// If this value is 0, then we'll assume that array-mode is
// to be used.
uint32 prizeSequenceFactor;
// Maximum number of winners that the prize sequence can yield,
// plus the leftover winners, which will get equal shares of
// the remainder from the first-prize sequence.
uint16 prizeSequence_winnerCount;
// How many winners would get sequence-computed prizes.
// The left-over winners
// This is needed because prizes in sequence tend to zero, so
// we need to limit the sequence to avoid very small prizes,
// and to avoid the remainder.
uint16 prizeSequence_sequencedWinnerCount;
// Initial token supply (without decimals).
uint48 initialTokenSupply;
// Ending Algorithm type.
// More about the 3 algorithm types above.
uint8 endingAlgoType;
// --------- Slot --------- //
// Array mode: The winner profit share percentages array.
// For example, lottery profits can be distributed this way:
//
// Winner profit shares (8 winners):
// [ 20%, 15%, 10%, 5%, 4%, 3%, 2%, 1% ] = 60% of profits.
// Owner profits: 10%
// Pool profits: 30%
//
// Pool profit share is not defined explicitly in the config, so
// when we internally validate specified profit shares, we
// assume the pool share to be the left amount until 100% ,
// but we also make sure that this amount is at least equal to
// MIN_POOL_PROFITS, defined in CoreSettings.
//
uint32[] winnerProfitShares;
}
// ========================= Constants ========================= //
// The Miner Profits - max/min values.
// These aren't defined in Core Settings, because Miner Profits
// are only specific to this lottery type.
uint32 constant MIN_MINER_PROFITS = 1 * PERCENT;
uint32 constant MAX_MINER_PROFITS = 10 * PERCENT;
// Uniswap Router V2 contract instance.
// Address is the same for MainNet, and all public testnets.
IUniswapRouter constant uniswapRouter = IUniswapRouter(
address( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ) );
// Public-accessible ERC20 token specific constants.
string constant public name = "UniLottery Token";
string constant public symbol = "ULT";
uint256 constant public decimals = 18;
// =================== State Variables =================== //
// ------- Initial Slots ------- //
// The config which is passed to constructor.
LotteryConfig internal cfg;
// ------- Slot ------- //
// The Lottery Storage contract, which stores all holder data,
// such as scores, referral tree data, etc.
LotteryStorage public lotStorage;
// ------- Slot ------- //
// Pool address. Set on constructor from msg.sender.
address payable public poolAddress;
// ------- Slot ------- //
// Randomness Provider address.
address public randomnessProvider;
// ------- Slot ------- //
// Exchange address. In Uniswap mode, it's the Uniswap liquidity
// pair's address, where trades execute.
address public exchangeAddress;
// Start date.
uint32 public startDate;
// Completion (Mining Phase End) date.
uint32 public completionDate;
// The date when Randomness Provider was called, requesting a
// random seed for the lottery finish.
// Also, when this variable becomes Non-Zero, it indicates that we're
// on Ending Stage Part One: waiting for the random seed.
uint32 finish_timeRandomSeedRequested;
// ------- Slot ------- //
// WETH address. Set by calling Router's getter, on constructor.
address WETHaddress;
// Is the WETH first or second token in our Uniswap Pair?
bool uniswap_ethFirst;
// If we are, or were before, on finishing stage, this is the
// probability of lottery going to Ending Stage on this transaction.
uint32 finishProbablity;
// Re-Entrancy Lock (Mutex).
// We protect for reentrancy in the Fund Transfer functions.
bool reEntrancyMutexLocked;
// On which stage we are currently.
uint8 public lotteryStage;
// Indicator for whether the lottery fund gains have passed a
// minimum fund gain requirement.
// After that time point (when this bool is set), the token sells
// which could drop the fund value below the requirement, would
// be denied.
bool fundGainRequirementReached;
// The current step of the Mining Stage.
uint16 miningStep;
// If we're currently on Special Transfer Mode - that is, we allow
// direct transfers between parties even in NON-ACTIVE state.
bool specialTransferModeEnabled;
// ------- Slot ------- //
// Per-Transaction Pseudo-Random hash value (transferHashValue).
// This value is computed on every token transfer, by keccak'ing
// the last (current) transferHashValue, msg.sender, now, and
// transaction count.
//
// This is used on Finishing Stage, as a pseudo-random number,
// which is used to check if we should end the lottery (move to
// Ending Stage).
uint256 transferHashValue;
// ------- Slot ------- //
// On lottery end, get & store the lottery total ETH return
// (including initial funds), and profit amount.
uint128 public ending_totalReturn;
uint128 public ending_profitAmount;
// ------- Slot ------- //
// The mapping that contains TRUE for addresses that already claimed
// their lottery winner prizes.
// Used only in COMPLETION, on claimWinnerPrize(), to check if
// msg.sender has already claimed his prize.
mapping( address => bool ) public prizeClaimersAddresses;
// ============= Private/internal functions ============= //
// Pool Only modifier.
modifier poolOnly {
require( msg.sender == poolAddress );
_;
}
// Only randomness provider allowed modifier.
modifier randomnessProviderOnly {
require( msg.sender == randomnessProvider );
_;
}
// Execute function only on specific lottery stage.
modifier onlyOnStage( STAGE _stage )
{
require( lotteryStage == uint8( _stage ) );
_;
}
// Modifier for protecting the function from re-entrant calls,
// by using a locked Re-Entrancy Lock (Mutex).
modifier mutexLOCKED
{
require( ! reEntrancyMutexLocked );
reEntrancyMutexLocked = true;
_;
reEntrancyMutexLocked = false;
}
// Check if we're currently on a specific stage.
function onStage( STAGE _stage )
internal view
returns( bool )
{
return ( lotteryStage == uint8( _stage ) );
}
/**
* Check if token transfer to specific wallet won't exceed
* maximum token amount allowed to own by a single wallet.
*
* @return true, if holder's balance with "amount" added,
* would exceed the max allowed single holder's balance
* (by default, that is 5% of total supply).
*/
function transferExceedsMaxBalance(
address holder, uint amount )
internal view
returns( bool )
{
uint maxAllowedBalance =
( totalSupply() * cfg.maxAmountForWallet_percentageOfSupply ) /
( _100PERCENT );
return ( ( balanceOf( holder ) + amount ) > maxAllowedBalance );
}
/**
* Update holder data.
* This function is called by _transfer() function, just before
* transfering final amount of tokens directly from sender to
* receiver.
* At this point, all burns/mints have been done, and we're sure
* that this transfer is valid and must be successful.
*
* In all modes, this function is used to update the holder array.
*
* However, on external exchange modes (e.g. on Uniswap mode),
* it is also used to track buy/sell ether value, to update holder
* scores, when token buys/sells cannot be tracked directly.
*
* If, however, we use Standalone mode, we are the exchange,
* so on _transfer() we already know the ether value, which is
* set to currentBuySellEtherValue variable.
*
* @param amountSent - the token amount that is deducted from
* sender's balance. This includes burn, and owner fee.
*
* @param amountReceived - the token amount that receiver
* actually receives, after burns and fees.
*
* @return holderCountChanged - indicates whether holder count
* changes during this transfer - new holder joins or leaves
* (true), or no change occurs (false).
*/
function updateHolderData_preTransfer(
address sender,
address receiver,
uint256 amountSent,
uint256 amountReceived )
internal
returns( bool holderCountChanged )
{
// Update holder array, if new token holder joined, or if
// a holder transfered his whole balance.
holderCountChanged = false;
// Sender transferred his whole balance - no longer a holder.
if( balanceOf( sender ) == amountSent )
{
lotStorage.removeHolder( sender );
holderCountChanged = true;
}
// Receiver didn't have any tokens before - add it to holders.
if( balanceOf( receiver ) == 0 && amountReceived > 0 )
{
lotStorage.addHolder( receiver );
holderCountChanged = true;
}
// Update holder score factors: if buy/sell occured, update
// etherContributed and timeFactors scores,
// and also propagate the scores through the referral chain
// to the parent referrers (this is done in Storage contract).
// This lottery operates only on external exchange (Uniswap)
// mode, so we have to find out the buy/sell Ether value by
// calling the external exchange (Uniswap pair) contract.
// Temporary variable to store current transfer's buy/sell
// value in Ethers.
int buySellValue;
// Sender is an exchange - buy detected.
if( sender == exchangeAddress && receiver != exchangeAddress )
{
// Use the Router's functionality.
// Set the exchange path to WETH -> ULT
// (ULT is Lottery Token, and it's address is our address).
address[] memory path = new address[]( 2 );
path[ 0 ] = WETHaddress;
path[ 1 ] = address(this);
uint[] memory ethAmountIn = uniswapRouter.getAmountsIn(
amountSent, // uint amountOut,
path // address[] path
);
buySellValue = int( ethAmountIn[ 0 ] );
// Compute time factor value for the current ether value.
// buySellValue is POSITIVE.
// When computing Time Factors, leave only 6 ether decimals.
int timeFactorValue = ( buySellValue / (10 ** 12) ) *
int( (now - startDate) / cfg.timeFactorDivisor );
// Update and propagate the buyer (receiver) scores.
lotStorage.updateAndPropagateScoreChanges(
receiver,
int80( buySellValue ),
int80( timeFactorValue ),
int80( amountReceived ) );
}
// Receiver is an exchange - sell detected.
else if( sender != exchangeAddress && receiver == exchangeAddress )
{
// Use the Router's functionality.
// Set the exchange path to ULT -> WETH
// (ULT is Lottery Token, and it's address is our address).
address[] memory path = new address[]( 2 );
path[ 0 ] = address(this);
path[ 1 ] = WETHaddress;
uint[] memory ethAmountOut = uniswapRouter.getAmountsOut(
amountReceived, // uint amountIn
path // address[] path
);
// It's a sell (ULT -> WETH), so set value to NEGATIVE.
buySellValue = int( -1 ) * int( ethAmountOut[ 1 ] );
// Compute time factor value for the current ether value.
// buySellValue is NEGATIVE.
int timeFactorValue = ( buySellValue / (10 ** 12) ) *
int( (now - startDate) / cfg.timeFactorDivisor );
// Update and propagate the seller (sender) scores.
lotStorage.updateAndPropagateScoreChanges(
sender,
int80( buySellValue ),
int80( timeFactorValue ),
-1 * int80( amountSent ) );
}
// Neither Sender nor Receiver are exchanges - default transfer.
// Tokens just got transfered between wallets, without
// exchanging for ETH - so etherContributed_change = 0.
// On this case, update both sender's & receiver's scores.
//
else {
buySellValue = 0;
lotStorage.updateAndPropagateScoreChanges( sender, 0, 0,
-1 * int80( amountSent ) );
lotStorage.updateAndPropagateScoreChanges( receiver, 0, 0,
int80( amountReceived ) );
}
// Check if lottery liquidity pool funds have already
// reached a minimum required ETH value.
uint ethFunds = getCurrentEthFunds();
if( !fundGainRequirementReached &&
ethFunds >= cfg.fundRequirement_denySells )
{
fundGainRequirementReached = true;
}
// Check whether this token transfer is allowed if it's a sell
// (if buySellValue is negative):
//
// If we've already reached the minimum fund gain requirement,
// and this sell would shrink lottery liquidity pool's ETH funds
// below this requirement, then deny this sell, causing this
// transaction to fail.
if( fundGainRequirementReached &&
buySellValue < 0 &&
( uint( -1 * buySellValue ) >= ethFunds ||
ethFunds - uint( -1 * buySellValue ) <
cfg.fundRequirement_denySells ) )
{
require( false );
}
}
/**
* Check for finishing stage start conditions.
* - If some conditions are met, start finishing stage!
* Do it by setting "onFinishingStage" bool.
* - If we're currently on finishing stage, and some condition
* is no longer met, then stop the finishing stage.
*/
function checkFinishingStageConditions()
internal
{
// Firstly, check if lottery hasn't exceeded it's maximum lifetime.
// If so, don't check anymore, just set finishing stage, and
// end the lottery on further call of checkForEnding().
if( (now - startDate) > cfg.maxLifetime )
{
lotteryStage = uint8( STAGE.FINISHING );
return;
}
// Compute & check the finishing criteria.
// Notice that we adjust the config-specified fund gain
// percentage increase to uint-mode, by adding 100 percents,
// because we don't deal with negative percentages, and here
// we represent loss as a percentage below 100%, and gains
// as percentage above 100%.
// So, if in regular gains notation, it's said 10% gain,
// in uint mode, it's said 110% relative increase.
//
// (Also, remember that losses are impossible in our lottery
// working scheme).
if( lotStorage.getHolderCount() >= cfg.finishCriteria_minNumberOfHolders
&&
getCurrentEthFunds() >= cfg.finishCriteria_minFunds
&&
(now - startDate) >= cfg.finishCriteria_minTimeActive )
{
if( onStage( STAGE.ACTIVE ) )
{
// All conditions are met - start the finishing stage.
lotteryStage = uint8( STAGE.FINISHING );
emit FinishingStageStarted();
}
}
else if( onStage( STAGE.FINISHING ) )
{
// However, what if some condition was not met, but we're
// already on the finishing stage?
// If so, we must stop the finishing stage.
// But what to do with the finishing probability?
// Config specifies if it should be reset or maintain it's
// value until the next time finishing stage is started.
lotteryStage = uint8( STAGE.ACTIVE );
if( cfg.finish_resetProbabilityOnStop )
finishProbablity = cfg.finish_initialProbability;
emit FinishingStageStopped();
}
}
/**
* We're currently on finishing stage - so let's check if
* we should end the lottery now!
*
* This function is called from _transfer(), only if we're sure
* that we're currently on finishing stage (onFinishingStage
* variable is set).
*
* Here, we compute the pseudo-random number from hash of
* current message's sender, now, and other values,
* and modulo it to the current finish probability.
* If it's equal to 1, then we end the lottery!
*
* Also, here we update the finish probability according to
* probability update criteria - holder count, and tx count.
*
* @param holderCountChanged - indicates whether Holder Count
* has changed during this transfer (new holder joined, or
* a holder sold all his tokens).
*/
function checkForEnding( bool holderCountChanged )
internal
{
// At first, check if lottery max lifetime is exceeded.
// If so, start ending procedures right now.
if( (now - startDate) > cfg.maxLifetime )
{
startEndingStage();
return;
}
// Now, we know that lottery lifetime is still OK, and we're
// currently on Finishing Stage (because this function is
// called only when onFinishingStage is set).
//
// Now, check if we should End the lottery, by computing
// a modulo on a pseudo-random number, which is a transfer
// hash, computed for every transfer on _transfer() function.
//
// Get the modulo amount according to current finish
// probability.
// We use precision of 0.01% - notice the "10000 *" before
// 100 PERCENT.
// Later, when modulo'ing, we'll check if value is below 10000.
//
uint prec = 10000;
uint modAmount = (prec * _100PERCENT) / finishProbablity;
if( ( transferHashValue % modAmount ) <= prec )
{
// Finish probability is met! Commence lottery end -
// start Ending Stage.
startEndingStage();
return;
}
// Finish probability wasn't met.
// Update the finish probability, by increasing it!
// Transaction count criteria.
// As we know that this function is called on every new
// transfer (transaction), we don't check if transactionCount
// increased or not - we just perform probability update.
finishProbablity += cfg.finish_probabilityIncreaseStep_transaction;
// Now, perform holder count criteria update.
// Finish probability increases, no matter if holder count
// increases or decreases.
if( holderCountChanged )
finishProbablity += cfg.finish_probabilityIncreaseStep_holder;
}
/**
* Start the Ending Stage, by De-Activating the lottery,
* to deny all further token transfers (excluding the one when
* removing liquidity from Uniswap), and transition into the
* Mining Phase - set the lotteryStage to MINING.
*/
function startEndingStage()
internal
{
lotteryStage = uint8( STAGE.ENDING_MINING );
}
/**
* Execute the first step of the Mining Stage - request a
* Random Seed from the Randomness Provider.
*
* Here, we call the Randomness Provider, asking for a true random seed
* to be passed to us into our callback, named
* "finish_randomnessProviderCallback()".
*
* When that callback will be called, our storage's random seed will
* be set, and we'll be able to start the Ending Algorithm on
* further mining steps.
*
* Notice that Randomness Provider must already be funded, to
* have enough Ether for Provable fee and the gas costs of our
* callback function, which are quite high, because of winner
* selection algorithm, which is computationally expensive.
*
* The Randomness Provider is always funded by the Pool,
* right before the Pool deploys and starts a new lottery, so
* as every lottery calls the Randomness Provider only once,
* the one-call-fund method for every lottery is sufficient.
*
* Also notice, that Randomness Provider might fail to call
* our callback due to some unknown reasons!
* Then, the lottery profits could stay locked in this
* lottery contract forever ?!!
*
* No! We've thought about that - we've implemented the
* Alternative Ending mechanism, where, if specific time passes
* after we've made a request to Randomness Provider, and
* callback hasn't been called yet, we allow external actor to
* execute the Alternative ending, which basically does the
* same things as the default ending, just that the Random Seed
* will be computed locally in our contract, using the
* Pseudo-Random mechanism, which could compute a reasonably
* fair and safe value using data from holder array, and other
* values, described in more detail on corresponding function's
* description.
*/
function mine_requestRandomSeed()
internal
{
// We're sure that the Randomness Provider has enough funds.
// Execute the random request, and get ready for Ending Algorithm.
IRandomnessProvider( randomnessProvider )
.requestRandomSeedForLotteryFinish();
// Store the time when random seed has been requested, to
// be able to alternatively handle the lottery finish, if
// randomness provider doesn't call our callback for some
// reason.
finish_timeRandomSeedRequested = uint32( now );
// Emit appropriate events.
emit RandomnessProviderCalled();
}
/** PAYABLE [ OUT ] >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
*
* Transfer the Owner & Pool profit shares, when lottery ends.
* This function is the first one that's executed on the Mining
* Stage.
* This is the first step of Mining. So, the Miner who executes this
* function gets the mining reward.
*
* This function's job is to Gather the Profits & Initial Funds,
* and Transfer them to Profiters - that is, to The Pool, and
* to The Owner.
*
* The Miners' profit share and Winner Prize Fund stay in this
* contract.
*
* On this function, we (in this order):
*
* 1. Remove all liquidity from Uniswap (if using Uniswap Mode),
* pulling it to our contract's wallet.
*
* 2. Transfer the Owner and the Pool ETH profit shares to
* Owner and Pool addresses.
*
* * This function transfers Ether out of our contract:
* - We transfer the Profits to Pool and Owner addresses.
*/
function mine_removeUniswapLiquidityAndTransferProfits()
internal
mutexLOCKED
{
// We've already approved our token allowance to Router.
// Now, approve Uniswap liquidity token's Router allowance.
ERC20( exchangeAddress ).approve( address(uniswapRouter), uint(-1) );
// Enable the SPECIAL-TRANSFER mode, to allow Uniswap to transfer
// the tokens from Pair to Router, and then from Router to us.
specialTransferModeEnabled = true;
// Remove liquidity!
uint amountETH = uniswapRouter
.removeLiquidityETHSupportingFeeOnTransferTokens(
address(this), // address token,
ERC20( exchangeAddress ).balanceOf( address(this) ),
0, // uint amountTokenMin,
0, // uint amountETHMin,
address(this), // address to,
(now + 10000000) // uint deadline
);
// Tokens are transfered. Disable the special transfer mode.
specialTransferModeEnabled = false;
// Check that we've got a correct amount of ETH.
require( address(this).balance >= amountETH &&
address(this).balance >= cfg.initialFunds );
// Compute the Profit Amount (current balance - initial funds).
ending_totalReturn = uint128( address(this).balance );
ending_profitAmount = ending_totalReturn - uint128( cfg.initialFunds );
// Compute, and Transfer Owner's profit share and
// Pool's profit share to their respective addresses.
uint poolShare = ( ending_profitAmount * cfg.poolProfitShare ) /
( _100PERCENT );
uint ownerShare = ( ending_profitAmount * cfg.ownerProfitShare ) /
( _100PERCENT );
// To pool, transfer it's profit share plus initial funds.
IUniLotteryPool( poolAddress ).lotteryFinish
{ value: poolShare + cfg.initialFunds }
( ending_totalReturn, ending_profitAmount );
// Transfer Owner's profit share.
OWNER_ADDRESS.transfer( ownerShare );
// Emit ending event.
emit LotteryEnd( ending_totalReturn, ending_profitAmount );
}
/**
* Executes a single step of the Winner Selection Algorithm
* (the Ending Algorithm).
* The algorithm itself is being executed in the Storage contract.
*
* On current design, whole algorithm is executed in a single step.
*
* This function is executed only in the Mining stage, and
* accounts for most of the gas spent during mining.
*/
function mine_executeEndingAlgorithmStep()
internal
{
// Launch the winner algorithm, to execute the next step.
lotStorage.executeWinnerSelectionAlgorithm();
}
// =============== Public functions =============== //
/**
* Constructor of this delegate code contract.
* Here, we set OUR STORAGE's lotteryStage to DISABLED, because
* we don't want anybody to call this contract directly.
*/
constructor() public
{
lotteryStage = uint8( STAGE.DISABLED );
}
/**
* Construct the lottery contract which is delegating it's
* call to us.
*
* @param config - LotteryConfig structure to use in this lottery.
*
* Future approach: ABI-encoded Lottery Config
* (different implementations might use different config
* structures, which are ABI-decoded inside the implementation).
*
* Also, this "config" includes the ABI-encoded temporary values,
* which are not part of persisted LotteryConfig, but should
* be used only in constructor - for example, values to be
* assigned to storage variables, such as ERC20 token's
* name, symbol, and decimals.
*
* @param _poolAddress - Address of the Main UniLottery Pool, which
* provides initial funds, and receives it's profit share.
*
* @param _randomProviderAddress - Address of a Randomness Provider,
* to use for obtaining random seeds.
*
* @param _storageAddress - Address of a Lottery Storage.
* Storage contract is a separate contract which holds all
* lottery token holder data, such as intermediate scores.
*
*/
function construct(
LotteryConfig memory config,
address payable _poolAddress,
address _randomProviderAddress,
address _storageAddress )
external
{
// Check if contract wasn't already constructed!
require( poolAddress == address( 0 ) );
// Set the Pool's Address - notice that it's not the
// msg.sender, because lotteries aren't created directly
// by the Pool, but by the Lottery Factory!
poolAddress = _poolAddress;
// Set the Randomness Provider address.
randomnessProvider = _randomProviderAddress;
// Check the minimum & maximum requirements for config
// profit & lifetime parameters.
require( config.maxLifetime <= MAX_LOTTERY_LIFETIME );
require( config.poolProfitShare >= MIN_POOL_PROFITS &&
config.poolProfitShare <= MAX_POOL_PROFITS );
require( config.ownerProfitShare >= MIN_OWNER_PROFITS &&
config.ownerProfitShare <= MAX_OWNER_PROFITS );
require( config.minerProfitShare >= MIN_MINER_PROFITS &&
config.minerProfitShare <= MAX_MINER_PROFITS );
// Check if winner profit share is good.
uint32 totalWinnerShare =
(_100PERCENT) - config.poolProfitShare
- config.ownerProfitShare
- config.minerProfitShare;
require( totalWinnerShare >= MIN_WINNER_PROFIT_SHARE );
// Check if ending algorithm params are good.
require( config.randRatio_scorePart != 0 &&
config.randRatio_randPart != 0 &&
( config.randRatio_scorePart +
config.randRatio_randPart ) < 10000 );
require( config.endingAlgoType ==
uint8( EndingAlgoType.MinedWinnerSelection ) ||
config.endingAlgoType ==
uint8( EndingAlgoType.WinnerSelfValidation ) ||
config.endingAlgoType ==
uint8( EndingAlgoType.RolledRandomness ) );
// Set the number of winners (winner count).
// If using Computed Sequence winner prize shares, set that
// value, and if it's zero, then we're using the Array-Mode
// prize share specification.
if( config.prizeSequence_winnerCount == 0 &&
config.winnerProfitShares.length != 0 )
config.prizeSequence_winnerCount =
uint16( config.winnerProfitShares.length );
// Setup our Lottery Storage - initialize, and set the
// Algorithm Config.
LotteryStorage _lotStorage = LotteryStorage( _storageAddress );
// Setup a Winner Score Config for the winner selection algo,
// to be used in the Lottery Storage.
LotteryStorage.WinnerAlgorithmConfig memory winnerConfig;
// Algorithm type.
winnerConfig.endingAlgoType = config.endingAlgoType;
// Individual player max score parts.
winnerConfig.maxPlayerScore_etherContributed =
config.maxPlayerScore_etherContributed;
winnerConfig.maxPlayerScore_tokenHoldingAmount =
config.maxPlayerScore_tokenHoldingAmount;
winnerConfig.maxPlayerScore_timeFactor =
config.maxPlayerScore_timeFactor;
winnerConfig.maxPlayerScore_refferalBonus =
config.maxPlayerScore_refferalBonus;
// Score-To-Random ratio parts.
winnerConfig.randRatio_scorePart = config.randRatio_scorePart;
winnerConfig.randRatio_randPart = config.randRatio_randPart;
// Set winner count (no.of winners).
winnerConfig.winnerCount = config.prizeSequence_winnerCount;
// Initialize the storage (bind it to our contract).
_lotStorage.initialize( winnerConfig );
// Set our immutable variable.
lotStorage = _lotStorage;
// Now, set our config to the passed config.
cfg = config;
// Might be un-needed (can be replaced by Constant on the MainNet):
WETHaddress = uniswapRouter.WETH();
}
/** PAYABLE [ IN ] <<<<<<<<<<<<<<<<<<<<<<<<<<<<
*
* Fallback Receive Ether function.
* Used to receive ETH funds back from Uniswap, on lottery's end,
* when removing liquidity.
*/
receive() external payable
{
emit FallbackEtherReceiver( msg.sender, msg.value );
}
/** PAYABLE [ IN ] <<<<<<<<<<<<<<<<<<<<<<<<<<<<
* PAYABLE [ OUT ] >>>>>>>>>>>>>>>>>>>>>>>>>>>>
*
* Initialization function.
* Here, the most important startup operations are made -
* such as minting initial token supply and transfering it to
* the Uniswap liquidity pair, in exchange for UNI-v2 tokens.
*
* This function is called by the pool, when transfering
* initial funds to this contract.
*
* What's payable?
* - Pool transfers initial funds to our contract.
* - We transfer that initial fund Ether to Uniswap liquidity pair
* when creating/providing it.
*/
function initialize()
external
payable
poolOnly
mutexLOCKED
onlyOnStage( STAGE.INITIAL )
{
// Check if pool transfered correct amount of funds.
require( address( this ).balance == cfg.initialFunds );
// Set start date.
startDate = uint32( now );
// Set the initial transfer hash value.
transferHashValue = uint( keccak256(
abi.encodePacked( msg.sender, now ) ) );
// Set initial finish probability, to be used when finishing
// stage starts.
finishProbablity = cfg.finish_initialProbability;
// ===== Active operations - mint & distribute! ===== //
// Mint full initial supply of tokens to our contract address!
_mint( address(this),
uint( cfg.initialTokenSupply ) * (10 ** decimals) );
// Now - prepare to create a new Uniswap Liquidity Pair,
// with whole our total token supply and initial funds ETH
// as the two liquidity reserves.
// Approve Uniswap Router to allow it to spend our tokens.
// Set maximum amount available.
_approve( address(this), address( uniswapRouter ), uint(-1) );
// Provide liquidity - the Router will automatically
// create a new Pair.
uniswapRouter.addLiquidityETH
{ value: address(this).balance }
(
address(this), // address token,
totalSupply(), // uint amountTokenDesired,
totalSupply(), // uint amountTokenMin,
address(this).balance, // uint amountETHMin,
address(this), // address to,
(now + 1000) // uint deadline
);
// Get the Pair address - that will be the exchange address.
exchangeAddress = IUniswapFactory( uniswapRouter.factory() )
.getPair( WETHaddress, address(this) );
// We assume that the token reserves of the pair are good,
// and that we own the full amount of liquidity tokens.
// Find out which of the pair tokens is WETH - is it the
// first or second one. Use it later, when getting our share.
if( IUniswapPair( exchangeAddress ).token0() == WETHaddress )
uniswap_ethFirst = true;
else
uniswap_ethFirst = false;
// Move to ACTIVE lottery stage.
// Now, all token transfers will be allowed.
lotteryStage = uint8( STAGE.ACTIVE );
// Lottery is initialized. We're ready to emit event.
emit LotteryInitialized();
}
// Return this lottery's initial funds, as were specified in the config.
//
function getInitialFunds() external view
returns( uint )
{
return cfg.initialFunds;
}
// Return active (still not returned to pool) initial fund value.
// If no-longer-active, return 0 (default) - because funds were
// already returned back to the pool.
//
function getActiveInitialFunds() external view
returns( uint )
{
if( onStage( STAGE.ACTIVE ) )
return cfg.initialFunds;
return 0;
}
/**
* Get current Exchange's Token and ETH reserves.
* We're on Uniswap mode, so get reserves from Uniswap.
*/
function getReserves()
external view
returns( uint _ethReserve, uint _tokenReserve )
{
// Use data from Uniswap pair contract.
( uint112 res0, uint112 res1, ) =
IUniswapPair( exchangeAddress ).getReserves();
if( uniswap_ethFirst )
return ( res0, res1 );
else
return ( res1, res0 );
}
/**
* Get our share (ETH amount) of the Uniswap Pair ETH reserve,
* of our Lottery tokens ULT-WETH liquidity pair.
*/
function getCurrentEthFunds()
public view
returns( uint ethAmount )
{
IUniswapPair pair = IUniswapPair( exchangeAddress );
( uint112 res0, uint112 res1, ) = pair.getReserves();
uint resEth = uint( uniswap_ethFirst ? res0 : res1 );
// Compute our amount of the ETH reserve, based on our
// percentage of our liquidity token balance to total supply.
uint liqTokenPercentage =
( pair.balanceOf( address(this) ) * (_100PERCENT) ) /
( pair.totalSupply() );
// Compute and return the ETH reserve.
return ( resEth * liqTokenPercentage ) / (_100PERCENT);
}
/**
* Get current finish probability.
* If it's ACTIVE stage, return 0 automatically.
*/
function getFinishProbability()
external view
returns( uint32 )
{
if( onStage( STAGE.FINISHING ) )
return finishProbablity;
return 0;
}
/**
* Generate a referral ID for msg.sender, who must be a token holder.
* Referral ID is used to refer other wallets into playing our
* lottery.
* - Referrer gets bonus points for every wallet that bought
* lottery tokens and specified his referral ID.
* - Referrees (wallets who got referred by registering a valid
* referral ID, corresponding to some referrer), get some
* bonus points for specifying (registering) a referral ID.
*
* Referral ID is a uint256 number, which is generated by
* keccak256'ing the holder's address, holder's current
* token ballance, and current time.
*/
function generateReferralID()
external
onlyOnStage( STAGE.ACTIVE )
{
uint256 refID = lotStorage.generateReferralID( msg.sender );
// Emit approppriate events.
emit ReferralIDGenerated( msg.sender, refID );
}
/**
* Register a referral for a msg.sender (must be token holder),
* using a valid referral ID got from a referrer.
* This function is called by a referree, who obtained a
* valid referral ID from some referrer, who previously
* generated it using generateReferralID().
*
* You can only register a referral once!
* When you do so, you get bonus referral points!
*/
function registerReferral(
uint256 referralID )
external
onlyOnStage( STAGE.ACTIVE )
{
address referrer = lotStorage.registerReferral(
msg.sender,
cfg.playerScore_referralRegisteringBonus,
referralID );
// Emit approppriate events.
emit ReferralRegistered( msg.sender, referrer, referralID );
}
/**
* The most important function of this contract - Transfer Function.
*
* Here, all token burning, intermediate score tracking, and
* finish condition checking is performed, according to the
* properties specified in config.
*/
function _transfer( address sender,
address receiver,
uint256 amount )
internal
override
{
// Check if transfers are allowed in current state.
// On Non-Active stage, transfers are allowed only from/to
// our contract.
// As we don't have Standalone Mode on this lottery variation,
// that means that tokens to/from our contract are travelling
// only when we transfer them to Uniswap Pair, and when
// Uniswap transfers them back to us, on liquidity remove.
//
// On this state, we also don't perform any burns nor
// holding trackings - just transfer and return.
if( !onStage( STAGE.ACTIVE ) &&
!onStage( STAGE.FINISHING ) &&
( sender == address(this) || receiver == address(this) ||
specialTransferModeEnabled ) )
{
super._transfer( sender, receiver, amount );
return;
}
// Now, we know that we're NOT on special mode.
// Perform standard checks & brecks.
require( ( onStage( STAGE.ACTIVE ) ||
onStage( STAGE.FINISHING ) ) );
// Can't transfer zero tokens, or use address(0) as sender.
require( amount != 0 && sender != address(0) );
// Compute the Burn Amount - if buying tokens from an exchange,
// we use a lower burn rate - to incentivize buying!
// Otherwise (if selling or just transfering between wallets),
// we use a higher burn rate.
uint burnAmount;
// It's a buy - sender is an exchange.
if( sender == exchangeAddress )
burnAmount = ( amount * cfg.burn_buyerRate ) / (_100PERCENT);
else
burnAmount = ( amount * cfg.burn_defaultRate ) / (_100PERCENT);
// Now, compute the final amount to be gotten by the receiver.
uint finalAmount = amount - burnAmount;
// Check if receiver's balance won't exceed the max-allowed!
// Receiver must not be an exchange.
if( receiver != exchangeAddress )
{
require( !transferExceedsMaxBalance( receiver, finalAmount ) );
}
// Now, update holder data array accordingly.
bool holderCountChanged = updateHolderData_preTransfer(
sender,
receiver,
amount, // Amount Sent (Pre-Fees)
finalAmount // Amount Received (Post-Fees).
);
// All is ok - perform the burn and token transfers now.
// Burn token amount from sender's balance.
super._burn( sender, burnAmount );
// Finally, transfer the final amount from sender to receiver.
super._transfer( sender, receiver, finalAmount );
// Compute new Pseudo-Random transfer hash, which must be
// computed for every transfer, and is used in the
// Finishing Stage as a pseudo-random unique value for
// every transfer, by which we determine whether lottery
// should end on this transfer.
//
// Compute it like this: keccak the last (current)
// transferHashValue, msg.sender, sender, receiver, amount.
transferHashValue = uint( keccak256( abi.encodePacked(
transferHashValue, msg.sender, sender, receiver, amount ) ) );
// Check if we should be starting a finishing stage now.
checkFinishingStageConditions();
// If we're on finishing stage, check for ending conditions.
// If ending check is satisfied, the checkForEnding() function
// starts ending operations.
if( onStage( STAGE.FINISHING ) )
checkForEnding( holderCountChanged );
}
/**
* Callback function, which is called from Randomness Provider,
* after it obtains a random seed to be passed to us, after
* we have initiated The Ending Stage, on which random seed
* is used to generate random factors for Winner Selection
* algorithm.
*/
function finish_randomnessProviderCallback(
uint256 randomSeed,
uint256 /*callID*/ )
external
randomnessProviderOnly
{
// Set the random seed in the Storage Contract.
lotStorage.setRandomSeed( randomSeed );
// If algo-type is not Mined Winner Selection, then by now
// we assume lottery as COMPL3T3D.
if( cfg.endingAlgoType != uint8(EndingAlgoType.MinedWinnerSelection) )
{
lotteryStage = uint8( STAGE.COMPLETION );
completionDate = uint32( now );
}
}
/**
* Function checks if we can initiate Alternative Seed generation.
*
* Alternative approach to Lottery Random Seed is used only when
* Randomness Provider doesn't work, and doesn't call the
* above callback.
*
* This alternative approach can be initiated by Miners, when
* these conditions are met:
* - Lottery is on Ending (Mining) stage.
* - Request to Randomness Provider was made at least X time ago,
* and our callback hasn't been called yet.
*
* If these conditions are met, we can initiate the Alternative
* Random Seed generation, which generates a seed based on our
* state.
*/
function alternativeSeedGenerationPossible()
internal view
returns( bool )
{
return ( onStage( STAGE.ENDING_MINING ) &&
( (now - finish_timeRandomSeedRequested) >
cfg.REQUIRED_TIME_WAITING_FOR_RANDOM_SEED ) );
}
/**
* Return this lottery's config, using ABIEncoderV2.
*/
/*function getLotteryConfig()
external view
returns( LotteryConfig memory ourConfig )
{
return cfg;
}*/
/**
* Checks if Mining is currently available.
*/
function isMiningAvailable()
external view
returns( bool )
{
return onStage( STAGE.ENDING_MINING ) &&
( miningStep == 0 ||
( miningStep == 1 &&
( lotStorage.getRandomSeed() != 0 ||
alternativeSeedGenerationPossible() )
) );
}
/** PAYABLE [ OUT ] >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
*
* Mining function, to be executed on Ending (Mining) stage.
*
* "Mining" approach is used in this lottery, to use external
* actors for executing the gas-expensive Ending Algorithm,
* and other ending operations, such as profit transfers.
*
* "Miners" can be any external actors who call this function.
* When Miner successfully completes a Mining Step, he gets
* a Mining Reward, which is a certain portion of lottery's profit
* share, dedicated to Miners.
*
* NOT-IMPLEMENTED APPROACH:
*
* All these operations are divided into "mining steps", which are
* smaller components, which fit into reasonable gas limits.
* All "steps" are designed to take up similar amount of gas.
*
* For example, if total lottery profits (total ETH got from
* pulling liquidity out of Uniswap, minus initial funds),
* is 100 ETH, Miner Profit Share is 10%, and there are 5 mining
* steps total, then for a singe step executed, miner will get:
*
* (100 * 0.1) / 5 = 2 ETH.
*
* ---------------------------------
*
* CURRENTLY IMPLEMENTED APPROACH:
*
* As the above-defined approach would consume very much gas for
* inter-step intermediate state storage, we have thought that
* for now, it's better to have only 2 mining steps, the second of
* which performs the whole Winner Selection Algorithm.
*
* This is because performing the whole algorithm at once would save
* us up to 10x more gas in total, than executing it in steps.
*
* However, this solution is not scalable, because algorithm has
* to fit into block gas limit (10,000,000 gas), so we are limited
* to a certain safe maximum number of token holders, which is
* empirically determined during testing, and defined in the
* MAX_SAFE_NUMBER_OF_HOLDERS constant, which is checked against the
* config value "finishCriteria_minNumberOfHolders" in constructor.
*
* So, in this approach, there are only 2 mining steps:
*
* 1. Remove liquidity from Uniswap, transfer profit shares to
* the Pool and the Owner Address, and request Random Seed
* from the Randomness Provider.
* Reward: 25% of total Mining Rewards.
*
* 2. Perform the whole Winner Selection Algorithm inside the
* Lottery Storage contract.
* Reward: 75% of total Mining Rewards.
*
* * Function transfers Ether out of our contract:
* - Transfers the current miner's reward to msg.sender.
*/
function mine()
external
onlyOnStage( STAGE.ENDING_MINING )
{
uint currentStepReward;
// Perform different operations on different mining steps.
// Step 0: Remove liquidity from Uniswap, transfer profits to
// Pool and Owner addresses. Also, request a Random Seed
// from the Randomness Provider.
if( miningStep == 0 )
{
mine_requestRandomSeed();
mine_removeUniswapLiquidityAndTransferProfits();
// Compute total miner reward amount, then compute this
// step's reward later.
uint totalMinerRewards =
( ending_profitAmount * cfg.minerProfitShare ) /
( _100PERCENT );
// Step 0 reward is 10% for Algo type 1.
if( cfg.endingAlgoType == uint8(EndingAlgoType.MinedWinnerSelection) )
{
currentStepReward = ( totalMinerRewards * (10 * PERCENT) ) /
( _100PERCENT );
}
// If other algo-types, second step is not normally needed,
// so here we take 80% of miner rewards.
// If Randomness Provider won't give us a seed after
// specific amount of time, we'll initiate a second step,
// with remaining 20% of miner rewords.
else
{
currentStepReward = ( totalMinerRewards * (80 * PERCENT) ) /
( _100PERCENT );
}
require( currentStepReward <= totalMinerRewards );
}
// Step 1:
// If we use MinedWinnerSelection algo-type, then execute the
// winner selection algorithm.
// Otherwise, check if Random Provider hasn't given us a
// random seed long enough, so that we have to generate a
// seed locally.
else
{
// Check if we can go into this step when using specific
// ending algorithm types.
if( cfg.endingAlgoType != uint8(EndingAlgoType.MinedWinnerSelection) )
{
require( lotStorage.getRandomSeed() == 0 &&
alternativeSeedGenerationPossible() );
}
// Compute total miner reward amount, then compute this
// step's reward later.
uint totalMinerRewards =
( ending_profitAmount * cfg.minerProfitShare ) /
( _100PERCENT );
// Firstly, check if random seed is already obtained.
// If not, check if we should generate it locally.
if( lotStorage.getRandomSeed() == 0 )
{
if( alternativeSeedGenerationPossible() )
{
// Set random seed inside the Storage Contract,
// but using our contract's transferHashValue as the
// random seed.
// We believe that this hash has enough randomness
// to be considered a fairly good random seed,
// because it has beed chain-computed for every
// token transfer that has occured in ACTIVE stage.
//
lotStorage.setRandomSeed( transferHashValue );
// If using Non-Mined algorithm types, reward for this
// step is 20% of miner funds.
if( cfg.endingAlgoType !=
uint8(EndingAlgoType.MinedWinnerSelection) )
{
currentStepReward =
( totalMinerRewards * (20 * PERCENT) ) /
( _100PERCENT );
}
}
else
{
// If alternative seed generation is not yet possible
// (not enough time passed since the rand.provider
// request was made), then mining is not available
// currently.
require( false );
}
}
// Now, we know that Random Seed is obtained.
// If we use this algo-type, perform the actual
// winner selection algorithm.
if( cfg.endingAlgoType == uint8(EndingAlgoType.MinedWinnerSelection) )
{
mine_executeEndingAlgorithmStep();
// Set the prize amount to SECOND STEP prize amount (90%).
currentStepReward = ( totalMinerRewards * (90 * PERCENT) ) /
( _100PERCENT );
}
// Now we've completed both Mining Steps, it means MINING stage
// is finally completed!
// Transition to COMPLETION stage, and set lottery completion
// time to NOW.
lotteryStage = uint8( STAGE.COMPLETION );
completionDate = uint32( now );
require( currentStepReward <= totalMinerRewards );
}
// Now, transfer the reward to miner!
// Check for bugs too - if the computed amount doesn't exceed.
// Increment the mining step - move to next step (if there is one).
miningStep++;
// Check & Lock the Re-Entrancy Lock for transfers.
require( ! reEntrancyMutexLocked );
reEntrancyMutexLocked = true;
// Finally, transfer the reward to message sender!
msg.sender.transfer( currentStepReward );
// UnLock ReEntrancy Lock.
reEntrancyMutexLocked = false;
}
/**
* Function computes winner prize amount for winner at rank #N.
* Prerequisites: Must be called only on STAGE.COMPLETION stage,
* because we use the final profits amount here, and that value
* (ending_profitAmount) is known only on COMPLETION stage.
*
* @param rankingPosition - ranking position of a winner.
* @return finalPrizeAmount - prize amount, in Wei, of this winner.
*/
function getWinnerPrizeAmount(
uint rankingPosition )
public view
returns( uint finalPrizeAmount )
{
// Calculate total winner prize fund profit percentage & amount.
uint winnerProfitPercentage =
(_100PERCENT) - cfg.poolProfitShare -
cfg.ownerProfitShare - cfg.minerProfitShare;
uint totalPrizeAmount =
( ending_profitAmount * winnerProfitPercentage ) /
( _100PERCENT );
// We compute the prize amounts differently for the algo-type
// RolledRandomness, because distribution of these prizes is
// non-deterministic - multiple holders could fall onto the
// same ranking position, due to randomness of rolled score.
//
if( cfg.endingAlgoType == uint8(EndingAlgoType.RolledRandomness) )
{
// Here, we'll use Prize Sequence Factor approach differently.
// We'll use the prizeSequenceFactor value not to compute
// a geometric progression, but to compute an arithmetic
// progression, where each ranking position will get a
// prize equal to
// "totalPrizeAmount - rankingPosition * singleWinnerShare"
//
// singleWinnerShare is computed as a value corresponding
// to single-winner's share of total prize amount.
//
// Using such an approach, winner at rank 0 would get a
// prize equal to whole totalPrizeAmount, but, as the
// scores are rolled using random factor, it's very unlikely
// to get a such high score, so most likely such prize
// won't ever be claimed, but it is a possibility.
//
// Most of the winners in this approach are likely to
// roll scores in the middle, so would get prizes equal to
// 1-10% of total prize funds.
uint singleWinnerShare = totalPrizeAmount /
cfg.prizeSequence_winnerCount;
return totalPrizeAmount - rankingPosition * singleWinnerShare;
}
// Now, we know that ending algorithm is normal (deterministic).
// So, compute the prizes in a standard way.
// If using Computed Sequence: loop for "rankingPosition"
// iterations, while computing the prize shares.
// If "rankingPosition" is larger than sequencedWinnerCount,
// then compute the prize from sequence-leftover amount.
if( cfg.prizeSequenceFactor != 0 )
{
require( rankingPosition < cfg.prizeSequence_winnerCount );
// Leftover: If prizeSequenceFactor is 25%, it's 75%.
uint leftoverPercentage =
(_100PERCENT) - cfg.prizeSequenceFactor;
// Loop until the needed iteration.
uint loopCount = (
rankingPosition >= cfg.prizeSequence_sequencedWinnerCount ?
cfg.prizeSequence_sequencedWinnerCount :
rankingPosition
);
for( uint i = 0; i < loopCount; i++ )
{
totalPrizeAmount =
( totalPrizeAmount * leftoverPercentage ) /
( _100PERCENT );
}
// Get end prize amount - sequenced, or leftover.
// Leftover-mode.
if( loopCount == cfg.prizeSequence_sequencedWinnerCount &&
cfg.prizeSequence_winnerCount >
cfg.prizeSequence_sequencedWinnerCount )
{
// Now, totalPrizeAmount equals all leftover-group winner
// prize funds.
// So, just divide it by number of leftover winners.
finalPrizeAmount =
( totalPrizeAmount ) /
( cfg.prizeSequence_winnerCount -
cfg.prizeSequence_sequencedWinnerCount );
}
// Sequenced-mode
else
{
finalPrizeAmount =
( totalPrizeAmount * cfg.prizeSequenceFactor ) /
( _100PERCENT );
}
}
// Else, if we're using Pre-Specified Array of winner profit
// shares, just get the share at the corresponding index.
else
{
require( rankingPosition < cfg.winnerProfitShares.length );
finalPrizeAmount =
( totalPrizeAmount *
cfg.winnerProfitShares[ rankingPosition ] ) /
( _100PERCENT );
}
}
/**
* After lottery has completed, this function returns if msg.sender
* is one of lottery winners, and the position in winner rankings.
*
* Function must be used to obtain the ranking position before
* calling claimWinnerPrize().
*
* @param addr - address whose status to check.
*/
function getWinnerStatus( address addr )
external view
returns( bool isWinner, uint32 rankingPosition,
uint prizeAmount )
{
if( !onStage( STAGE.COMPLETION ) || balanceOf( addr ) == 0 )
return (false , 0, 0);
( isWinner, rankingPosition ) =
lotStorage.getWinnerStatus( addr );
if( isWinner )
{
prizeAmount = getWinnerPrizeAmount( rankingPosition );
if( prizeAmount > address(this).balance )
prizeAmount = address(this).balance;
}
}
/**
* Compute the intermediate Active Stage player score.
* This score is Player Score, not randomized.
* @param addr - address to check.
*/
function getPlayerIntermediateScore( address addr )
external view
returns( uint )
{
return lotStorage.getPlayerActiveStageScore( addr );
}
/** PAYABLE [ OUT ] >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
*
* Claim the winner prize of msg.sender, if he is one of the winners.
*
* This function must be provided a ranking position of msg.sender,
* which must be obtained using the function above.
*
* The Lottery Storage then just checks if holder address in the
* winner array element at position rankingPosition is the same
* as msg.sender's.
*
* If so, then claim request is valid, and we can give the appropriate
* prize to that winner.
* Prize can be determined by a computed factor-based sequence, or
* from the pre-specified winner array.
*
* * This function transfers Ether out of our contract:
* - Sends the corresponding winner prize to the msg.sender.
*
* @param rankingPosition - the position of Winner Array, that
* msg.sender says he is in (obtained using getWinnerStatus).
*/
function claimWinnerPrize(
uint32 rankingPosition )
external
onlyOnStage( STAGE.COMPLETION )
mutexLOCKED
{
// Check if msg.sender hasn't already claimed his prize.
require( ! prizeClaimersAddresses[ msg.sender ] );
// msg.sender must have at least some of UniLottery Tokens.
require( balanceOf( msg.sender ) != 0 );
// Check if there are any prize funds left yet.
require( address(this).balance != 0 );
// If using Mined Selection Algo, check if msg.sender is
// really on that ranking position - algo was already executed.
if( cfg.endingAlgoType == uint8(EndingAlgoType.MinedWinnerSelection) )
{
require( lotStorage.minedSelection_isAddressOnWinnerPosition(
msg.sender, rankingPosition ) );
}
// For other algorithms, get ranking position by executing
// a specific algorithm of that algo-type.
else
{
bool isWinner;
( isWinner, rankingPosition ) =
lotStorage.getWinnerStatus( msg.sender );
require( isWinner );
}
// Compute the prize amount, using our internal function.
uint finalPrizeAmount = getWinnerPrizeAmount( rankingPosition );
// If prize is small and computation precision errors occured,
// leading it to be larger than our balance, fix it.
if( finalPrizeAmount > address(this).balance )
finalPrizeAmount = address(this).balance;
// Transfer the Winning Prize to msg.sender!
msg.sender.transfer( finalPrizeAmount );
// Mark msg.sender as already claimed his prize.
prizeClaimersAddresses[ msg.sender ] = true;
}
/** PAYABLE [ OUT ] >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
*
* Transfer the leftover Winner Prize Funds of this contract to the
* Main UniLottery Pool, if prize claim deadline has been exceeded.
*
* Function can only be called from the Main Pool, and if some
* winners haven't managed to claim their prizes on time, their
* prizes will go back to UniLottery Pool.
*
* * Function transfers Ether out of our contract:
* - Transfer the leftover funds to the Pool (msg.sender).
*/
function getUnclaimedPrizes()
external
poolOnly
onlyOnStage( STAGE.COMPLETION )
mutexLOCKED
{
// Check if prize claim deadline has passed.
require( completionDate != 0 &&
( now - completionDate ) > cfg.prizeClaimTime );
// Just transfer it all to the Pool.
poolAddress.transfer( address(this).balance );
}
}
|
Copy the Winner Algo Config into memory, to avoid using 400-gas costing SLOAD every time we need to load something. Check if holderAddr is a holder at all! Compute the precision-adjusted constant ratio of referralBonus max score to the player individual max scores. Max available player score. Fix Min-Max scores, to avoid division by zero, if min == max. If min == max, make the difference equal to 1. Now, add bonus score, and compute total player's score: Bonus part, individual score part, and referree score part. Check if total player score <= 0. If so, make it equal to 1, because otherwise randomization won't be possible. Now, check if it's not more than max! If so, lowerify. This could have happen'd because of bonus. Return the score!
|
function getPlayerActiveStageScore( address holderAddr )
external view
returns( uint playerScore )
{
WinnerAlgorithmConfig memory cfg = algConfig;
if( holders[ holderIndexes[ holderAddr ] ] != holderAddr )
return 0;
int individualToReferralRatio =
( PRECISION * cfg.maxPlayerScore_refferalBonus ) /
( int( cfg.maxPlayerScore_etherContributed ) +
int( cfg.maxPlayerScore_timeFactor ) +
int( cfg.maxPlayerScore_tokenHoldingAmount ) );
int maxAvailablePlayerScore = int(
cfg.maxPlayerScore_etherContributed +
cfg.maxPlayerScore_timeFactor +
cfg.maxPlayerScore_tokenHoldingAmount +
cfg.maxPlayerScore_refferalBonus );
MinMaxHolderScores memory minMaxCpy = minMaxScores;
if( minMaxCpy.holderScore_etherContributed_min ==
minMaxCpy.holderScore_etherContributed_max )
minMaxCpy.holderScore_etherContributed_max =
minMaxCpy.holderScore_etherContributed_min + 1;
if( minMaxCpy.holderScore_timeFactors_min ==
minMaxCpy.holderScore_timeFactors_max )
minMaxCpy.holderScore_timeFactors_max =
minMaxCpy.holderScore_timeFactors_min + 1;
if( minMaxCpy.holderScore_tokenBalance_min ==
minMaxCpy.holderScore_tokenBalance_max )
minMaxCpy.holderScore_tokenBalance_max =
minMaxCpy.holderScore_tokenBalance_min + 1;
int totalPlayerScore =
holderData[ holderAddr ].bonusScore
+
computeHolderIndividualScores(
cfg, minMaxCpy, holderData[ holderAddr ] )
+
computeReferreeScoresForHolder(
individualToReferralRatio, cfg,
minMaxCpy, holderData[ holderAddr ] );
if( totalPlayerScore <= 0 )
totalPlayerScore = 1;
if( totalPlayerScore > maxAvailablePlayerScore )
totalPlayerScore = maxAvailablePlayerScore;
return uint( totalPlayerScore );
}
| 7,489,618 |
// SPDX-License-Identifier: MIT
// File: @openzeppelin/contracts/access/IAccessControl.sol
pragma solidity ^0.8.0;
interface IAccessControl {
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
function hasRole(bytes32 role, address account) external view returns (bool);
function getRoleAdmin(bytes32 role) external view returns (bytes32);
function grantRole(bytes32 role, address account) external;
function revokeRole(bytes32 role, address account) external;
function renounceRole(bytes32 role, address account) external;
}
// File: @openzeppelin/contracts/utils/Context.sol
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File: @openzeppelin/contracts/utils/Strings.sol
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
function toString(uint256 value) internal pure returns (string memory) {
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);
}
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);
}
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol
interface IERC165 {
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: @openzeppelin/contracts/utils/introspection/ERC165.sol
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// File: @openzeppelin/contracts/access/AccessControl.sol
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(uint160(account), 20),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)
)
);
}
}
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
function _grantRole(bytes32 role, address account) private {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() {
_setOwner(_msgSender());
}
function owner() public view virtual returns (address) {
return _owner;
}
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File: @openzeppelin/contracts/security/Pausable.sol
abstract contract Pausable is Context {
event Paused(address account);
event Unpaused(address account);
bool private _paused;
constructor() {
_paused = false;
}
function paused() public view virtual returns (bool) {
return _paused;
}
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// File: @openzeppelin/contracts/security/ReentrancyGuard.sol
abstract contract ReentrancyGuard {
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
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;
_;
_status = _NOT_ENTERED;
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol
interface IERC20Metadata is IERC20 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
}
// File: contracts/libraries/ERC20.sol
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;
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
function name() public view virtual override returns (string memory) {
return _name;
}
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
function decimals() public view virtual override returns (uint8) {
return 18;
}
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
_approve(sender, _msgSender(), currentAllowance - amount);
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
return true;
}
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
_balances[sender] = senderBalance - amount;
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(sender, recipient, amount);
}
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);
}
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
_balances[account] = accountBalance - amount;
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
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);
}
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
// File: contracts/SoulPower.sol
contract SoulPower is ERC20('SoulPower', 'SOUL'), AccessControl {
address public supreme; // supreme divine
bytes32 public anunnaki; // admin role
bytes32 public thoth; // minter role
bytes32 public constant DOMAIN_TYPEHASH = // EIP-712 typehash for the contract's domain
keccak256('EIP712Domain(string name,uint chainId,address verifyingContract)');
bytes32 public constant DELEGATION_TYPEHASH = // EIP-712 typehash for the delegation struct used by the contract
keccak256('Delegation(address delegatee,uint nonce,uint expiry)');
// mappings for user accounts (address)
mapping(address => mapping(uint => Checkpoint)) public checkpoints; // vote checkpoints
mapping(address => uint) public numCheckpoints; // checkpoint count
mapping(address => uint) public nonces; // signing / validating states
mapping(address => address) internal _delegates; // each accounts' delegate
struct Checkpoint { // checkpoint for marking number of votes from a given timestamp
uint fromTime;
uint votes;
}
event NewSupreme(address supreme);
event Rethroned(bytes32 role, address oldAccount, address newAccount);
event DelegateChanged( // emitted when an account changes its delegate
address indexed delegator,
address indexed fromDelegate,
address indexed toDelegate
);
event DelegateVotesChanged( // emitted when a delegate account's vote balance changes
address indexed delegate,
uint previousBalance,
uint newBalance
);
// restricted to the house of the role passed as an object to obey
modifier obey(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
// channels the authority vested in anunnaki and thoth to the supreme
constructor() {
supreme = msg.sender; // WARNING: set to multi-sig when deploying
anunnaki = keccak256('anunnaki'); // alpha supreme
thoth = keccak256('thoth'); // god of wisdom and magic
_divinationRitual(DEFAULT_ADMIN_ROLE, DEFAULT_ADMIN_ROLE, supreme); // supreme as root admin
_divinationRitual(anunnaki, anunnaki, supreme); // anunnaki as admin of anunnaki
_divinationRitual(thoth, anunnaki, supreme); // anunnaki as admin of thoth
mint(supreme, 50_000_000 * 1e18); // mints initial supply of 50M
}
// solidifies roles (internal)
function _divinationRitual(bytes32 _role, bytes32 _adminRole, address _account) internal {
_setupRole(_role, _account);
_setRoleAdmin(_role, _adminRole);
}
// grants `role` to `newAccount` && renounces `role` from `oldAccount` (public role)
function rethroneRitual(bytes32 role, address oldAccount, address newAccount) public obey(role) {
require(oldAccount != newAccount, 'must be a new address');
grantRole(role, newAccount); // grants new account
renounceRole(role, oldAccount); // removes old account of role
emit Rethroned(role, oldAccount, newAccount);
}
// updates supreme address (public anunnaki)
function newSupreme(address _supreme) public obey(anunnaki) {
require(supreme != _supreme, 'make a change, be the change'); // prevents self-destruct
rethroneRitual(DEFAULT_ADMIN_ROLE, supreme, _supreme); // empowers new supreme
supreme = _supreme;
emit NewSupreme(supreme);
}
// checks whether sender has divine role (public view)
function hasDivineRole(bytes32 role) public view returns (bool) {
return hasRole(role, msg.sender);
}
// mints soul power as the house of thoth so wills (public thoth)
function mint(address _to, uint _amount) public obey(thoth) {
_mint(_to, _amount);
_moveDelegates(address(0), _delegates[_to], _amount);
}
// destroys `amount` tokens from the caller (public)
function burn(uint amount) public {
_burn(_msgSender(), amount);
_moveDelegates(_delegates[_msgSender()], address(0), amount);
}
// destroys `amount` tokens from the `account` (public)
function burnFrom(address account, uint amount) public {
uint currentAllowance = allowance(account, _msgSender());
require(currentAllowance >= amount, 'burn amount exceeds allowance');
_approve(account, _msgSender(), currentAllowance - amount);
_burn(account, amount);
_moveDelegates(_delegates[account], address(0), amount);
}
// returns the address delegated by a given delegator (external view)
function delegates(address delegator) external view returns (address) {
return _delegates[delegator];
}
// delegates to the `delegatee` (external)
function delegate(address delegatee) external {
return _delegate(msg.sender, delegatee);
}
// delegates votes from signatory to `delegatee` (external)
function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
) external {
bytes32 domainSeparator = keccak256(
abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this))
);
bytes32 structHash = keccak256(
abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry)
);
bytes32 digest = keccak256(
abi.encodePacked('\x19\x01', domainSeparator, structHash)
);
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), 'delegateBySig: invalid signature');
require(nonce == nonces[signatory]++, 'delegateBySig: invalid nonce');
require(block.timestamp <= expiry, 'delegateBySig: signature expired');
return _delegate(signatory, delegatee);
}
// returns current votes balance for `account` (external view)
function getCurrentVotes(address account) external view returns (uint) {
uint nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
// returns an account's prior vote count as of a given timestamp (external view)
function getPriorVotes(address account, uint blockTimestamp) external view returns (uint) {
require(blockTimestamp < block.timestamp, 'getPriorVotes: not yet determined');
uint nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) { return 0; }
// checks most recent balance
if (checkpoints[account][nCheckpoints - 1].fromTime <= blockTimestamp) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// checks implicit zero balance
if (checkpoints[account][0].fromTime > blockTimestamp) {
return 0;
}
uint lower = 0;
uint upper = nCheckpoints - 1;
while (upper > lower) {
uint center = upper - (upper - lower) / 2; // avoids overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromTime == blockTimestamp) {
return cp.votes;
} else if (cp.fromTime < blockTimestamp) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function safe256(uint n, string memory errorMessage) internal pure returns (uint) {
require(n < type(uint).max, errorMessage);
return uint(n);
}
function getChainId() internal view returns (uint) {
uint chainId;
assembly { chainId := chainid() }
return chainId;
}
function _delegate(address delegator, address delegatee) internal {
address currentDelegate = _delegates[delegator];
uint delegatorBalance = balanceOf(delegator); // balance of underlying SOUL (not scaled)
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _moveDelegates(address srcRep, address dstRep, uint amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
// decreases old representative
uint srcRepNum = numCheckpoints[srcRep];
uint srcRepOld = srcRepNum > 0
? checkpoints[srcRep][srcRepNum - 1].votes
: 0;
uint srcRepNew = srcRepOld - amount;
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
// increases new representative
uint dstRepNum = numCheckpoints[dstRep];
uint dstRepOld = dstRepNum > 0
? checkpoints[dstRep][dstRepNum - 1].votes
: 0;
uint dstRepNew = dstRepOld + amount;
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(
address delegatee,
uint nCheckpoints,
uint oldVotes,
uint newVotes
) internal {
uint blockTimestamp = safe256(block.timestamp, 'block timestamp exceeds 256 bits');
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromTime == blockTimestamp) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockTimestamp, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
}
// File: contracts/libraries/Operable.sol
abstract contract Operable is Context, Ownable {
address[] public operators;
mapping(address => bool) public operator;
event OperatorUpdated(address indexed operator, bool indexed access);
constructor () {
address msgSender = _msgSender();
operator[msgSender] = true;
operators.push(msgSender);
emit OperatorUpdated(msgSender, true);
}
modifier onlyOperator() {
address msgSender = _msgSender();
require(operator[msgSender], "Operator: caller is not an operator");
_;
}
function removeOperator(address removingOperator) public virtual onlyOperator {
require(operator[removingOperator], 'Operable: address is not an operator');
operator[removingOperator] = false;
for (uint8 i; i < operators.length; i++) {
if (operators[i] == removingOperator) {
operators[i] = operators[i+1];
operators.pop();
emit OperatorUpdated(removingOperator, false);
return;
}
}
}
function addOperator(address newOperator) public virtual onlyOperator {
require(newOperator != address(0), "Operable: new operator is the zero address");
require(!operator[newOperator], 'Operable: address is already an operator');
operator[newOperator] = true;
operators.push(newOperator);
emit OperatorUpdated(newOperator, true);
}
}
// File: contracts/SeanceCircle.sol
// SeanceCircle with Governance.
contract SeanceCircle is ERC20('SeanceCircle', 'SEANCE'), Ownable, Operable {
SoulPower public soul;
bool isInitialized;
function mint(address _to, uint256 _amount) public onlyOperator {
require(isInitialized, 'the circle has not yet begun');
_mint(_to, _amount);
_moveDelegates(address(0), _delegates[_to], _amount);
}
function burn(address _from ,uint256 _amount) public onlyOperator {
_burn(_from, _amount);
_moveDelegates(_delegates[_from], address(0), _amount);
}
function initialize(SoulPower _soul) external onlyOwner {
require(!isInitialized, 'the circle has already begun');
soul = _soul;
isInitialized = true;
}
// safe soul transfer function, just in case if rounding error causes pool to not have enough SOUL.
function safeSoulTransfer(address _to, uint256 _amount) public onlyOperator {
uint256 soulBal = soul.balanceOf(address(this));
if (_amount > soulBal) {
soul.transfer(_to, soulBal);
} else {
soul.transfer(_to, _amount);
}
}
// record of each accounts delegate
mapping (address => address) internal _delegates;
// checkpoint for marking number of votes from a given block timestamp
struct Checkpoint {
uint256 fromTime;
uint256 votes;
}
// record of votes checkpoints for each account, by index
mapping (address => mapping (uint256 => Checkpoint)) public checkpoints;
// number of checkpoints for each account
mapping (address => uint256) public numCheckpoints;
// EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
// EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
// record of states for signing / validating signatures
mapping (address => uint) public nonces;
// emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
// emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
// returns the address delegated by a given delegator (external view)
function delegates(address delegator) external view returns (address) { return _delegates[delegator]; }
// delegates to the `delegatee` (external)
function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); }
// delegates votes from signatory to `delegatee` (external)
function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
bytes32 domainSeparator = keccak256(
abi.encode(
DOMAIN_TYPEHASH,
keccak256(bytes(name())),
getChainId(),
address(this)
)
);
bytes32 structHash = keccak256(
abi.encode(
DELEGATION_TYPEHASH,
delegatee,
nonce,
expiry
)
);
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
domainSeparator,
structHash
)
);
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "SOUL::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "SOUL::delegateBySig: invalid nonce");
require(block.timestamp <= expiry, "SOUL::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
// returns current votes balance for `account` (external view)
function getCurrentVotes(address account) external view returns (uint) {
uint nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
// returns an account's prior vote count as of a given timestamp (external view)
function getPriorVotes(address account, uint blockTimestamp) external view returns (uint256) {
require(blockTimestamp < block.timestamp, "SOUL::getPriorVotes: not yet determined");
uint256 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// checks most recent balance
if (checkpoints[account][nCheckpoints - 1].fromTime <= blockTimestamp) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// checks implicit zero balance
if (checkpoints[account][0].fromTime > blockTimestamp) {
return 0;
}
uint256 lower = 0;
uint256 upper = nCheckpoints - 1;
while (upper > lower) {
uint256 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromTime == blockTimestamp) {
return cp.votes;
} else if (cp.fromTime < blockTimestamp) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee) internal {
address currentDelegate = _delegates[delegator];
uint256 delegatorBalance = balanceOf(delegator); // balance of underlying SOUL (not scaled);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
// decrease old representative
uint256 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint256 srcRepNew = srcRepOld - amount;
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
// increase new representative
uint256 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint256 dstRepNew = dstRepOld + amount;
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(
address delegatee,
uint256 nCheckpoints,
uint256 oldVotes,
uint256 newVotes
)
internal
{
uint256 blockTimestamp = safe256(block.timestamp, "SOUL::_writeCheckpoint: block timestamp exceeds 256 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromTime == blockTimestamp) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockTimestamp, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe256(uint n, string memory errorMessage) internal pure returns (uint256) {
require(n < type(uint256).max, errorMessage);
return uint256(n);
}
function getChainId() internal view returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
function newSoul(SoulPower _soul) external onlyOperator {
require(soul != _soul, 'must be a new address');
soul = _soul;
}
}
// File: contracts/interfaces/IMigrator.sol
interface IMigrator {
function migrate(IERC20 token) external returns (IERC20);
}
// File: contracts/SoulSummoner.sol
// the summoner of souls | ownership transferred to a governance smart contract
// upon sufficient distribution + the community's desire to self-govern.
contract SoulSummoner is AccessControl, Pausable, ReentrancyGuard {
// user info
struct Users {
uint amount; // total tokens user has provided.
uint rewardDebt; // reward debt (see below).
uint rewardDebtAtTime; // the last time user stake.
uint lastWithdrawTime; // the last time a user withdrew at.
uint firstDepositTime; // the last time a user deposited at.
uint timeDelta; // time passed since withdrawals.
uint lastDepositTime; // most recent deposit time.
// pending reward = (user.amount * pool.accSoulPerShare) - user.rewardDebt
// the following occurs when a user +/- tokens to a pool:
// 1. pool: `accSoulPerShare` and `lastRewardTime` update.
// 2. user: receives pending reward.
// 3. user: `amount` updates(+/-).
// 4. user: `rewardDebt` updates (+/-).
}
// pool info
struct Pools {
IERC20 lpToken; // lp token ierc20 contract.
uint allocPoint; // allocation points assigned to this pool | SOULs to distribute per second.
uint lastRewardTime; // most recent UNIX timestamp during which SOULs distribution occurred in the pool.
uint accSoulPerShare; // accumulated SOULs per share, times 1e12.
}
// soul power: our native utility token
address private soulAddress;
SoulPower public soul;
// seance circle: our governance token
address private seanceAddress;
SeanceCircle public seance;
address public team; // receives 1/8 soul supply
address public dao; // recieves 1/8 soul supply
address public supreme; // has supreme role
// migrator contract | has lotsa power
IMigrator public migrator;
// blockchain variables accounting for share of overall emissions
uint public totalWeight;
uint public weight;
// soul x day x this.chain
uint public dailySoul; // = weight * 250K * 1e18;
// soul x second x this.chain
uint public soulPerSecond; // = dailySoul / 86400;
// bonus muliplier for early soul summoners
uint public bonusMultiplier = 1;
// timestamp when soul rewards began (initialized)
uint public startTime;
// ttl allocation points | must be the sum of all allocation points
uint public totalAllocPoint;
// summoner initialized state.
bool public isInitialized;
// decay rate on withdrawal fee of 1%.
uint public immutable dailyDecay = enWei(1);
// start rate for the withdrawal fee.
uint public startRate;
Pools[] public poolInfo; // pool info
mapping (uint => mapping (address => Users)) public userInfo; // staker data
// divinated roles
bytes32 public isis; // soul summoning goddess of magic
bytes32 public maat; // goddess of cosmic order
event RoleDivinated(bytes32 role, bytes32 supreme);
// restricted to the council of the role passed as an object to obey (role)
modifier obey(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
// prevents: early reward distribution
modifier isSummoned {
require(isInitialized, 'rewards have not yet begun');
_;
}
event Deposit(address indexed user, uint indexed pid, uint amount);
event Withdraw(address indexed user, uint indexed pid, uint amount, uint timeStamp);
event Initialized(address team, address dao, address soul, address seance, uint totalAllocPoint, uint weight);
event PoolAdded(uint pid, uint allocPoint, IERC20 lpToken, uint totalAllocPoint);
event PoolSet(uint pid, uint allocPoint);
event WeightUpdated(uint weight, uint totalWeight);
event RewardsUpdated(uint dailySoul, uint soulPerSecond);
event StartRateUpdated(uint startRate);
event AccountsUpdated(address dao, address team, address admin);
event TokensUpdated(address soul, address seance);
event DepositRevised(uint _pid, address _user, uint _time);
// validates: pool exists
modifier validatePoolByPid(uint pid) {
require(pid < poolInfo.length, 'pool does not exist');
_;
}
// channels the power of the isis and ma'at to the deployer (deployer)
constructor() {
supreme = msg.sender; // 0x81Dd37687c74Df8F957a370A9A4435D873F5e5A9; // multi-sig safe
team = msg.sender; // 0x36d0164e87B58427c4153c089aeDDa8Ec0B80B9D; // team wallet
dao = msg.sender; // 0x1C63C726926197BD3CB75d86bCFB1DaeBcD87250; // dao treasury (multi-sig)
isis = keccak256("isis"); // goddess of magic who creates pools
maat = keccak256("maat"); // goddess of cosmic order who allocates emissions
_divinationCeremony(DEFAULT_ADMIN_ROLE, DEFAULT_ADMIN_ROLE, supreme);
_divinationCeremony(isis, isis, supreme); // isis role created -- supreme divined admin
_divinationCeremony(maat, isis, dao); // maat role created -- isis divined admin
}
function _divinationCeremony(bytes32 _role, bytes32 _adminRole, address _account)
internal returns (bool) {
_setupRole(_role, _account);
_setRoleAdmin(_role, _adminRole);
return true;
}
// validate: pool uniqueness to eliminate duplication risk (internal view)
function checkPoolDuplicate(IERC20 _token) internal view {
uint length = poolInfo.length;
for (uint pid = 0; pid < length; ++pid) {
require(poolInfo[pid].lpToken != _token, 'duplicated pool');
}
}
// activates: rewards (owner)
function initialize() external obey(isis) {
require(!isInitialized, 'already initialized');
soulAddress = 0xCF174A6793FA36A73e8fF18A71bd81C985ef5aB5;
seanceAddress = 0xD54Cf31D5653F4a062f5DA4C83170A5867d04442;
// [required]: update global constants
startTime = block.timestamp;
totalWeight = 1000;
weight = 1000;
startRate = enWei(14);
uint allocPoint = 1000;
soul = SoulPower(soulAddress);
seance = SeanceCircle(seanceAddress);
// updates: dailySoul and soulPerSecond
updateRewards(weight, totalWeight);
// adds: staking pool
poolInfo.push(Pools({
lpToken: soul,
allocPoint: allocPoint,
lastRewardTime: startTime,
accSoulPerShare: 0
}));
isInitialized = true; // triggers: initialize state
totalAllocPoint += allocPoint; // kickstarts: total allocation
emit Initialized(team, dao, soulAddress, seanceAddress, totalAllocPoint, weight);
}
// returns: amount of pools
function poolLength() external view returns (uint) { return poolInfo.length; }
// add: new pool (isis)
function addPool(uint _allocPoint, IERC20 _lpToken, bool _withUpdate)
public isSummoned obey(isis) { // isis: the soul summoning goddess whose power transcends them all
checkPoolDuplicate(_lpToken);
_addPool(_allocPoint, _lpToken, _withUpdate);
}
// add: new pool (internal)
function _addPool(uint _allocPoint, IERC20 _lpToken, bool _withUpdate) internal {
if (_withUpdate) { massUpdatePools(); }
totalAllocPoint += _allocPoint;
poolInfo.push(
Pools({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardTime: block.timestamp > startTime ? block.timestamp : startTime,
accSoulPerShare: 0
}));
updateStakingPool();
uint pid = poolInfo.length;
emit PoolAdded(pid, _allocPoint, _lpToken, totalAllocPoint);
}
// set: allocation points (maat)
function set(uint pid, uint allocPoint, bool withUpdate)
external isSummoned validatePoolByPid(pid) obey(maat) {
if (withUpdate) { massUpdatePools(); } // updates all pools
uint prevAllocPoint = poolInfo[pid].allocPoint;
poolInfo[pid].allocPoint = allocPoint;
if (prevAllocPoint != allocPoint) {
totalAllocPoint = totalAllocPoint - prevAllocPoint + allocPoint;
updateStakingPool(); // updates only selected pool
}
emit PoolSet(pid, allocPoint);
}
// set: migrator contract (isis)
function setMigrator(IMigrator _migrator) external isSummoned obey(isis) {
migrator = _migrator;
}
// view: user delta
function userDelta(uint256 _pid, address _user) public view returns (uint256 delta) {
Users memory user = userInfo[_pid][_user];
return user.lastWithdrawTime > 0
? block.timestamp - user.lastWithdrawTime
: block.timestamp - user.firstDepositTime;
}
// migrate: lp tokens to another contract (migrator)
function migrate(uint pid) external isSummoned validatePoolByPid(pid) {
require(address(migrator) != address(0), 'no migrator set');
Pools storage pool = poolInfo[pid];
IERC20 lpToken = pool.lpToken;
uint bal = lpToken.balanceOf(address(this));
lpToken.approve(address(migrator), bal);
IERC20 _lpToken = migrator.migrate(lpToken);
require(bal == _lpToken.balanceOf(address(this)), "migrate: insufficient balance");
pool.lpToken = _lpToken;
}
// view: bonus multiplier (public view)
function getMultiplier(uint from, uint to) public view returns (uint) {
return (to - from) * bonusMultiplier; // todo: minus parens
}
// returns: decay rate for a pid (public view)
function getFeeRate(uint pid, uint timeDelta) public view returns (uint feeRate) {
uint daysPassed = timeDelta < 1 days ? 0 : timeDelta / 1 days;
uint rateDecayed = enWei(daysPassed);
uint _rate = rateDecayed >= startRate ? 0 : startRate - rateDecayed;
// returns 0 for SAS
return pid == 0 ? 0 : _rate;
}
// returns: feeAmount and with withdrawableAmount for a given pid and amount
function getWithdrawable(uint pid, uint timeDelta, uint amount) public view returns (uint _feeAmount, uint _withdrawable) {
uint feeRate = fromWei(getFeeRate(pid, timeDelta));
uint feeAmount = (amount * feeRate) / 100;
uint withdrawable = amount - feeAmount;
return (feeAmount, withdrawable);
}
// view: pending soul rewards (external)
function pendingSoul(uint pid, address _user) external view returns (uint pendingAmount) {
Pools storage pool = poolInfo[pid];
Users storage user = userInfo[pid][_user];
uint accSoulPerShare = pool.accSoulPerShare;
uint lpSupply = pool.lpToken.balanceOf(address(this));
if (block.timestamp > pool.lastRewardTime && lpSupply != 0) {
uint multiplier = getMultiplier(pool.lastRewardTime, block.timestamp);
uint soulReward = multiplier * soulPerSecond * pool.allocPoint / totalAllocPoint;
accSoulPerShare = accSoulPerShare + soulReward * 1e12 / lpSupply;
}
return user.amount * accSoulPerShare / 1e12 - user.rewardDebt;
}
// update: rewards for all pools (public)
function massUpdatePools() public {
uint length = poolInfo.length;
for (uint pid = 0; pid < length; ++pid) { updatePool(pid); }
}
// update: rewards for a given pool id (public)
function updatePool(uint pid) public validatePoolByPid(pid) {
Pools storage pool = poolInfo[pid];
if (block.timestamp <= pool.lastRewardTime) { return; }
uint lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) { pool.lastRewardTime = block.timestamp; return; } // first staker in pool
uint multiplier = getMultiplier(pool.lastRewardTime, block.timestamp);
uint soulReward = multiplier * soulPerSecond * pool.allocPoint / totalAllocPoint;
uint divi = soulReward * 1e12 / 8e12; // 12.5% rewards
uint divis = divi * 2; // total divis
uint shares = soulReward - divis; // net shares
soul.mint(team, divi);
soul.mint(dao, divi);
soul.mint(address(seance), shares);
pool.accSoulPerShare = pool.accSoulPerShare + (soulReward * 1e12 / lpSupply);
pool.lastRewardTime = block.timestamp;
}
// deposit: lp tokens (lp owner)
function deposit(uint pid, uint amount) external nonReentrant validatePoolByPid(pid) whenNotPaused {
require (pid != 0, 'deposit SOUL by staking');
Pools storage pool = poolInfo[pid];
Users storage user = userInfo[pid][msg.sender];
updatePool(pid);
if (user.amount > 0) { // already deposited assets
uint pending = (user.amount * pool.accSoulPerShare) / 1e12 - user.rewardDebt;
if(pending > 0) { // sends pending rewards, if applicable
safeSoulTransfer(msg.sender, pending);
}
}
if (amount > 0) { // if adding more
pool.lpToken.transferFrom(address(msg.sender), address(this), amount);
user.amount += amount;
}
user.rewardDebt = user.amount * pool.accSoulPerShare / 1e12;
// marks timestamp for first deposit
user.firstDepositTime =
user.firstDepositTime > 0
? user.firstDepositTime
: block.timestamp;
emit Deposit(msg.sender, pid, amount);
}
// withdraw: lp tokens (external farmers)
function withdraw(uint pid, uint amount) external nonReentrant validatePoolByPid(pid) {
require (pid != 0, 'withdraw SOUL by unstaking');
Pools storage pool = poolInfo[pid];
Users storage user = userInfo[pid][msg.sender];
require(user.amount >= amount, 'withdraw not good');
updatePool(pid);
uint pending = user.amount * pool.accSoulPerShare / 1e12 - user.rewardDebt;
if(pending > 0) { safeSoulTransfer(msg.sender, pending); }
if(amount > 0) {
if(user.lastDepositTime > 0){
user.timeDelta = block.timestamp - user.lastDepositTime; }
else { user.timeDelta = block.timestamp - user.firstDepositTime; }
user.amount = user.amount - amount;
}
uint timeDelta = userInfo[pid][msg.sender].timeDelta;
(, uint withdrawable) = getWithdrawable(pid, timeDelta, amount); // removes feeAmount from amount
uint feeAmount = amount - withdrawable;
pool.lpToken.transfer(address(dao), feeAmount);
pool.lpToken.transfer(address(msg.sender), withdrawable);
user.rewardDebt = user.amount * pool.accSoulPerShare / 1e12;
user.lastWithdrawTime = block.timestamp;
emit Withdraw(msg.sender, pid, amount, block.timestamp);
}
// stake: soul into summoner (external)
function enterStaking(uint amount) external nonReentrant whenNotPaused {
Pools storage pool = poolInfo[0];
Users storage user = userInfo[0][msg.sender];
updatePool(0);
if (user.amount > 0) {
uint pending = user.amount * pool.accSoulPerShare / 1e12 - user.rewardDebt;
if(pending > 0) {
safeSoulTransfer(msg.sender, pending);
}
}
if(amount > 0) {
pool.lpToken.transferFrom(address(msg.sender), address(this), amount);
user.amount = user.amount + amount;
}
// marks timestamp for first deposit
user.firstDepositTime =
user.firstDepositTime > 0
? user.firstDepositTime
: block.timestamp;
user.rewardDebt = user.amount * pool.accSoulPerShare / 1e12;
seance.mint(msg.sender, amount);
emit Deposit(msg.sender, 0, amount);
}
// unstake: your soul (external staker)
function leaveStaking(uint amount) external nonReentrant {
Pools storage pool = poolInfo[0];
Users storage user = userInfo[0][msg.sender];
require(user.amount >= amount, "withdraw: not good");
updatePool(0);
uint pending = user.amount * pool.accSoulPerShare / 1e12 - user.rewardDebt;
if(pending > 0) {
safeSoulTransfer(msg.sender, pending);
}
if(amount > 0) {
user.amount = user.amount - amount;
pool.lpToken.transfer(address(msg.sender), amount);
}
user.rewardDebt = user.amount * pool.accSoulPerShare / 1e12;
user.lastWithdrawTime = block.timestamp;
seance.burn(msg.sender, amount);
emit Withdraw(msg.sender, 0, amount, block.timestamp);
}
// transfer: seance (internal)
function safeSoulTransfer(address account, uint amount) internal {
seance.safeSoulTransfer(account, amount);
}
// ** UPDATE FUNCTIONS ** //
// update: weight (maat)
function updateWeights(uint _weight, uint _totalWeight) external obey(maat) {
require(weight != _weight || totalWeight != _totalWeight, 'must be at least one new value');
require(_totalWeight >= _weight, 'weight cannot exceed totalWeight');
weight = _weight;
totalWeight = _totalWeight;
updateRewards(weight, totalWeight);
emit WeightUpdated(weight, totalWeight);
}
// update: staking pool (internal)
function updateStakingPool() internal {
uint length = poolInfo.length;
uint points;
for (uint pid = 1; pid < length; ++pid) {
points = points + poolInfo[pid].allocPoint;
}
if (points != 0) {
points = points / 3;
totalAllocPoint = totalAllocPoint - poolInfo[0].allocPoint + points;
poolInfo[0].allocPoint = points;
}
}
// update: multiplier (maat)
function updateMultiplier(uint _bonusMultiplier) external obey(maat) {
bonusMultiplier = _bonusMultiplier;
}
// update: rewards (internal)
function updateRewards(uint _weight, uint _totalWeight) internal {
uint share = enWei(_weight) / _totalWeight; // share of ttl emissions for chain (chain % ttl emissions)
dailySoul = share * (250_000); // dailySoul (for this.chain) = share (%) x 250K (soul emissions constant)
soulPerSecond = dailySoul / 1 days; // updates: daily rewards expressed in seconds (1 days = 86,400 secs)
emit RewardsUpdated(dailySoul, soulPerSecond);
}
// update: startRate (maat)
function updateStartRate(uint _startRate) public obey(maat) {
require(startRate != enWei(_startRate));
startRate = enWei(_startRate);
emit StartRateUpdated(startRate);
}
// update accounts: dao, team, and supreme addresses (isis)
function updateAccounts(address _dao, address _team, address _supreme) external obey(isis) {
require(dao != _dao || team != _team || supreme != _supreme, 'must be a new account');
dao = _dao;
team = _team;
supreme = _supreme;
emit AccountsUpdated(dao, team, supreme);
}
// update tokens: soul and seance addresses (isis)
function updateTokens(address _soul, address _seance) external obey(isis) {
require(soul != IERC20(_soul) || seance != IERC20(_seance), 'must be a new token address');
soul = SoulPower(_soul);
seance = SeanceCircle(_seance);
emit TokensUpdated(_soul, _seance);
}
// manual override to reassign the first deposit time for a given (pid, account)
function reviseDeposit(uint _pid, address _user, uint256 _time) public obey(maat) {
Users storage user = userInfo[_pid][_user];
user.firstDepositTime = _time;
emit DepositRevised(_pid, _user, _time);
}
// ** HELPER FUNCTIONS ** //
// helper functions to convert to wei and 1/100th
function enWei(uint amount) public pure returns (uint) { return amount * 1e18; }
function fromWei(uint amount) public pure returns (uint) { return amount / 1e18; }
}
|
manual override to reassign the first deposit time for a given (pid, account)
|
function reviseDeposit(uint _pid, address _user, uint256 _time) public obey(maat) {
Users storage user = userInfo[_pid][_user];
user.firstDepositTime = _time;
emit DepositRevised(_pid, _user, _time);
}
| 957,153 |
pragma solidity ^0.5.0;
contract ResolverBase {
bytes4 private constant INTERFACE_META_ID = 0x01ffc9a7;
function supportsInterface(bytes4 interfaceID) public pure returns(bool) {
return interfaceID == INTERFACE_META_ID;
}
function isAuthorised(bytes32 node) internal view returns(bool);
modifier authorised(bytes32 node) {
require(isAuthorised(node));
_;
}
function bytesToAddress(bytes memory b) internal pure returns(address payable a) {
require(b.length == 20);
assembly {
a := div(mload(add(b, 32)), exp(256, 12))
}
}
function addressToBytes(address a) internal pure returns(bytes memory b) {
b = new bytes(20);
assembly {
mstore(add(b, 32), mul(a, exp(256, 12)))
}
}
}
pragma solidity >=0.5.0;
interface ENS {
// Logged when the owner of a node assigns a new owner to a subnode.
event NewOwner(bytes32 indexed node, bytes32 indexed label, address owner);
// Logged when the owner of a node transfers ownership to a new account.
event Transfer(bytes32 indexed node, address owner);
// Logged when the resolver for a node changes.
event NewResolver(bytes32 indexed node, address resolver);
// Logged when the TTL of a node changes
event NewTTL(bytes32 indexed node, uint64 ttl);
// Logged when an operator is added or removed.
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
function setRecord(bytes32 node, address owner, address resolver, uint64 ttl) external;
function setSubnodeRecord(bytes32 node, bytes32 label, address owner, address resolver, uint64 ttl) external;
function setSubnodeOwner(bytes32 node, bytes32 label, address owner) external returns(bytes32);
function setResolver(bytes32 node, address resolver) external;
function setOwner(bytes32 node, address owner) external;
function setTTL(bytes32 node, uint64 ttl) external;
function setApprovalForAll(address operator, bool approved) external;
function owner(bytes32 node) external view returns (address);
function resolver(bytes32 node) external view returns (address);
function ttl(bytes32 node) external view returns (uint64);
function recordExists(bytes32 node) external view returns (bool);
function isApprovedForAll(address owner, address operator) external view returns (bool);
}
/**
* The ENS registry contract.
*/
contract ENSRegistry is ENS {
struct Record {
address owner;
address resolver;
uint64 ttl;
}
mapping (bytes32 => Record) records;
mapping (address => mapping(address => bool)) operators;
// Permits modifications only by the owner of the specified node.
modifier authorised(bytes32 node) {
address owner = records[node].owner;
require(owner == msg.sender || operators[owner][msg.sender]);
_;
}
/**
* @dev Constructs a new ENS registrar.
*/
constructor() public {
records[0x0].owner = msg.sender;
}
/**
* @dev Sets the record for a node.
* @param node The node to update.
* @param owner The address of the new owner.
* @param resolver The address of the resolver.
* @param ttl The TTL in seconds.
*/
function setRecord(bytes32 node, address owner, address resolver, uint64 ttl) external {
setOwner(node, owner);
_setResolverAndTTL(node, resolver, ttl);
}
/**
* @dev Sets the record for a subnode.
* @param node The parent node.
* @param label The hash of the label specifying the subnode.
* @param owner The address of the new owner.
* @param resolver The address of the resolver.
* @param ttl The TTL in seconds.
*/
function setSubnodeRecord(bytes32 node, bytes32 label, address owner, address resolver, uint64 ttl) external {
bytes32 subnode = setSubnodeOwner(node, label, owner);
_setResolverAndTTL(subnode, resolver, ttl);
}
/**
* @dev Transfers ownership of a node to a new address. May only be called by the current owner of the node.
* @param node The node to transfer ownership of.
* @param owner The address of the new owner.
*/
function setOwner(bytes32 node, address owner) public authorised(node) {
_setOwner(node, owner);
emit Transfer(node, owner);
}
/**
* @dev Transfers ownership of a subnode keccak256(node, label) to a new address. May only be called by the owner of the parent node.
* @param node The parent node.
* @param label The hash of the label specifying the subnode.
* @param owner The address of the new owner.
*/
function setSubnodeOwner(bytes32 node, bytes32 label, address owner) public authorised(node) returns(bytes32) {
bytes32 subnode = keccak256(abi.encodePacked(node, label));
_setOwner(subnode, owner);
emit NewOwner(node, label, owner);
return subnode;
}
/**
* @dev Sets the resolver address for the specified node.
* @param node The node to update.
* @param resolver The address of the resolver.
*/
function setResolver(bytes32 node, address resolver) public authorised(node) {
emit NewResolver(node, resolver);
records[node].resolver = resolver;
}
/**
* @dev Sets the TTL for the specified node.
* @param node The node to update.
* @param ttl The TTL in seconds.
*/
function setTTL(bytes32 node, uint64 ttl) public authorised(node) {
emit NewTTL(node, ttl);
records[node].ttl = ttl;
}
/**
* @dev Enable or disable approval for a third party ("operator") to manage
* all of `msg.sender`'s ENS records. Emits the ApprovalForAll event.
* @param operator Address to add to the set of authorized operators.
* @param approved True if the operator is approved, false to revoke approval.
*/
function setApprovalForAll(address operator, bool approved) external {
operators[msg.sender][operator] = approved;
emit ApprovalForAll(msg.sender, operator, approved);
}
/**
* @dev Returns the address that owns the specified node.
* @param node The specified node.
* @return address of the owner.
*/
function owner(bytes32 node) public view returns (address) {
address addr = records[node].owner;
if (addr == address(this)) {
return address(0x0);
}
return addr;
}
/**
* @dev Returns the address of the resolver for the specified node.
* @param node The specified node.
* @return address of the resolver.
*/
function resolver(bytes32 node) public view returns (address) {
return records[node].resolver;
}
/**
* @dev Returns the TTL of a node, and any records associated with it.
* @param node The specified node.
* @return ttl of the node.
*/
function ttl(bytes32 node) public view returns (uint64) {
return records[node].ttl;
}
/**
* @dev Returns whether a record has been imported to the registry.
* @param node The specified node.
* @return Bool if record exists
*/
function recordExists(bytes32 node) public view returns (bool) {
return records[node].owner != address(0x0);
}
/**
* @dev Query if an address is an authorized operator for another address.
* @param owner The address that owns the records.
* @param operator The address that acts on behalf of the owner.
* @return True if `operator` is an approved operator for `owner`, false otherwise.
*/
function isApprovedForAll(address owner, address operator) external view returns (bool) {
return operators[owner][operator];
}
function _setOwner(bytes32 node, address owner) internal {
records[node].owner = owner;
}
function _setResolverAndTTL(bytes32 node, address resolver, uint64 ttl) internal {
if(resolver != records[node].resolver) {
records[node].resolver = resolver;
emit NewResolver(node, resolver);
}
if(ttl != records[node].ttl) {
records[node].ttl = ttl;
emit NewTTL(node, ttl);
}
}
}
pragma solidity ^0.5.0;
contract ABIResolver is ResolverBase {
bytes4 constant private ABI_INTERFACE_ID = 0x2203ab56;
event ABIChanged(bytes32 indexed node, uint256 indexed contentType);
mapping(bytes32=>mapping(uint256=>bytes)) abis;
/**
* Sets the ABI associated with an ENS node.
* Nodes may have one ABI of each content type. To remove an ABI, set it to
* the empty string.
* @param node The node to update.
* @param contentType The content type of the ABI
* @param data The ABI data.
*/
function setABI(bytes32 node, uint256 contentType, bytes calldata data) external authorised(node) {
// Content types must be powers of 2
require(((contentType - 1) & contentType) == 0);
abis[node][contentType] = data;
emit ABIChanged(node, contentType);
}
/**
* Returns the ABI associated with an ENS node.
* Defined in EIP205.
* @param node The ENS node to query
* @param contentTypes A bitwise OR of the ABI formats accepted by the caller.
* @return contentType The content type of the return value
* @return data The ABI data
*/
function ABI(bytes32 node, uint256 contentTypes) external view returns (uint256, bytes memory) {
mapping(uint256=>bytes) storage abiset = abis[node];
for (uint256 contentType = 1; contentType <= contentTypes; contentType <<= 1) {
if ((contentType & contentTypes) != 0 && abiset[contentType].length > 0) {
return (contentType, abiset[contentType]);
}
}
return (0, bytes(""));
}
function supportsInterface(bytes4 interfaceID) public pure returns(bool) {
return interfaceID == ABI_INTERFACE_ID || super.supportsInterface(interfaceID);
}
}
pragma solidity ^0.5.0;
contract AddrResolver is ResolverBase {
bytes4 constant private ADDR_INTERFACE_ID = 0x3b3b57de;
bytes4 constant private ADDRESS_INTERFACE_ID = 0xf1cb7e06;
uint constant private COIN_TYPE_ETH = 60;
event AddrChanged(bytes32 indexed node, address a);
event AddressChanged(bytes32 indexed node, uint coinType, bytes newAddress);
mapping(bytes32=>mapping(uint=>bytes)) _addresses;
/**
* Sets the address associated with an ENS node.
* May only be called by the owner of that node in the ENS registry.
* @param node The node to update.
* @param a The address to set.
*/
function setAddr(bytes32 node, address a) external authorised(node) {
setAddr(node, COIN_TYPE_ETH, addressToBytes(a));
}
/**
* Returns the address associated with an ENS node.
* @param node The ENS node to query.
* @return The associated address.
*/
function addr(bytes32 node) public view returns (address payable) {
bytes memory a = addr(node, COIN_TYPE_ETH);
if(a.length == 0) {
return address(0);
}
return bytesToAddress(a);
}
function setAddr(bytes32 node, uint coinType, bytes memory a) public authorised(node) {
emit AddressChanged(node, coinType, a);
if(coinType == COIN_TYPE_ETH) {
emit AddrChanged(node, bytesToAddress(a));
}
_addresses[node][coinType] = a;
}
function addr(bytes32 node, uint coinType) public view returns(bytes memory) {
return _addresses[node][coinType];
}
function supportsInterface(bytes4 interfaceID) public pure returns(bool) {
return interfaceID == ADDR_INTERFACE_ID || interfaceID == ADDRESS_INTERFACE_ID || super.supportsInterface(interfaceID);
}
}
pragma solidity ^0.5.0;
contract ContentHashResolver is ResolverBase {
bytes4 constant private CONTENT_HASH_INTERFACE_ID = 0xbc1c58d1;
event ContenthashChanged(bytes32 indexed node, bytes hash);
mapping(bytes32=>bytes) hashes;
/**
* Sets the contenthash associated with an ENS node.
* May only be called by the owner of that node in the ENS registry.
* @param node The node to update.
* @param hash The contenthash to set
*/
function setContenthash(bytes32 node, bytes calldata hash) external authorised(node) {
hashes[node] = hash;
emit ContenthashChanged(node, hash);
}
/**
* Returns the contenthash associated with an ENS node.
* @param node The ENS node to query.
* @return The associated contenthash.
*/
function contenthash(bytes32 node) external view returns (bytes memory) {
return hashes[node];
}
function supportsInterface(bytes4 interfaceID) public pure returns(bool) {
return interfaceID == CONTENT_HASH_INTERFACE_ID || super.supportsInterface(interfaceID);
}
}
pragma solidity >0.4.23;
library BytesUtils {
/*
* @dev Returns the keccak-256 hash of a byte range.
* @param self The byte string to hash.
* @param offset The position to start hashing at.
* @param len The number of bytes to hash.
* @return The hash of the byte range.
*/
function keccak(bytes memory self, uint offset, uint len) internal pure returns (bytes32 ret) {
require(offset + len <= self.length);
assembly {
ret := keccak256(add(add(self, 32), offset), len)
}
}
/*
* @dev Returns a positive number if `other` comes lexicographically after
* `self`, a negative number if it comes before, or zero if the
* contents of the two bytes are equal.
* @param self The first bytes to compare.
* @param other The second bytes to compare.
* @return The result of the comparison.
*/
function compare(bytes memory self, bytes memory other) internal pure returns (int) {
return compare(self, 0, self.length, other, 0, other.length);
}
/*
* @dev Returns a positive number if `other` comes lexicographically after
* `self`, a negative number if it comes before, or zero if the
* contents of the two bytes are equal. Comparison is done per-rune,
* on unicode codepoints.
* @param self The first bytes to compare.
* @param offset The offset of self.
* @param len The length of self.
* @param other The second bytes to compare.
* @param otheroffset The offset of the other string.
* @param otherlen The length of the other string.
* @return The result of the comparison.
*/
function compare(bytes memory self, uint offset, uint len, bytes memory other, uint otheroffset, uint otherlen) internal pure returns (int) {
uint shortest = len;
if (otherlen < len)
shortest = otherlen;
uint selfptr;
uint otherptr;
assembly {
selfptr := add(self, add(offset, 32))
otherptr := add(other, add(otheroffset, 32))
}
for (uint idx = 0; idx < shortest; idx += 32) {
uint a;
uint b;
assembly {
a := mload(selfptr)
b := mload(otherptr)
}
if (a != b) {
// Mask out irrelevant bytes and check again
uint mask;
if (shortest > 32) {
mask = uint256(- 1); // aka 0xffffff....
} else {
mask = ~(2 ** (8 * (32 - shortest + idx)) - 1);
}
uint diff = (a & mask) - (b & mask);
if (diff != 0)
return int(diff);
}
selfptr += 32;
otherptr += 32;
}
return int(len) - int(otherlen);
}
/*
* @dev Returns true if the two byte ranges are equal.
* @param self The first byte range to compare.
* @param offset The offset into the first byte range.
* @param other The second byte range to compare.
* @param otherOffset The offset into the second byte range.
* @param len The number of bytes to compare
* @return True if the byte ranges are equal, false otherwise.
*/
function equals(bytes memory self, uint offset, bytes memory other, uint otherOffset, uint len) internal pure returns (bool) {
return keccak(self, offset, len) == keccak(other, otherOffset, len);
}
/*
* @dev Returns true if the two byte ranges are equal with offsets.
* @param self The first byte range to compare.
* @param offset The offset into the first byte range.
* @param other The second byte range to compare.
* @param otherOffset The offset into the second byte range.
* @return True if the byte ranges are equal, false otherwise.
*/
function equals(bytes memory self, uint offset, bytes memory other, uint otherOffset) internal pure returns (bool) {
return keccak(self, offset, self.length - offset) == keccak(other, otherOffset, other.length - otherOffset);
}
/*
* @dev Compares a range of 'self' to all of 'other' and returns True iff
* they are equal.
* @param self The first byte range to compare.
* @param offset The offset into the first byte range.
* @param other The second byte range to compare.
* @return True if the byte ranges are equal, false otherwise.
*/
function equals(bytes memory self, uint offset, bytes memory other) internal pure returns (bool) {
return self.length >= offset + other.length && equals(self, offset, other, 0, other.length);
}
/*
* @dev Returns true if the two byte ranges are equal.
* @param self The first byte range to compare.
* @param other The second byte range to compare.
* @return True if the byte ranges are equal, false otherwise.
*/
function equals(bytes memory self, bytes memory other) internal pure returns(bool) {
return self.length == other.length && equals(self, 0, other, 0, self.length);
}
/*
* @dev Returns the 8-bit number at the specified index of self.
* @param self The byte string.
* @param idx The index into the bytes
* @return The specified 8 bits of the string, interpreted as an integer.
*/
function readUint8(bytes memory self, uint idx) internal pure returns (uint8 ret) {
return uint8(self[idx]);
}
/*
* @dev Returns the 16-bit number at the specified index of self.
* @param self The byte string.
* @param idx The index into the bytes
* @return The specified 16 bits of the string, interpreted as an integer.
*/
function readUint16(bytes memory self, uint idx) internal pure returns (uint16 ret) {
require(idx + 2 <= self.length);
assembly {
ret := and(mload(add(add(self, 2), idx)), 0xFFFF)
}
}
/*
* @dev Returns the 32-bit number at the specified index of self.
* @param self The byte string.
* @param idx The index into the bytes
* @return The specified 32 bits of the string, interpreted as an integer.
*/
function readUint32(bytes memory self, uint idx) internal pure returns (uint32 ret) {
require(idx + 4 <= self.length);
assembly {
ret := and(mload(add(add(self, 4), idx)), 0xFFFFFFFF)
}
}
/*
* @dev Returns the 32 byte value at the specified index of self.
* @param self The byte string.
* @param idx The index into the bytes
* @return The specified 32 bytes of the string.
*/
function readBytes32(bytes memory self, uint idx) internal pure returns (bytes32 ret) {
require(idx + 32 <= self.length);
assembly {
ret := mload(add(add(self, 32), idx))
}
}
/*
* @dev Returns the 32 byte value at the specified index of self.
* @param self The byte string.
* @param idx The index into the bytes
* @return The specified 32 bytes of the string.
*/
function readBytes20(bytes memory self, uint idx) internal pure returns (bytes20 ret) {
require(idx + 20 <= self.length);
assembly {
ret := and(mload(add(add(self, 32), idx)), 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000000)
}
}
/*
* @dev Returns the n byte value at the specified index of self.
* @param self The byte string.
* @param idx The index into the bytes.
* @param len The number of bytes.
* @return The specified 32 bytes of the string.
*/
function readBytesN(bytes memory self, uint idx, uint len) internal pure returns (bytes32 ret) {
require(len <= 32);
require(idx + len <= self.length);
assembly {
let mask := not(sub(exp(256, sub(32, len)), 1))
ret := and(mload(add(add(self, 32), idx)), mask)
}
}
function memcpy(uint dest, uint src, uint len) private pure {
// Copy word-length chunks while possible
for (; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
// Copy remaining bytes
uint mask = 256 ** (32 - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
}
/*
* @dev Copies a substring into a new byte string.
* @param self The byte string to copy from.
* @param offset The offset to start copying at.
* @param len The number of bytes to copy.
*/
function substring(bytes memory self, uint offset, uint len) internal pure returns(bytes memory) {
require(offset + len <= self.length);
bytes memory ret = new bytes(len);
uint dest;
uint src;
assembly {
dest := add(ret, 32)
src := add(add(self, 32), offset)
}
memcpy(dest, src, len);
return ret;
}
// Maps characters from 0x30 to 0x7A to their base32 values.
// 0xFF represents invalid characters in that range.
bytes constant base32HexTable = hex'00010203040506070809FFFFFFFFFFFFFF0A0B0C0D0E0F101112131415161718191A1B1C1D1E1FFFFFFFFFFFFFFFFFFFFF0A0B0C0D0E0F101112131415161718191A1B1C1D1E1F';
/**
* @dev Decodes unpadded base32 data of up to one word in length.
* @param self The data to decode.
* @param off Offset into the string to start at.
* @param len Number of characters to decode.
* @return The decoded data, left aligned.
*/
function base32HexDecodeWord(bytes memory self, uint off, uint len) internal pure returns(bytes32) {
require(len <= 52);
uint ret = 0;
uint8 decoded;
for(uint i = 0; i < len; i++) {
bytes1 char = self[off + i];
require(char >= 0x30 && char <= 0x7A);
decoded = uint8(base32HexTable[uint(uint8(char)) - 0x30]);
require(decoded <= 0x20);
if(i == len - 1) {
break;
}
ret = (ret << 5) | decoded;
}
uint bitlen = len * 5;
if(len % 8 == 0) {
// Multiple of 8 characters, no padding
ret = (ret << 5) | decoded;
} else if(len % 8 == 2) {
// Two extra characters - 1 byte
ret = (ret << 3) | (decoded >> 2);
bitlen -= 2;
} else if(len % 8 == 4) {
// Four extra characters - 2 bytes
ret = (ret << 1) | (decoded >> 4);
bitlen -= 4;
} else if(len % 8 == 5) {
// Five extra characters - 3 bytes
ret = (ret << 4) | (decoded >> 1);
bitlen -= 1;
} else if(len % 8 == 7) {
// Seven extra characters - 4 bytes
ret = (ret << 2) | (decoded >> 3);
bitlen -= 3;
} else {
revert();
}
return bytes32(ret << (256 - bitlen));
}
}
pragma solidity >0.4.18;
/**
* @dev A library for working with mutable byte buffers in Solidity.
*
* Byte buffers are mutable and expandable, and provide a variety of primitives
* for writing to them. At any time you can fetch a bytes object containing the
* current contents of the buffer. The bytes object should not be stored between
* operations, as it may change due to resizing of the buffer.
*/
library Buffer {
/**
* @dev Represents a mutable buffer. Buffers have a current value (buf) and
* a capacity. The capacity may be longer than the current value, in
* which case it can be extended without the need to allocate more memory.
*/
struct buffer {
bytes buf;
uint capacity;
}
/**
* @dev Initializes a buffer with an initial capacity.
* @param buf The buffer to initialize.
* @param capacity The number of bytes of space to allocate the buffer.
* @return The buffer, for chaining.
*/
function init(buffer memory buf, uint capacity) internal pure returns(buffer memory) {
if (capacity % 32 != 0) {
capacity += 32 - (capacity % 32);
}
// Allocate space for the buffer data
buf.capacity = capacity;
assembly {
let ptr := mload(0x40)
mstore(buf, ptr)
mstore(ptr, 0)
mstore(0x40, add(32, add(ptr, capacity)))
}
return buf;
}
/**
* @dev Initializes a new buffer from an existing bytes object.
* Changes to the buffer may mutate the original value.
* @param b The bytes object to initialize the buffer with.
* @return A new buffer.
*/
function fromBytes(bytes memory b) internal pure returns(buffer memory) {
buffer memory buf;
buf.buf = b;
buf.capacity = b.length;
return buf;
}
function resize(buffer memory buf, uint capacity) private pure {
bytes memory oldbuf = buf.buf;
init(buf, capacity);
append(buf, oldbuf);
}
function max(uint a, uint b) private pure returns(uint) {
if (a > b) {
return a;
}
return b;
}
/**
* @dev Sets buffer length to 0.
* @param buf The buffer to truncate.
* @return The original buffer, for chaining..
*/
function truncate(buffer memory buf) internal pure returns (buffer memory) {
assembly {
let bufptr := mload(buf)
mstore(bufptr, 0)
}
return buf;
}
/**
* @dev Writes a byte string to a buffer. Resizes if doing so would exceed
* the capacity of the buffer.
* @param buf The buffer to append to.
* @param off The start offset to write to.
* @param data The data to append.
* @param len The number of bytes to copy.
* @return The original buffer, for chaining.
*/
function write(buffer memory buf, uint off, bytes memory data, uint len) internal pure returns(buffer memory) {
require(len <= data.length);
if (off + len > buf.capacity) {
resize(buf, max(buf.capacity, len + off) * 2);
}
uint dest;
uint src;
assembly {
// Memory address of the buffer data
let bufptr := mload(buf)
// Length of existing buffer data
let buflen := mload(bufptr)
// Start address = buffer address + offset + sizeof(buffer length)
dest := add(add(bufptr, 32), off)
// Update buffer length if we're extending it
if gt(add(len, off), buflen) {
mstore(bufptr, add(len, off))
}
src := add(data, 32)
}
// Copy word-length chunks while possible
for (; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
// Copy remaining bytes
uint mask = 256 ** (32 - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
return buf;
}
/**
* @dev Appends a byte string to a buffer. Resizes if doing so would exceed
* the capacity of the buffer.
* @param buf The buffer to append to.
* @param data The data to append.
* @param len The number of bytes to copy.
* @return The original buffer, for chaining.
*/
function append(buffer memory buf, bytes memory data, uint len) internal pure returns (buffer memory) {
return write(buf, buf.buf.length, data, len);
}
/**
* @dev Appends a byte string to a buffer. Resizes if doing so would exceed
* the capacity of the buffer.
* @param buf The buffer to append to.
* @param data The data to append.
* @return The original buffer, for chaining.
*/
function append(buffer memory buf, bytes memory data) internal pure returns (buffer memory) {
return write(buf, buf.buf.length, data, data.length);
}
/**
* @dev Writes a byte to the buffer. Resizes if doing so would exceed the
* capacity of the buffer.
* @param buf The buffer to append to.
* @param off The offset to write the byte at.
* @param data The data to append.
* @return The original buffer, for chaining.
*/
function writeUint8(buffer memory buf, uint off, uint8 data) internal pure returns(buffer memory) {
if (off >= buf.capacity) {
resize(buf, buf.capacity * 2);
}
assembly {
// Memory address of the buffer data
let bufptr := mload(buf)
// Length of existing buffer data
let buflen := mload(bufptr)
// Address = buffer address + sizeof(buffer length) + off
let dest := add(add(bufptr, off), 32)
mstore8(dest, data)
// Update buffer length if we extended it
if eq(off, buflen) {
mstore(bufptr, add(buflen, 1))
}
}
return buf;
}
/**
* @dev Appends a byte to the buffer. Resizes if doing so would exceed the
* capacity of the buffer.
* @param buf The buffer to append to.
* @param data The data to append.
* @return The original buffer, for chaining.
*/
function appendUint8(buffer memory buf, uint8 data) internal pure returns(buffer memory) {
return writeUint8(buf, buf.buf.length, data);
}
/**
* @dev Writes up to 32 bytes to the buffer. Resizes if doing so would
* exceed the capacity of the buffer.
* @param buf The buffer to append to.
* @param off The offset to write at.
* @param data The data to append.
* @param len The number of bytes to write (left-aligned).
* @return The original buffer, for chaining.
*/
function write(buffer memory buf, uint off, bytes32 data, uint len) private pure returns(buffer memory) {
if (len + off > buf.capacity) {
resize(buf, (len + off) * 2);
}
uint mask = 256 ** len - 1;
// Right-align data
data = data >> (8 * (32 - len));
assembly {
// Memory address of the buffer data
let bufptr := mload(buf)
// Address = buffer address + sizeof(buffer length) + off + len
let dest := add(add(bufptr, off), len)
mstore(dest, or(and(mload(dest), not(mask)), data))
// Update buffer length if we extended it
if gt(add(off, len), mload(bufptr)) {
mstore(bufptr, add(off, len))
}
}
return buf;
}
/**
* @dev Writes a bytes20 to the buffer. Resizes if doing so would exceed the
* capacity of the buffer.
* @param buf The buffer to append to.
* @param off The offset to write at.
* @param data The data to append.
* @return The original buffer, for chaining.
*/
function writeBytes20(buffer memory buf, uint off, bytes20 data) internal pure returns (buffer memory) {
return write(buf, off, bytes32(data), 20);
}
/**
* @dev Appends a bytes20 to the buffer. Resizes if doing so would exceed
* the capacity of the buffer.
* @param buf The buffer to append to.
* @param data The data to append.
* @return The original buffer, for chhaining.
*/
function appendBytes20(buffer memory buf, bytes20 data) internal pure returns (buffer memory) {
return write(buf, buf.buf.length, bytes32(data), 20);
}
/**
* @dev Appends a bytes32 to the buffer. Resizes if doing so would exceed
* the capacity of the buffer.
* @param buf The buffer to append to.
* @param data The data to append.
* @return The original buffer, for chaining.
*/
function appendBytes32(buffer memory buf, bytes32 data) internal pure returns (buffer memory) {
return write(buf, buf.buf.length, data, 32);
}
/**
* @dev Writes an integer to the buffer. Resizes if doing so would exceed
* the capacity of the buffer.
* @param buf The buffer to append to.
* @param off The offset to write at.
* @param data The data to append.
* @param len The number of bytes to write (right-aligned).
* @return The original buffer, for chaining.
*/
function writeInt(buffer memory buf, uint off, uint data, uint len) private pure returns(buffer memory) {
if (len + off > buf.capacity) {
resize(buf, (len + off) * 2);
}
uint mask = 256 ** len - 1;
assembly {
// Memory address of the buffer data
let bufptr := mload(buf)
// Address = buffer address + off + sizeof(buffer length) + len
let dest := add(add(bufptr, off), len)
mstore(dest, or(and(mload(dest), not(mask)), data))
// Update buffer length if we extended it
if gt(add(off, len), mload(bufptr)) {
mstore(bufptr, add(off, len))
}
}
return buf;
}
/**
* @dev Appends a byte to the end of the buffer. Resizes if doing so would
* exceed the capacity of the buffer.
* @param buf The buffer to append to.
* @param data The data to append.
* @return The original buffer.
*/
function appendInt(buffer memory buf, uint data, uint len) internal pure returns(buffer memory) {
return writeInt(buf, buf.buf.length, data, len);
}
}
pragma solidity >0.4.23;
/**
* @dev RRUtils is a library that provides utilities for parsing DNS resource records.
*/
library RRUtils {
using BytesUtils for *;
using Buffer for *;
/**
* @dev Returns the number of bytes in the DNS name at 'offset' in 'self'.
* @param self The byte array to read a name from.
* @param offset The offset to start reading at.
* @return The length of the DNS name at 'offset', in bytes.
*/
function nameLength(bytes memory self, uint offset) internal pure returns(uint) {
uint idx = offset;
while (true) {
assert(idx < self.length);
uint labelLen = self.readUint8(idx);
idx += labelLen + 1;
if (labelLen == 0) {
break;
}
}
return idx - offset;
}
/**
* @dev Returns a DNS format name at the specified offset of self.
* @param self The byte array to read a name from.
* @param offset The offset to start reading at.
* @return The name.
*/
function readName(bytes memory self, uint offset) internal pure returns(bytes memory ret) {
uint len = nameLength(self, offset);
return self.substring(offset, len);
}
/**
* @dev Returns the number of labels in the DNS name at 'offset' in 'self'.
* @param self The byte array to read a name from.
* @param offset The offset to start reading at.
* @return The number of labels in the DNS name at 'offset', in bytes.
*/
function labelCount(bytes memory self, uint offset) internal pure returns(uint) {
uint count = 0;
while (true) {
assert(offset < self.length);
uint labelLen = self.readUint8(offset);
offset += labelLen + 1;
if (labelLen == 0) {
break;
}
count += 1;
}
return count;
}
/**
* @dev An iterator over resource records.
*/
struct RRIterator {
bytes data;
uint offset;
uint16 dnstype;
uint16 class;
uint32 ttl;
uint rdataOffset;
uint nextOffset;
}
/**
* @dev Begins iterating over resource records.
* @param self The byte string to read from.
* @param offset The offset to start reading at.
* @return An iterator object.
*/
function iterateRRs(bytes memory self, uint offset) internal pure returns (RRIterator memory ret) {
ret.data = self;
ret.nextOffset = offset;
next(ret);
}
/**
* @dev Returns true iff there are more RRs to iterate.
* @param iter The iterator to check.
* @return True iff the iterator has finished.
*/
function done(RRIterator memory iter) internal pure returns(bool) {
return iter.offset >= iter.data.length;
}
/**
* @dev Moves the iterator to the next resource record.
* @param iter The iterator to advance.
*/
function next(RRIterator memory iter) internal pure {
iter.offset = iter.nextOffset;
if (iter.offset >= iter.data.length) {
return;
}
// Skip the name
uint off = iter.offset + nameLength(iter.data, iter.offset);
// Read type, class, and ttl
iter.dnstype = iter.data.readUint16(off);
off += 2;
iter.class = iter.data.readUint16(off);
off += 2;
iter.ttl = iter.data.readUint32(off);
off += 4;
// Read the rdata
uint rdataLength = iter.data.readUint16(off);
off += 2;
iter.rdataOffset = off;
iter.nextOffset = off + rdataLength;
}
/**
* @dev Returns the name of the current record.
* @param iter The iterator.
* @return A new bytes object containing the owner name from the RR.
*/
function name(RRIterator memory iter) internal pure returns(bytes memory) {
return iter.data.substring(iter.offset, nameLength(iter.data, iter.offset));
}
/**
* @dev Returns the rdata portion of the current record.
* @param iter The iterator.
* @return A new bytes object containing the RR's RDATA.
*/
function rdata(RRIterator memory iter) internal pure returns(bytes memory) {
return iter.data.substring(iter.rdataOffset, iter.nextOffset - iter.rdataOffset);
}
/**
* @dev Checks if a given RR type exists in a type bitmap.
* @param self The byte string to read the type bitmap from.
* @param offset The offset to start reading at.
* @param rrtype The RR type to check for.
* @return True if the type is found in the bitmap, false otherwise.
*/
function checkTypeBitmap(bytes memory self, uint offset, uint16 rrtype) internal pure returns (bool) {
uint8 typeWindow = uint8(rrtype >> 8);
uint8 windowByte = uint8((rrtype & 0xff) / 8);
uint8 windowBitmask = uint8(uint8(1) << (uint8(7) - uint8(rrtype & 0x7)));
for (uint off = offset; off < self.length;) {
uint8 window = self.readUint8(off);
uint8 len = self.readUint8(off + 1);
if (typeWindow < window) {
// We've gone past our window; it's not here.
return false;
} else if (typeWindow == window) {
// Check this type bitmap
if (len * 8 <= windowByte) {
// Our type is past the end of the bitmap
return false;
}
return (self.readUint8(off + windowByte + 2) & windowBitmask) != 0;
} else {
// Skip this type bitmap
off += len + 2;
}
}
return false;
}
function compareNames(bytes memory self, bytes memory other) internal pure returns (int) {
if (self.equals(other)) {
return 0;
}
uint off;
uint otheroff;
uint prevoff;
uint otherprevoff;
uint counts = labelCount(self, 0);
uint othercounts = labelCount(other, 0);
// Keep removing labels from the front of the name until both names are equal length
while (counts > othercounts) {
prevoff = off;
off = progress(self, off);
counts--;
}
while (othercounts > counts) {
otherprevoff = otheroff;
otheroff = progress(other, otheroff);
othercounts--;
}
// Compare the last nonequal labels to each other
while (counts > 0 && !self.equals(off, other, otheroff)) {
prevoff = off;
off = progress(self, off);
otherprevoff = otheroff;
otheroff = progress(other, otheroff);
counts -= 1;
}
if (off == 0) {
return -1;
}
if(otheroff == 0) {
return 1;
}
return self.compare(prevoff + 1, self.readUint8(prevoff), other, otherprevoff + 1, other.readUint8(otherprevoff));
}
function progress(bytes memory body, uint off) internal pure returns(uint) {
return off + 1 + body.readUint8(off);
}
}
pragma solidity ^0.5.0;
contract DNSResolver is ResolverBase {
using RRUtils for *;
using BytesUtils for bytes;
bytes4 constant private DNS_RECORD_INTERFACE_ID = 0xa8fa5682;
bytes4 constant private DNS_ZONE_INTERFACE_ID = 0x5c47637c;
// DNSRecordChanged is emitted whenever a given node/name/resource's RRSET is updated.
event DNSRecordChanged(bytes32 indexed node, bytes name, uint16 resource, bytes record);
// DNSRecordDeleted is emitted whenever a given node/name/resource's RRSET is deleted.
event DNSRecordDeleted(bytes32 indexed node, bytes name, uint16 resource);
// DNSZoneCleared is emitted whenever a given node's zone information is cleared.
event DNSZoneCleared(bytes32 indexed node);
// DNSZonehashChanged is emitted whenever a given node's zone hash is updated.
event DNSZonehashChanged(bytes32 indexed node, bytes lastzonehash, bytes zonehash);
// Zone hashes for the domains.
// A zone hash is an EIP-1577 content hash in binary format that should point to a
// resource containing a single zonefile.
// node => contenthash
mapping(bytes32=>bytes) private zonehashes;
// Version the mapping for each zone. This allows users who have lost
// track of their entries to effectively delete an entire zone by bumping
// the version number.
// node => version
mapping(bytes32=>uint256) private versions;
// The records themselves. Stored as binary RRSETs
// node => version => name => resource => data
mapping(bytes32=>mapping(uint256=>mapping(bytes32=>mapping(uint16=>bytes)))) private records;
// Count of number of entries for a given name. Required for DNS resolvers
// when resolving wildcards.
// node => version => name => number of records
mapping(bytes32=>mapping(uint256=>mapping(bytes32=>uint16))) private nameEntriesCount;
/**
* Set one or more DNS records. Records are supplied in wire-format.
* Records with the same node/name/resource must be supplied one after the
* other to ensure the data is updated correctly. For example, if the data
* was supplied:
* a.example.com IN A 1.2.3.4
* a.example.com IN A 5.6.7.8
* www.example.com IN CNAME a.example.com.
* then this would store the two A records for a.example.com correctly as a
* single RRSET, however if the data was supplied:
* a.example.com IN A 1.2.3.4
* www.example.com IN CNAME a.example.com.
* a.example.com IN A 5.6.7.8
* then this would store the first A record, the CNAME, then the second A
* record which would overwrite the first.
*
* @param node the namehash of the node for which to set the records
* @param data the DNS wire format records to set
*/
function setDNSRecords(bytes32 node, bytes calldata data) external authorised(node) {
uint16 resource = 0;
uint256 offset = 0;
bytes memory name;
bytes memory value;
bytes32 nameHash;
// Iterate over the data to add the resource records
for (RRUtils.RRIterator memory iter = data.iterateRRs(0); !iter.done(); iter.next()) {
if (resource == 0) {
resource = iter.dnstype;
name = iter.name();
nameHash = keccak256(abi.encodePacked(name));
value = bytes(iter.rdata());
} else {
bytes memory newName = iter.name();
if (resource != iter.dnstype || !name.equals(newName)) {
setDNSRRSet(node, name, resource, data, offset, iter.offset - offset, value.length == 0);
resource = iter.dnstype;
offset = iter.offset;
name = newName;
nameHash = keccak256(name);
value = bytes(iter.rdata());
}
}
}
if (name.length > 0) {
setDNSRRSet(node, name, resource, data, offset, data.length - offset, value.length == 0);
}
}
/**
* Obtain a DNS record.
* @param node the namehash of the node for which to fetch the record
* @param name the keccak-256 hash of the fully-qualified name for which to fetch the record
* @param resource the ID of the resource as per https://en.wikipedia.org/wiki/List_of_DNS_record_types
* @return the DNS record in wire format if present, otherwise empty
*/
function dnsRecord(bytes32 node, bytes32 name, uint16 resource) public view returns (bytes memory) {
return records[node][versions[node]][name][resource];
}
/**
* Check if a given node has records.
* @param node the namehash of the node for which to check the records
* @param name the namehash of the node for which to check the records
*/
function hasDNSRecords(bytes32 node, bytes32 name) public view returns (bool) {
return (nameEntriesCount[node][versions[node]][name] != 0);
}
/**
* Clear all information for a DNS zone.
* @param node the namehash of the node for which to clear the zone
*/
function clearDNSZone(bytes32 node) public authorised(node) {
versions[node]++;
emit DNSZoneCleared(node);
}
/**
* setZonehash sets the hash for the zone.
* May only be called by the owner of that node in the ENS registry.
* @param node The node to update.
* @param hash The zonehash to set
*/
function setZonehash(bytes32 node, bytes calldata hash) external authorised(node) {
bytes memory oldhash = zonehashes[node];
zonehashes[node] = hash;
emit DNSZonehashChanged(node, oldhash, hash);
}
/**
* zonehash obtains the hash for the zone.
* @param node The ENS node to query.
* @return The associated contenthash.
*/
function zonehash(bytes32 node) external view returns (bytes memory) {
return zonehashes[node];
}
function supportsInterface(bytes4 interfaceID) public pure returns(bool) {
return interfaceID == DNS_RECORD_INTERFACE_ID ||
interfaceID == DNS_ZONE_INTERFACE_ID ||
super.supportsInterface(interfaceID);
}
function setDNSRRSet(
bytes32 node,
bytes memory name,
uint16 resource,
bytes memory data,
uint256 offset,
uint256 size,
bool deleteRecord) private
{
uint256 version = versions[node];
bytes32 nameHash = keccak256(name);
bytes memory rrData = data.substring(offset, size);
if (deleteRecord) {
if (records[node][version][nameHash][resource].length != 0) {
nameEntriesCount[node][version][nameHash]--;
}
delete(records[node][version][nameHash][resource]);
emit DNSRecordDeleted(node, name, resource);
} else {
if (records[node][version][nameHash][resource].length == 0) {
nameEntriesCount[node][version][nameHash]++;
}
records[node][version][nameHash][resource] = rrData;
emit DNSRecordChanged(node, name, resource, rrData);
}
}
}
pragma solidity ^0.5.0;
contract InterfaceResolver is ResolverBase, AddrResolver {
bytes4 constant private INTERFACE_INTERFACE_ID = bytes4(keccak256("interfaceImplementer(bytes32,bytes4)"));
bytes4 private constant INTERFACE_META_ID = 0x01ffc9a7;
event InterfaceChanged(bytes32 indexed node, bytes4 indexed interfaceID, address implementer);
mapping(bytes32=>mapping(bytes4=>address)) interfaces;
/**
* Sets an interface associated with a name.
* Setting the address to 0 restores the default behaviour of querying the contract at `addr()` for interface support.
* @param node The node to update.
* @param interfaceID The EIP 165 interface ID.
* @param implementer The address of a contract that implements this interface for this node.
*/
function setInterface(bytes32 node, bytes4 interfaceID, address implementer) external authorised(node) {
interfaces[node][interfaceID] = implementer;
emit InterfaceChanged(node, interfaceID, implementer);
}
/**
* Returns the address of a contract that implements the specified interface for this name.
* If an implementer has not been set for this interfaceID and name, the resolver will query
* the contract at `addr()`. If `addr()` is set, a contract exists at that address, and that
* contract implements EIP165 and returns `true` for the specified interfaceID, its address
* will be returned.
* @param node The ENS node to query.
* @param interfaceID The EIP 165 interface ID to check for.
* @return The address that implements this interface, or 0 if the interface is unsupported.
*/
function interfaceImplementer(bytes32 node, bytes4 interfaceID) external view returns (address) {
address implementer = interfaces[node][interfaceID];
if(implementer != address(0)) {
return implementer;
}
address a = addr(node);
if(a == address(0)) {
return address(0);
}
(bool success, bytes memory returnData) = a.staticcall(abi.encodeWithSignature("supportsInterface(bytes4)", INTERFACE_META_ID));
if(!success || returnData.length < 32 || returnData[31] == 0) {
// EIP 165 not supported by target
return address(0);
}
(success, returnData) = a.staticcall(abi.encodeWithSignature("supportsInterface(bytes4)", interfaceID));
if(!success || returnData.length < 32 || returnData[31] == 0) {
// Specified interface not supported by target
return address(0);
}
return a;
}
function supportsInterface(bytes4 interfaceID) public pure returns(bool) {
return interfaceID == INTERFACE_INTERFACE_ID || super.supportsInterface(interfaceID);
}
}
pragma solidity ^0.5.0;
contract NameResolver is ResolverBase {
bytes4 constant private NAME_INTERFACE_ID = 0x691f3431;
event NameChanged(bytes32 indexed node, string name);
mapping(bytes32=>string) names;
/**
* Sets the name associated with an ENS node, for reverse records.
* May only be called by the owner of that node in the ENS registry.
* @param node The node to update.
* @param name The name to set.
*/
function setName(bytes32 node, string calldata name) external authorised(node) {
names[node] = name;
emit NameChanged(node, name);
}
/**
* Returns the name associated with an ENS node, for reverse records.
* Defined in EIP181.
* @param node The ENS node to query.
* @return The associated name.
*/
function name(bytes32 node) external view returns (string memory) {
return names[node];
}
function supportsInterface(bytes4 interfaceID) public pure returns(bool) {
return interfaceID == NAME_INTERFACE_ID || super.supportsInterface(interfaceID);
}
}
pragma solidity ^0.5.0;
contract PubkeyResolver is ResolverBase {
bytes4 constant private PUBKEY_INTERFACE_ID = 0xc8690233;
event PubkeyChanged(bytes32 indexed node, bytes32 x, bytes32 y);
struct PublicKey {
bytes32 x;
bytes32 y;
}
mapping(bytes32=>PublicKey) pubkeys;
/**
* Sets the SECP256k1 public key associated with an ENS node.
* @param node The ENS node to query
* @param x the X coordinate of the curve point for the public key.
* @param y the Y coordinate of the curve point for the public key.
*/
function setPubkey(bytes32 node, bytes32 x, bytes32 y) external authorised(node) {
pubkeys[node] = PublicKey(x, y);
emit PubkeyChanged(node, x, y);
}
/**
* Returns the SECP256k1 public key associated with an ENS node.
* Defined in EIP 619.
* @param node The ENS node to query
* @return x, y the X and Y coordinates of the curve point for the public key.
*/
function pubkey(bytes32 node) external view returns (bytes32 x, bytes32 y) {
return (pubkeys[node].x, pubkeys[node].y);
}
function supportsInterface(bytes4 interfaceID) public pure returns(bool) {
return interfaceID == PUBKEY_INTERFACE_ID || super.supportsInterface(interfaceID);
}
}
pragma solidity ^0.5.0;
contract TextResolver is ResolverBase {
bytes4 constant private TEXT_INTERFACE_ID = 0x59d1d43c;
event TextChanged(bytes32 indexed node, string indexed indexedKey, string key);
mapping(bytes32=>mapping(string=>string)) texts;
/**
* Sets the text data associated with an ENS node and key.
* May only be called by the owner of that node in the ENS registry.
* @param node The node to update.
* @param key The key to set.
* @param value The text data value to set.
*/
function setText(bytes32 node, string calldata key, string calldata value) external authorised(node) {
texts[node][key] = value;
emit TextChanged(node, key, key);
}
/**
* Returns the text data associated with an ENS node and key.
* @param node The ENS node to query.
* @param key The text data key to query.
* @return The associated text data.
*/
function text(bytes32 node, string calldata key) external view returns (string memory) {
return texts[node][key];
}
function supportsInterface(bytes4 interfaceID) public pure returns(bool) {
return interfaceID == TEXT_INTERFACE_ID || super.supportsInterface(interfaceID);
}
}
pragma solidity ^0.5.0;
/**
* A simple resolver anyone can use; only allows the owner of a node to set its
* address.
*/
contract PublicResolver is ABIResolver, AddrResolver, ContentHashResolver, DNSResolver, InterfaceResolver, NameResolver, PubkeyResolver, TextResolver {
ENS ens;
/**
* A mapping of authorisations. An address that is authorised for a name
* may make any changes to the name that the owner could, but may not update
* the set of authorisations.
* (node, owner, caller) => isAuthorised
*/
mapping(bytes32=>mapping(address=>mapping(address=>bool))) public authorisations;
event AuthorisationChanged(bytes32 indexed node, address indexed owner, address indexed target, bool isAuthorised);
constructor(ENS _ens) public {
ens = _ens;
}
/**
* @dev Sets or clears an authorisation.
* Authorisations are specific to the caller. Any account can set an authorisation
* for any name, but the authorisation that is checked will be that of the
* current owner of a name. Thus, transferring a name effectively clears any
* existing authorisations, and new authorisations can be set in advance of
* an ownership transfer if desired.
*
* @param node The name to change the authorisation on.
* @param target The address that is to be authorised or deauthorised.
* @param isAuthorised True if the address should be authorised, or false if it should be deauthorised.
*/
function setAuthorisation(bytes32 node, address target, bool isAuthorised) external {
authorisations[node][msg.sender][target] = isAuthorised;
emit AuthorisationChanged(node, msg.sender, target, isAuthorised);
}
function isAuthorised(bytes32 node) internal view returns(bool) {
address owner = ens.owner(node);
return owner == msg.sender || authorisations[node][owner][msg.sender];
}
}
|
zonehash obtains the hash for the zone. node The ENS node to query. return The associated contenthash./
|
function zonehash(bytes32 node) external view returns (bytes memory) {
return zonehashes[node];
}
| 15,587 |
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.3;
import "./interfaces/IStakingFactory.sol";
import "./StakingRewards.sol";
import "./interfaces/IStakingRewards.sol";
/// @title StakingFactory, A contract where users can create their own staking pool
contract StakingFactory is IStakingFactory {
address[] private allPools;
mapping(address => bool) private isOurs;
/**
* @notice Caller creates a new StakingRewards pool and it gets added to this factory
* @param _stakingToken token address that needs to be staked to earn rewards
* @param _startBlock block number when rewards start
* @param _endBlock block number when rewards end
* @param _bufferBlocks no. of blocks after which owner can reclaim any unclaimed rewards
* @return listaddr address of newly created contract
*/
function createPool(
address _stakingToken,
uint256 _startBlock,
uint256 _endBlock,
uint256 _bufferBlocks
) external override returns (address listaddr) {
listaddr = address(
new StakingRewards(
_stakingToken,
_startBlock,
_endBlock,
_bufferBlocks
)
);
StakingRewards(listaddr).transferOwnership(msg.sender);
allPools.push(listaddr);
isOurs[listaddr] = true;
emit PoolCreated(msg.sender, listaddr);
}
/**
* @notice Checks if a address belongs to this contract' pools
*/
function ours(address _a) external view override returns (bool) {
return isOurs[_a];
}
/**
* @notice Returns no. of pools stored in contract
*/
function listCount() external view override returns (uint256) {
return allPools.length;
}
/**
* @notice Returns address of the pool located at given id
*/
function listAt(uint256 _idx) external view override returns (address) {
require(_idx < allPools.length, "Index exceeds list length");
return allPools[_idx];
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.3;
interface IStakingFactory {
event PoolCreated(address indexed sender, address indexed newPool);
function createPool(
address _stakingToken,
uint256 _startBlock,
uint256 _endBlock,
uint256 _bufferBlocks
) external returns (address);
function ours(address _a) external view returns (bool);
function listCount() external view returns (uint256);
function listAt(uint256 _idx) external view returns (address);
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.3;
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import "./interfaces/IStakingRewards.sol";
/// @title StakingRewards, A contract where users can stake a token X "stakingToken" and get Y..X..Z as rewards
/// @notice Based on https://github.com/sushiswap/sushiswap/blob/master/contracts/MasterChef.sol but better
contract StakingRewards is Ownable, ReentrancyGuard, IStakingRewards {
using SafeERC20 for IERC20;
using EnumerableSet for EnumerableSet.AddressSet;
modifier notStopped {
require(!isStopped, "Rewards have stopped");
_;
}
modifier onlyRewardsPeriod {
require(block.number < endBlock, "Rewards period ended");
_;
}
struct RewardInfo {
IERC20 rewardToken;
uint256 lastRewardBlock; // Last block number that reward token distribution occurs.
uint256 rewardPerBlock; // How many reward tokens to distribute per block.
uint256 totalRewards;
uint256 accTokenPerShare; // Accumulated token per share, times 1e18.
}
RewardInfo[] private rewardInfo;
IERC20 public immutable stakingToken; // token to be staked for rewards
uint256 public immutable startBlock; // block number when reward period starts
uint256 public endBlock; // block number when reward period ends
// how many blocks to wait after owner can reclaim unclaimed tokens
uint256 public immutable bufferBlocks;
// indicates that rewards have stopped forever and can't be extended anymore
// also means that owner recovered all unclaimed rewards after a certain amount of bufferBlocks has passed
// new users won't be able to deposit and everyone left can withdraw his/her stake
bool public isStopped;
mapping(address => uint256) private userAmount;
mapping(uint256 => mapping(address => uint256)) private rewardDebt; // rewardDebt[rewardId][user] = N
mapping(uint256 => mapping(address => uint256)) private rewardPaid; // rewardPaid[rewardId][user] = N
EnumerableSet.AddressSet private pooledTokens;
uint8 private constant MAX_POOLED_TOKENS = 5;
constructor(
address _stakingToken,
uint256 _startBlock,
uint256 _endBlock,
uint256 _bufferBlocks
) {
_startBlock = (_startBlock == 0) ? block.number : _startBlock;
require(
_endBlock > block.number && _endBlock > _startBlock,
"Invalid end block"
);
stakingToken = IERC20(_stakingToken);
startBlock = _startBlock;
endBlock = _endBlock;
bufferBlocks = _bufferBlocks;
}
/**
* @notice Caller deposits the staking token to start earning rewards
* @param _amount amount of staking token to deposit
*/
function deposit(uint256 _amount)
external
override
notStopped
nonReentrant
{
updateAllRewards();
uint256 _currentAmount = userAmount[msg.sender];
uint256 _balanceBefore = stakingToken.balanceOf(address(this));
stakingToken.safeTransferFrom(msg.sender, address(this), _amount);
_amount = stakingToken.balanceOf(address(this)) - _balanceBefore;
uint256 _newUserAmount = _currentAmount + _amount;
if (_currentAmount > 0) {
for (uint256 i = 0; i < rewardInfo.length; i++) {
RewardInfo memory _reward = rewardInfo[i];
uint256 _pending =
((_currentAmount * _reward.accTokenPerShare) / 1e18) -
rewardDebt[i][msg.sender];
rewardDebt[i][msg.sender] =
(_newUserAmount * _reward.accTokenPerShare) /
1e18;
rewardPaid[i][msg.sender] += _pending;
_reward.rewardToken.safeTransfer(msg.sender, _pending);
}
} else {
for (uint256 i = 0; i < rewardInfo.length; i++) {
RewardInfo memory _reward = rewardInfo[i];
rewardDebt[i][msg.sender] =
(_amount * _reward.accTokenPerShare) /
1e18;
}
}
userAmount[msg.sender] = _newUserAmount;
emit Deposit(msg.sender, _amount);
}
/**
* @notice Caller withdraws the staking token and its pending rewards, if any
* @param _amount amount of staking token to withdraw
*/
function withdraw(uint256 _amount) external override nonReentrant {
updateAllRewards();
uint256 _currentAmount = userAmount[msg.sender];
require(_currentAmount >= _amount, "withdraw: not good");
uint256 newUserAmount = _currentAmount - _amount;
if (!isStopped) {
for (uint256 i = 0; i < rewardInfo.length; i++) {
RewardInfo memory _reward = rewardInfo[i];
uint256 _pending =
((_currentAmount * _reward.accTokenPerShare) / 1e18) -
rewardDebt[i][msg.sender];
rewardDebt[i][msg.sender] =
(newUserAmount * _reward.accTokenPerShare) /
1e18;
rewardPaid[i][msg.sender] += _pending;
_reward.rewardToken.safeTransfer(msg.sender, _pending);
}
}
userAmount[msg.sender] = newUserAmount;
stakingToken.safeTransfer(msg.sender, _amount);
emit Withdraw(msg.sender, _amount);
}
/**
* @notice Caller withdraws tokens staked by user without caring about rewards
*/
function emergencyWithdraw() external override nonReentrant {
for (uint256 i = 0; i < rewardInfo.length; i++) {
rewardDebt[i][msg.sender] = 0;
}
stakingToken.safeTransfer(msg.sender, userAmount[msg.sender]);
userAmount[msg.sender] = 0;
emit EmergencyWithdraw(msg.sender, userAmount[msg.sender]);
}
/**
* @notice Caller claims its pending rewards without having to withdraw its stake
*/
function claimRewards() external override notStopped nonReentrant {
for (uint256 i = 0; i < rewardInfo.length; i++) _claimReward(i);
}
/**
* @notice Caller claims a single pending reward without having to withdraw its stake
* @dev _rid is the index of rewardInfo array
* @param _rid reward id
*/
function claimReward(uint256 _rid)
external
override
notStopped
nonReentrant
{
_claimReward(_rid);
}
/**
* @notice Adds a reward token to the pool, only contract owner can call this
* @param _rewardToken address of the ERC20 token
* @param _totalRewards amount of total rewards to distribute from startBlock to endBlock
*/
function add(IERC20 _rewardToken, uint256 _totalRewards)
external
override
nonReentrant
onlyOwner
onlyRewardsPeriod
{
require(rewardInfo.length < MAX_POOLED_TOKENS, "Pool is full");
_add(_rewardToken, _totalRewards);
}
/**
* @notice Adds multiple reward tokens to the pool in a single call, only contract owner can call this
* @param _rewardSettings array of struct composed of "IERC20 rewardToken" and "uint256 totalRewards"
*/
function addMulti(RewardSettings[] memory _rewardSettings)
external
override
nonReentrant
onlyOwner
onlyRewardsPeriod
{
require(
rewardInfo.length + _rewardSettings.length < MAX_POOLED_TOKENS,
"Pool is full"
);
for (uint8 i = 0; i < _rewardSettings.length; i++)
_add(
_rewardSettings[i].rewardToken,
_rewardSettings[i].totalRewards
);
}
/**
* @notice Owner can recover any ERC20 that's not the staking token neither a pooledToken
* @param _tokenAddress address of the ERC20 mistakenly sent to this contract
* @param _tokenAmount amount to recover
*/
function recoverERC20(address _tokenAddress, uint256 _tokenAmount)
external
override
onlyOwner
{
require(
_tokenAddress != address(stakingToken) &&
!pooledTokens.contains(_tokenAddress),
"Cannot recover"
);
IERC20(_tokenAddress).safeTransfer(msg.sender, _tokenAmount);
emit Recovered(_tokenAddress, _tokenAmount);
}
/**
* @notice Owner can recover rewards that's not been claimed after endBlock + bufferBlocks
* @dev Warning: it will set isStopped to true, so no more deposits, extensions or rewards claim but only withdrawals
*/
function recoverUnclaimedRewards() external override onlyOwner notStopped {
require(
block.number > endBlock + bufferBlocks,
"Not allowed to reclaim"
);
isStopped = true;
for (uint8 i = 0; i < rewardInfo.length; i++) {
IERC20 _token = IERC20(rewardInfo[i].rewardToken);
uint256 _amount = _token.balanceOf(address(this));
rewardInfo[i].lastRewardBlock = block.number;
_token.safeTransfer(msg.sender, _amount);
emit UnclaimedRecovered(address(_token), _amount);
}
}
/**
* @notice After a reward period has ended owner can decide to extend it by adding more rewards
* @dev totalRewards will be distributed from block.number to newEndBlock
* @param _newEndBlock block number when new rewards end
* @param _newTotalRewards array of new total rewards for each pooled token
*/
function extendRewards(
uint256 _newEndBlock,
uint256[] memory _newTotalRewards
) external override onlyOwner notStopped nonReentrant {
require(block.number > endBlock, "Rewards not ended");
require(_newEndBlock > block.number, "Invalid end block");
require(
_newTotalRewards.length == rewardInfo.length,
"Pool length mismatch"
);
for (uint8 i = 0; i < _newTotalRewards.length; i++) {
updateReward(i);
uint256 _balanceBefore =
IERC20(rewardInfo[i].rewardToken).balanceOf(address(this));
IERC20(rewardInfo[i].rewardToken).safeTransferFrom(
msg.sender,
address(this),
_newTotalRewards[i]
);
_newTotalRewards[i] =
IERC20(rewardInfo[i].rewardToken).balanceOf(address(this)) -
_balanceBefore;
uint256 _rewardPerBlock =
_newTotalRewards[i] / (_newEndBlock - block.number);
rewardInfo[i].rewardPerBlock = _rewardPerBlock;
rewardInfo[i].totalRewards += _newTotalRewards[i];
}
endBlock = _newEndBlock;
emit RewardsExtended(_newEndBlock);
}
/**
* @notice Gets the number of pooled reward tokens in contract
*/
function rewardsLength() external view override returns (uint256) {
return rewardInfo.length;
}
/**
* @notice Gets the amount of staked tokens for a given user
* @param _user address of given user
*/
function balanceOf(address _user) external view override returns (uint256) {
return userAmount[_user];
}
/**
* @notice Gets the total amount of staked tokens in contract
*/
function totalSupply() external view override returns (uint256) {
return stakingToken.balanceOf(address(this));
}
/**
* @notice Caller can see pending rewards for a given reward id and user
* @dev _rid is the index of rewardInfo array
* @param _rid reward id
* @param _user address of a user
* @return amount of pending rewards
*/
function getPendingRewards(uint256 _rid, address _user)
external
view
override
returns (uint256)
{
return _getPendingRewards(_rid, _user);
}
/**
* @notice Caller can see pending rewards for a given user
* @param _user address of a user
* @return array of struct containing rewardToken and pendingReward
*/
function getAllPendingRewards(address _user)
external
view
override
returns (PendingRewards[] memory)
{
PendingRewards[] memory _pendingRewards =
new PendingRewards[](rewardInfo.length);
for (uint8 i = 0; i < rewardInfo.length; i++) {
_pendingRewards[i] = PendingRewards({
rewardToken: rewardInfo[i].rewardToken,
pendingReward: _getPendingRewards(i, _user)
});
}
return _pendingRewards;
}
/**
* @notice Caller can see pending rewards for a given user
* @param _user address of a user
* @return array of struct containing rewardToken and pendingReward
*/
function earned(address _user)
external
view
override
returns (EarnedRewards[] memory)
{
EarnedRewards[] memory earnedRewards =
new EarnedRewards[](rewardInfo.length);
for (uint8 i = 0; i < rewardInfo.length; i++) {
earnedRewards[i] = EarnedRewards({
rewardToken: rewardInfo[i].rewardToken,
earnedReward: rewardPaid[i][_user] +
_getPendingRewards(i, _user)
});
}
return earnedRewards;
}
/**
* @notice Caller can see total rewards for every pooled token
* @return array of struct containing rewardToken and totalRewards
*/
function getRewardsForDuration()
external
view
override
returns (RewardSettings[] memory)
{
RewardSettings[] memory _rewardSettings =
new RewardSettings[](rewardInfo.length);
for (uint8 i = 0; i < rewardInfo.length; i++) {
_rewardSettings[i] = RewardSettings({
rewardToken: rewardInfo[i].rewardToken,
totalRewards: rewardInfo[i].totalRewards
});
}
return _rewardSettings;
}
/**
* @notice Update reward variables of the given pool to be up-to-date.
* @dev _rid is the index of rewardInfo array
* @param _rid reward id
*/
function updateReward(uint256 _rid) public {
RewardInfo storage _reward = rewardInfo[_rid];
if (block.number <= _reward.lastRewardBlock) {
return;
}
uint256 _lpSupply = stakingToken.balanceOf(address(this));
if (_lpSupply == 0) {
_reward.lastRewardBlock = block.number;
return;
}
uint256 _tokenReward = getMultiplier(_reward) * _reward.rewardPerBlock;
_reward.accTokenPerShare += (_tokenReward * 1e18) / _lpSupply;
_reward.lastRewardBlock = block.number;
}
/**
* @notice Mass updates reward variables
*/
function updateAllRewards() public {
uint256 _length = rewardInfo.length;
for (uint256 pid = 0; pid < _length; pid++) {
updateReward(pid);
}
}
/**
* @notice Gets the correct multiplier of rewardPerBlock for a given RewardInfo
*/
function getMultiplier(RewardInfo memory _reward)
internal
view
returns (uint256 _multiplier)
{
uint256 _lastBlock =
(block.number > endBlock) ? endBlock : block.number;
_multiplier = (_lastBlock > _reward.lastRewardBlock)
? _lastBlock - _reward.lastRewardBlock
: 0;
}
/**
* @notice Pending rewards for a given reward id and user
* @dev _rid is the index of rewardInfo array
* @param _rid reward id
* @param _user address of a user
* @return amount of pending rewards
*/
function _getPendingRewards(uint256 _rid, address _user)
internal
view
returns (uint256)
{
if (isStopped) return 0;
RewardInfo storage _reward = rewardInfo[_rid];
uint256 _amount = userAmount[_user];
uint256 _debt = rewardDebt[_rid][_user];
uint256 _rewardPerBlock = _reward.rewardPerBlock;
uint256 _accTokenPerShare = _reward.accTokenPerShare;
uint256 _lpSupply = stakingToken.balanceOf(address(this));
if (block.number > _reward.lastRewardBlock && _lpSupply != 0) {
uint256 reward = getMultiplier(_reward) * _rewardPerBlock;
_accTokenPerShare += ((reward * 1e18) / _lpSupply);
}
return ((_amount * _accTokenPerShare) / 1e18) - _debt;
}
/**
* @notice Adds a reward token to the rewards pool
* @param _rewardToken address of the ERC20 token
* @param _totalRewards amount of total rewards to distribute from startBlock to endBlock
*/
function _add(IERC20 _rewardToken, uint256 _totalRewards) internal {
require(
address(_rewardToken) != address(stakingToken),
"rewardToken = stakingToken"
);
require(!pooledTokens.contains(address(_rewardToken)), "pool exists");
uint256 _balanceBefore = _rewardToken.balanceOf(address(this));
_rewardToken.safeTransferFrom(msg.sender, address(this), _totalRewards);
_totalRewards = _rewardToken.balanceOf(address(this)) - _balanceBefore;
require(_totalRewards != 0, "No rewards");
uint256 _lastRewardBlock =
block.number > startBlock ? block.number : startBlock;
pooledTokens.add(address(_rewardToken));
uint256 _rewardPerBlock = _totalRewards / (endBlock - _lastRewardBlock);
rewardInfo.push(
RewardInfo({
rewardToken: _rewardToken,
rewardPerBlock: _rewardPerBlock,
totalRewards: _totalRewards,
lastRewardBlock: _lastRewardBlock,
accTokenPerShare: 0
})
);
}
/**
* @notice Caller claims a single pending reward without having to withdraw its stake
* @dev _rid is the index of rewardInfo array
* @param _rid reward id
*/
function _claimReward(uint256 _rid) internal {
updateReward(_rid);
uint256 _amount = userAmount[msg.sender];
uint256 _debt = rewardDebt[_rid][msg.sender];
RewardInfo memory _reward = rewardInfo[_rid];
uint256 pending = ((_amount * _reward.accTokenPerShare) / 1e18) - _debt;
rewardPaid[_rid][msg.sender] += pending;
rewardDebt[_rid][msg.sender] =
(_amount * _reward.accTokenPerShare) /
1e18;
_reward.rewardToken.safeTransfer(msg.sender, pending);
}
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.3;
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
struct RewardSettings {
IERC20 rewardToken;
uint256 totalRewards;
}
struct PendingRewards {
IERC20 rewardToken;
uint256 pendingReward;
}
struct EarnedRewards {
IERC20 rewardToken;
uint256 earnedReward;
}
interface IStakingRewards {
event Deposit(address indexed user, uint256 amount);
event Withdraw(address indexed user, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 amount);
event Recovered(address token, uint256 amount);
event UnclaimedRecovered(address token, uint256 amount);
event RewardsExtended(uint256 newEndBlock);
function deposit(uint256 _amount) external;
function withdraw(uint256 _amount) external;
function emergencyWithdraw() external;
function claimRewards() external;
function claimReward(uint256 _rid) external;
function add(IERC20 _rewardToken, uint256 _totalRewards) external;
function addMulti(RewardSettings[] memory _poolSettings) external;
function recoverERC20(address _tokenAddress, uint256 _tokenAmount) external;
function recoverUnclaimedRewards() external;
function extendRewards(
uint256 _newEndBlock,
uint256[] memory _newTotalRewards
) external;
function rewardsLength() external view returns (uint256);
function balanceOf(address _user) external view returns (uint256);
function totalSupply() external view returns (uint256);
function getPendingRewards(uint256 _rid, address _user)
external
view
returns (uint256);
function getAllPendingRewards(address _user)
external
view
returns (PendingRewards[] memory);
function getRewardsForDuration()
external
view
returns (RewardSettings[] memory);
function earned(address _user)
external
view
returns (EarnedRewards[] memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @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;
/**
* @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.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
|
Gets the correct multiplier of rewardPerBlock for a given RewardInfo/
|
function getMultiplier(RewardInfo memory _reward)
internal
view
returns (uint256 _multiplier)
{
uint256 _lastBlock =
(block.number > endBlock) ? endBlock : block.number;
_multiplier = (_lastBlock > _reward.lastRewardBlock)
? _lastBlock - _reward.lastRewardBlock
: 0;
}
| 10,130,576 |
./full_match/97/0x8B4032b71C804517D54878d78730c230F768Ad57/sources/tests/BSC ChainLinkTests/PW.sol
|
Return the contributor addresses/
|
function getContributors() public view returns (address[] memory) {
return contributors;
}
| 5,018,791 |
./full_match/8453/0x94E69ef94BE77b98BF22F54784F2151a5084A3AB/sources/contracts/CamelotRouter.sol
|
ADD LIQUIDITY create the pair if it doesn't exist yet
|
function _addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin
) internal returns (uint amountA, uint amountB) {
if (ICamelotFactory(factory).getPair(tokenA, tokenB) == address(0)) {
ICamelotFactory(factory).createPair(tokenA, tokenB);
}
(uint reserveA, uint reserveB) = UniswapV2Library.getReserves(factory, tokenA, tokenB);
if (reserveA == 0 && reserveB == 0) {
(amountA, amountB) = (amountADesired, amountBDesired);
uint amountBOptimal = UniswapV2Library.quote(amountADesired, reserveA, reserveB);
if (amountBOptimal <= amountBDesired) {
require(amountBOptimal >= amountBMin, 'CamelotRouter: INSUFFICIENT_B_AMOUNT');
(amountA, amountB) = (amountADesired, amountBOptimal);
uint amountAOptimal = UniswapV2Library.quote(amountBDesired, reserveB, reserveA);
assert(amountAOptimal <= amountADesired);
require(amountAOptimal >= amountAMin, 'CamelotRouter: INSUFFICIENT_A_AMOUNT');
(amountA, amountB) = (amountAOptimal, amountBDesired);
}
}
}
| 11,558,878 |
./full_match/42/0x8C541aaeca2fc4B7D24ac22148911d78E2866017/sources/localhost/OverPie/overpie.sol
|
_pie 是指defi token的合约,非 pie 的入口 _balancer 是指 defi token/weth 的合约地址 _minBalancerOut 是指从 balancer 里换出的 defi token 的最小值 _maxPrice 是指交换过程中 defi token 对 weth 的最大值 _profit 是最低的利润 _tokens 是 defi token 的构成 token 的列表 _amountOutMins 是 defi token 的每一种构成 token 换出的 eth 的最小值
|
function balancerToPie(
address _pie,
address _balancer,
uint256 _minBalancerOut,
uint256 _maxPrice,
uint256 _profit,
address[] calldata _tokens,
uint256[] calldata _amountOutMins
) public payable onlyOwner {
msg.sender.transfer(address(this).balance);
}
| 16,271,740 |
pragma solidity ^0.4.25;
/**
* @author wpzczbyqy <[email protected]>
* @title bytes32类型集合操作
* 提供bytes32集合类型操作,包括新增元素,删除元素,获取元素等
**/
library LibBytes32Set {
struct Bytes32Set {
bytes32[] values;
mapping(bytes32 => uint256) indexes;
}
/**
*@dev byte32集合是否包含某个元素
*@param set bytes32类型集合
*@param val 待验证的值
*@return bool 是否包含该元素,true 包含;false 不包含
**/
function contains(Bytes32Set storage set, bytes32 val) internal view returns (bool) {
return set.indexes[val] != 0;
}
/**
*@dev byte32集合,增加一个元素
*@param set bytes32类型集合
*@param val 待增加的值
*@return bool 是否成功添加了元素
**/
function add(Bytes32Set storage set, bytes32 val) internal view returns (bool) {
if(!contains(set, val)){
set.values.push(val);
set.indexes[val] = set.values.length;
return true;
}
return false;
}
/**
*@dev byte32集合,删除一个元素
*@param set bytes32类型集合
*@param val 待删除的值
*@return bool 是否成功删除了元素
**/
function remove(Bytes32Set storage set, bytes32 val) internal view returns (bool) {
uint256 valueIndex = set.indexes[val];
if(contains(set,val)){
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set.values.length - 1;
if(toDeleteIndex != lastIndex){
bytes32 lastValue = set.values[lastIndex];
set.values[toDeleteIndex] = lastValue;
set.indexes[lastValue] = valueIndex;
}
delete set.values[lastIndex];
delete set.indexes[val];
set.values.length--;
return true;
}
return false;
}
/**
*@dev 获取集合中的所有元素
*@param set bytes32类型集合
*@return bytes32[] 返回集合中的所有元素
**/
function getAll(Bytes32Set storage set) internal view returns (bytes32[] memory) {
return set.values;
}
/**
*@dev 获取集合中元素的数量
*@param set bytes32类型集合
*@return uint256 集合中元素数量
**/
function getSize(Bytes32Set storage set) internal view returns (uint256) {
return set.values.length;
}
/**
*@dev 某个元素在集合中的位置
*@param set bytes32类型集合
*@param val 待查找的值
*@return bool,uint256 是否存在此元素与该元素的位置
**/
function atPosition (Bytes32Set storage set, bytes32 val) internal view returns (bool, uint256) {
if(contains(set, val)){
return (true, set.indexes[val]-1);
}
return (false, 0);
}
/**
*@dev 根据索引获取集合中的元素
*@param set bytes32类型集合
*@param index 索引
*@return bytes32 查找到的元素
**/
function getByIndex(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
require(index < set.values.length,"Index: index out of bounds");
return set.values[index];
}
/**
*@dev 求两个集合的并集 a ∪ b
*@param set a bytes32类型集合
*@param set b bytes32类型集合
*@return bytes32[] 并集元素
**/
function union(Bytes32Set storage a, Bytes32Set storage b) internal view returns (bytes32[]){
if(b.values.length == 0){
return a.values;
}
bool isIn;
for(uint i = 0; i < b.values.length; i++){
isIn = contains(a, b.values[i]);
if(!isIn){
add(a, b.values[i]);
}
}
return a.values;
}
/**
*@dev 求两个集合的差 a - b
*@param set a bytes32类型集合
*@param set b bytes32类型集合
*@return bytes32[] 差集元素
**/
function relative(Bytes32Set storage a, Bytes32Set storage b) internal view returns (bytes32[]){
if(b.values.length == 0){
return a.values;
}
bool isIn;
for(uint i = 0; i < b.values.length; i++){
isIn = contains(a, b.values[i]);
if(isIn){
remove(a,b.values[i]);
}
}
return a.values;
}
/**
*@dev 求两个集合的交集 a ∩ b
*@param set a bytes32类型集合
*@param set b bytes32类型集合
*@return bytes32[] 交集元素
**/
function intersect(Bytes32Set storage a, Bytes32Set storage b) internal view returns (bytes32[]){
if(b.values.length == 0){
return ;
}
bool isIn;
for(uint i = 0; i < a.values.length; i++){
isIn = contains(b, a.values[i]);
if(!isIn){
remove(a,a.values[i]);
}
}
return a.values;
}
}
|
求两个集合的交集 a ∩ b set a bytes32类型集合 set b bytes32类型集合return bytes32[] 交集元素/
|
function intersect(Bytes32Set storage a, Bytes32Set storage b) internal view returns (bytes32[]){
if(b.values.length == 0){
return ;
}
bool isIn;
for(uint i = 0; i < a.values.length; i++){
isIn = contains(b, a.values[i]);
if(!isIn){
remove(a,a.values[i]);
}
}
return a.values;
}
| 12,743,647 |
./partial_match/1/0x8DbB99cc3721f5c9cc7c9E92Db260813cf78cdd3/sources/CertifiedPartners.sol
|
get keccak256 hash of string user User or Certified Partner identifier return keccak256 hash
|
function getUserBytes(string memory user) public pure returns (bytes32) {
return keccak256(abi.encode(user));
}
| 2,718,543 |
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
/*
Simple OTC Escrow contract to transfer tokens OTC
Inspired and forked from BadgerDAO
https://github.com/Badger-Finance/badger-system/blob/develop/contracts/badger-timelock/OtcEscrow.sol
*/
contract OtcEscrow {
using SafeERC20 for IERC20;
address public receivedToken;
address public sentToken;
address public recipient;
address public beneficiary;
uint256 public receivedAmount;
uint256 public sentAmount;
constructor(
address beneficiary_,
address recipient_,
address receivedToken_,
address sentToken_,
uint256 receivedAmount_,
uint256 sentAmount_
) {
beneficiary = beneficiary_;
recipient = recipient_;
receivedToken = receivedToken_;
sentToken = sentToken_;
receivedAmount = receivedAmount_;
sentAmount = sentAmount_;
}
modifier onlyApprovedParties() {
require(msg.sender == recipient || msg.sender == beneficiary);
_;
}
/// @dev Atomically trade specified amount of receivedToken for control over sentToken in vesting contract
/// @dev Either counterparty may execute swap if sufficient token approval is given by recipient
function swap() public onlyApprovedParties {
// Transfer expected receivedToken from beneficiary
IERC20(receivedToken).safeTransferFrom(
beneficiary,
recipient,
receivedAmount
);
// Transfer sentToken to beneficiary
IERC20(sentToken).safeTransfer(address(beneficiary), sentAmount);
}
/// @dev Return sentToken to Fei Protocol to revoke escrow deal
function revoke() external {
require(msg.sender == recipient, "onlyRecipient");
uint256 sentTokenBalance = IERC20(sentToken).balanceOf(address(this));
IERC20(sentToken).safeTransfer(recipient, sentTokenBalance);
}
function revokeReceivedToken() external onlyApprovedParties {
uint256 receivedTokenBalance = IERC20(receivedToken).balanceOf(
address(this)
);
IERC20(receivedToken).safeTransfer(beneficiary, receivedTokenBalance);
}
}
// 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.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 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);
}
}
}
}
|
Return sentToken to Fei Protocol to revoke escrow deal
|
function revoke() external {
require(msg.sender == recipient, "onlyRecipient");
uint256 sentTokenBalance = IERC20(sentToken).balanceOf(address(this));
IERC20(sentToken).safeTransfer(recipient, sentTokenBalance);
}
| 1,101,443 |
/* solhint-disable func-order */
pragma solidity ^0.4.24;
import "./BimodalLib.sol";
import "./MerkleVerifier.sol";
import "./SafeMath/SafeMathLib32.sol";
import "./SafeMath/SafeMathLib256.sol";
/**
* This library contains the challenge-response implementations of NOCUST.
*/
library ChallengeLib {
using SafeMathLib256 for uint256;
using SafeMathLib32 for uint32;
using BimodalLib for BimodalLib.Ledger;
// EVENTS
event ChallengeIssued(address indexed token, address indexed recipient, address indexed sender);
event StateUpdate(
address indexed token,
address indexed account,
uint256 indexed eon,
uint64 trail,
bytes32[] allotmentChain,
bytes32[] membershipChain,
uint256[] values,
uint256[2][3] lrDeltasPassiveMark,
bytes32 activeStateChecksum,
bytes32 passiveChecksum,
bytes32 r, bytes32 s, uint8 v
);
// Validation
function verifyProofOfExclusiveAccountBalanceAllotment(
BimodalLib.Ledger storage ledger,
ERC20 token,
address holder,
bytes32[2] activeStateChecksum_passiveTransfersRoot, // solhint-disable func-param-name-mixedcase
uint64 trail,
uint256[3] eonPassiveMark,
bytes32[] allotmentChain,
bytes32[] membershipChain,
uint256[] values,
uint256[2] LR // solhint-disable func-param-name-mixedcase
)
public
view
returns (bool)
{
BimodalLib.Checkpoint memory checkpoint = ledger.checkpoints[eonPassiveMark[0].mod(ledger.EONS_KEPT)];
require(eonPassiveMark[0] == checkpoint.eonNumber, 'r');
// activeStateChecksum is set to the account node.
activeStateChecksum_passiveTransfersRoot[0] = keccak256(abi.encodePacked(
keccak256(abi.encodePacked(address(this))),
keccak256(abi.encodePacked(token)),
keccak256(abi.encodePacked(holder)),
keccak256(abi.encodePacked(
activeStateChecksum_passiveTransfersRoot[1], // passiveTransfersRoot
eonPassiveMark[1],
eonPassiveMark[2])),
activeStateChecksum_passiveTransfersRoot[0] // activeStateChecksum
));
// the interval allotment is set to form the leaf
activeStateChecksum_passiveTransfersRoot[0] = keccak256(abi.encodePacked(
LR[0], activeStateChecksum_passiveTransfersRoot[0], LR[1]
));
// This calls the merkle verification procedure, which returns the
// checkpoint allotment size
uint64 tokenTrail = ledger.tokenToTrail[token];
LR[0] = MerkleVerifier.verifyProofOfExclusiveBalanceAllotment(
trail,
tokenTrail,
activeStateChecksum_passiveTransfersRoot[0],
checkpoint.merkleRoot,
allotmentChain,
membershipChain,
values,
LR);
// The previous allotment size of the target eon is reconstructed from the
// deposits and withdrawals performed so far and the current balance.
LR[1] = address(this).balance;
if (token != address(this)) {
require(
tokenTrail != 0,
't');
LR[1] = token.balanceOf(this);
}
// Credit back confirmed withdrawals that were performed since target eon
for (tokenTrail = 0; tokenTrail < ledger.EONS_KEPT; tokenTrail++) {
if (ledger.confirmedWithdrawals[token][tokenTrail].eon >= eonPassiveMark[0]) {
LR[1] = LR[1].add(ledger.confirmedWithdrawals[token][tokenTrail].amount);
}
}
// Debit deposits performed since target eon
for (tokenTrail = 0; tokenTrail < ledger.EONS_KEPT; tokenTrail++) {
if (ledger.deposits[token][tokenTrail].eon >= eonPassiveMark[0]) {
LR[1] = LR[1].sub(ledger.deposits[token][tokenTrail].amount);
}
}
// Debit withdrawals pending since prior eon
LR[1] = LR[1].sub(ledger.getPendingWithdrawalsAtEon(token, eonPassiveMark[0].sub(1)));
// Require that the reconstructed allotment matches the proof allotment
require(
LR[0] <= LR[1],
'b');
return true;
}
function verifyProofOfActiveStateUpdateAgreement(
ERC20 token,
address holder,
uint64 trail,
uint256 eon,
bytes32 txSetRoot,
uint256[2] deltas,
address attester,
bytes32 r,
bytes32 s,
uint8 v
)
public
view
returns (bytes32 checksum)
{
checksum = MerkleVerifier.activeStateUpdateChecksum(token, holder, trail, eon, txSetRoot, deltas);
require(attester == BimodalLib.signedMessageECRECOVER(checksum, r, s, v), 'A');
}
function verifyWithdrawalAuthorization(
ERC20 token,
address holder,
uint256 expiry,
uint256 amount,
address attester,
bytes32 r,
bytes32 s,
uint8 v
)
public
view
returns (bool)
{
bytes32 checksum = keccak256(abi.encodePacked(
keccak256(abi.encodePacked(address(this))),
keccak256(abi.encodePacked(token)),
keccak256(abi.encodePacked(holder)),
expiry,
amount));
require(attester == BimodalLib.signedMessageECRECOVER(checksum, r, s, v), 'a');
return true;
}
// Challenge Lifecycle Methods
/**
* This method increments the live challenge counter and emits and event
* containing the challenge index.
*/
function markChallengeLive(
BimodalLib.Ledger storage ledger,
ERC20 token,
address recipient,
address sender
)
private
{
require(ledger.currentEra() > ledger.BLOCKS_PER_EPOCH);
uint256 eon = ledger.currentEon();
BimodalLib.Checkpoint storage checkpoint = ledger.getOrCreateCheckpoint(eon, eon);
checkpoint.liveChallenges = checkpoint.liveChallenges.add(1);
emit ChallengeIssued(token, recipient, sender);
}
/**
* This method clears all the data in a Challenge structure and decrements the
* live challenge counter.
*/
function clearChallenge(
BimodalLib.Ledger storage ledger,
BimodalLib.Challenge storage challenge
)
private
{
BimodalLib.Checkpoint storage checkpoint = ledger.getOrCreateCheckpoint(
challenge.initialStateEon.add(1),
ledger.currentEon());
checkpoint.liveChallenges = checkpoint.liveChallenges.sub(1);
challenge.challengeType = BimodalLib.ChallengeType.NONE;
challenge.block = 0;
// challenge.initialStateEon = 0;
challenge.initialStateBalance = 0;
challenge.deltaHighestSpendings = 0;
challenge.deltaHighestGains = 0;
challenge.finalStateBalance = 0;
challenge.deliveredTxNonce = 0;
challenge.trailIdentifier = 0;
}
/**
* This method marks a challenge as having been successfully answered only if
* the response was provided in time.
*/
function markChallengeAnswered(
BimodalLib.Ledger storage ledger,
BimodalLib.Challenge storage challenge
)
private
{
uint256 eon = ledger.currentEon();
require(
challenge.challengeType != BimodalLib.ChallengeType.NONE &&
block.number.sub(challenge.block) < ledger.BLOCKS_PER_EPOCH &&
(
challenge.initialStateEon == eon.sub(1) ||
(challenge.initialStateEon == eon.sub(2) && ledger.currentEra() < ledger.BLOCKS_PER_EPOCH)
)
);
clearChallenge(ledger, challenge);
}
// ========================================================================
// ========================================================================
// ========================================================================
// ==================================== STATE UPDATE Challenge
// ========================================================================
// ========================================================================
// ========================================================================
/**
* This method initiates the fields of the Challenge struct to hold a state
* update challenge.
*/
function initStateUpdateChallenge(
BimodalLib.Ledger storage ledger,
ERC20 token,
uint256 owed,
uint256[2] spentGained,
uint64 trail
)
private
{
BimodalLib.Challenge storage challengeEntry = ledger.challengeBook[token][msg.sender][msg.sender];
require(challengeEntry.challengeType == BimodalLib.ChallengeType.NONE);
require(challengeEntry.initialStateEon < ledger.currentEon().sub(1));
challengeEntry.initialStateEon = ledger.currentEon().sub(1);
challengeEntry.initialStateBalance = owed;
challengeEntry.deltaHighestSpendings = spentGained[0];
challengeEntry.deltaHighestGains = spentGained[1];
challengeEntry.trailIdentifier = trail;
challengeEntry.challengeType = BimodalLib.ChallengeType.STATE_UPDATE;
challengeEntry.block = block.number;
markChallengeLive(ledger, token, msg.sender, msg.sender);
}
/**
* This method checks that the updated balance is at least as much as the
* expected balance.
*/
function checkStateUpdateBalance(
BimodalLib.Ledger storage ledger,
ERC20 token,
BimodalLib.Challenge storage challenge,
uint256[2] LR, // solhint-disable func-param-name-mixedcase
uint256[2] spentGained,
uint256 passivelyReceived
)
private
view
{
(uint256 deposits, uint256 withdrawals) = ledger.getCurrentEonDepositsWithdrawals(token, msg.sender);
uint256 incoming = spentGained[1] // actively received in commit chain
.add(deposits)
.add(passivelyReceived);
uint256 outgoing = spentGained[0] // actively spent in commit chain
.add(withdrawals);
// This verification is modified to permit underflow of expected balance
// since a client can choose to zero the `challenge.initialStateBalance`
require(
challenge.initialStateBalance
.add(incoming)
<=
LR[1].sub(LR[0]) // final balance allotment
.add(outgoing)
,
'B');
}
function challengeStateUpdateWithProofOfExclusiveBalanceAllotment(
BimodalLib.Ledger storage ledger,
ERC20 token,
bytes32[2] checksums,
uint64 trail,
bytes32[] allotmentChain,
bytes32[] membershipChain,
uint256[] value,
uint256[2][3] lrDeltasPassiveMark,
bytes32[3] rsTxSetRoot,
uint8 v
)
public
/* payable */
/* onlyWithFairReimbursement(ledger) */
{
uint256 previousEon = ledger.currentEon().sub(1);
address operator = ledger.operator;
// The hub must have committed to this state update
if (lrDeltasPassiveMark[1][0] != 0 || lrDeltasPassiveMark[1][1] != 0) {
verifyProofOfActiveStateUpdateAgreement(
token,
msg.sender,
trail,
previousEon,
rsTxSetRoot[2],
lrDeltasPassiveMark[1],
operator,
rsTxSetRoot[0], rsTxSetRoot[1], v);
}
initStateUpdateChallenge(
ledger,
token,
lrDeltasPassiveMark[0][1].sub(lrDeltasPassiveMark[0][0]),
lrDeltasPassiveMark[1],
trail);
// The initial state must have been ratified in the commitment
require(verifyProofOfExclusiveAccountBalanceAllotment(
ledger,
token,
msg.sender,
checksums,
trail,
[previousEon, lrDeltasPassiveMark[2][0], lrDeltasPassiveMark[2][1]],
allotmentChain,
membershipChain,
value,
lrDeltasPassiveMark[0]));
}
function challengeStateUpdateWithProofOfActiveStateUpdateAgreement(
BimodalLib.Ledger storage ledger,
ERC20 token,
bytes32 txSetRoot,
uint64 trail,
uint256[2] deltas,
bytes32 r,
bytes32 s,
uint8 v
)
public
/* payable */
/* TODO calculate exact addition */
/* onlyWithSkewedReimbursement(ledger, 25) */
{
// The hub must have committed to this transition
verifyProofOfActiveStateUpdateAgreement(
token,
msg.sender,
trail,
ledger.currentEon().sub(1),
txSetRoot,
deltas,
ledger.operator,
r, s, v);
initStateUpdateChallenge(ledger, token, 0, deltas, trail);
}
function answerStateUpdateChallenge(
BimodalLib.Ledger storage ledger,
ERC20 token,
address issuer,
bytes32[] allotmentChain,
bytes32[] membershipChain,
uint256[] values,
uint256[2][3] lrDeltasPassiveMark, // [ [L, R], Deltas ]
bytes32[6] rSrStxSetRootChecksum,
uint8[2] v
)
public
{
BimodalLib.Challenge storage challenge = ledger.challengeBook[token][issuer][issuer];
require(challenge.challengeType == BimodalLib.ChallengeType.STATE_UPDATE);
// Transition must have been approved by issuer
if (lrDeltasPassiveMark[1][0] != 0 || lrDeltasPassiveMark[1][1] != 0) {
rSrStxSetRootChecksum[0] = verifyProofOfActiveStateUpdateAgreement(
token,
issuer,
challenge.trailIdentifier,
challenge.initialStateEon,
rSrStxSetRootChecksum[4], // txSetRoot
lrDeltasPassiveMark[1], // deltas
issuer,
rSrStxSetRootChecksum[0], // R[0]
rSrStxSetRootChecksum[1], // S[0]
v[0]);
address operator = ledger.operator;
rSrStxSetRootChecksum[1] = verifyProofOfActiveStateUpdateAgreement(
token,
issuer,
challenge.trailIdentifier,
challenge.initialStateEon,
rSrStxSetRootChecksum[4], // txSetRoot
lrDeltasPassiveMark[1], // deltas
operator,
rSrStxSetRootChecksum[2], // R[1]
rSrStxSetRootChecksum[3], // S[1]
v[1]);
require(rSrStxSetRootChecksum[0] == rSrStxSetRootChecksum[1], 'u');
} else {
rSrStxSetRootChecksum[0] = bytes32(0);
}
// Transition has to be at least as recent as submitted one
require(
lrDeltasPassiveMark[1][0] >= challenge.deltaHighestSpendings &&
lrDeltasPassiveMark[1][1] >= challenge.deltaHighestGains,
'x');
// Transition has to have been properly applied
checkStateUpdateBalance(
ledger,
token,
challenge,
lrDeltasPassiveMark[0], // LR
lrDeltasPassiveMark[1], // deltas
lrDeltasPassiveMark[2][0]); // passive amount
// Truffle crashes when trying to interpret this event in some cases.
emit StateUpdate(
token,
issuer,
challenge.initialStateEon.add(1),
challenge.trailIdentifier,
allotmentChain,
membershipChain,
values,
lrDeltasPassiveMark,
rSrStxSetRootChecksum[0], // activeStateChecksum
rSrStxSetRootChecksum[5], // passiveAcceptChecksum
rSrStxSetRootChecksum[2], // R[1]
rSrStxSetRootChecksum[3], // S[1]
v[1]);
// Proof of stake must be ratified in the checkpoint
require(verifyProofOfExclusiveAccountBalanceAllotment(
ledger,
token,
issuer,
[rSrStxSetRootChecksum[0], rSrStxSetRootChecksum[5]], // activeStateChecksum, passiveAcceptChecksum
challenge.trailIdentifier,
[
challenge.initialStateEon.add(1), // eonNumber
lrDeltasPassiveMark[2][0], // passiveAmount
lrDeltasPassiveMark[2][1]
],
allotmentChain,
membershipChain,
values,
lrDeltasPassiveMark[0]), // LR
'c');
markChallengeAnswered(ledger, challenge);
}
// ========================================================================
// ========================================================================
// ========================================================================
// ==================================== ACTIVE DELIVERY Challenge
// ========================================================================
// ========================================================================
// ========================================================================
function initTransferDeliveryChallenge(
BimodalLib.Ledger storage ledger,
ERC20 token,
address sender,
address recipient,
uint256 amount,
uint256 txNonce,
uint64 trail
)
private
{
BimodalLib.Challenge storage challenge = ledger.challengeBook[token][recipient][sender];
require(challenge.challengeType == BimodalLib.ChallengeType.NONE);
require(challenge.initialStateEon < ledger.currentEon().sub(1));
challenge.challengeType = BimodalLib.ChallengeType.TRANSFER_DELIVERY;
challenge.initialStateEon = ledger.currentEon().sub(1);
challenge.deliveredTxNonce = txNonce;
challenge.block = block.number;
challenge.trailIdentifier = trail;
challenge.finalStateBalance = amount;
markChallengeLive(
ledger,
token,
recipient,
sender);
}
function challengeTransferDeliveryWithProofOfActiveStateUpdateAgreement(
BimodalLib.Ledger storage ledger,
ERC20 token,
address[2] SR, // solhint-disable func-param-name-mixedcase
uint256[2] nonceAmount,
uint64[3] trails,
bytes32[] chain,
uint256[2] deltas,
bytes32[3] rsTxSetRoot,
uint8 v
)
public
/* payable */
/* onlyWithFairReimbursement() */
{
require(msg.sender == SR[0] || msg.sender == SR[1], 'd');
// Require hub to have committed to transition
verifyProofOfActiveStateUpdateAgreement(
token,
SR[0],
trails[0],
ledger.currentEon().sub(1),
rsTxSetRoot[2],
deltas,
ledger.operator,
rsTxSetRoot[0], rsTxSetRoot[1], v);
rsTxSetRoot[0] = MerkleVerifier.transferChecksum(
SR[1],
nonceAmount[1], // amount
trails[2],
nonceAmount[0]); // nonce
// Require tx to exist in transition
require(MerkleVerifier.verifyProofOfMembership(
trails[1],
chain,
rsTxSetRoot[0], // transferChecksum
rsTxSetRoot[2]), // txSetRoot
'e');
initTransferDeliveryChallenge(
ledger,
token,
SR[0], // senderAddress
SR[1], // recipientAddress
nonceAmount[1], // amount
nonceAmount[0], // nonce
trails[2]); // recipientTrail
}
function answerTransferDeliveryChallengeWithProofOfActiveStateUpdateAgreement(
BimodalLib.Ledger storage ledger,
ERC20 token,
address[2] SR, // solhint-disable func-param-name-mixedcase
uint64 transferMembershipTrail,
bytes32[] allotmentChain,
bytes32[] membershipChain,
uint256[] values,
uint256[2][3] lrDeltasPassiveMark,
bytes32[2] txSetRootChecksum,
bytes32[] txChain
)
public
{
BimodalLib.Challenge storage challenge = ledger.challengeBook[token][SR[1]][SR[0]];
require(challenge.challengeType == BimodalLib.ChallengeType.TRANSFER_DELIVERY);
// Assert that the challenged transaction belongs to the transfer set
require(MerkleVerifier.verifyProofOfMembership(
transferMembershipTrail,
txChain,
MerkleVerifier.transferChecksum(
SR[0],
challenge.finalStateBalance, // amount
challenge.trailIdentifier, // recipient trail
challenge.deliveredTxNonce),
txSetRootChecksum[0])); // txSetRoot
// Require committed transition to include transfer
txSetRootChecksum[0] = MerkleVerifier.activeStateUpdateChecksum(
token,
SR[1],
challenge.trailIdentifier,
challenge.initialStateEon,
txSetRootChecksum[0], // txSetRoot
lrDeltasPassiveMark[1]); // Deltas
// Assert that this transition was used to update the recipient's stake
require(verifyProofOfExclusiveAccountBalanceAllotment(
ledger,
token,
SR[1], // recipient
txSetRootChecksum, // [activeStateChecksum, passiveChecksum]
challenge.trailIdentifier,
[
challenge.initialStateEon.add(1), // eonNumber
lrDeltasPassiveMark[2][0], // passiveAmount
lrDeltasPassiveMark[2][1] // passiveMark
],
allotmentChain,
membershipChain,
values,
lrDeltasPassiveMark[0])); // LR
markChallengeAnswered(ledger, challenge);
}
// ========================================================================
// ========================================================================
// ========================================================================
// ==================================== PASSIVE DELIVERY Challenge
// ========================================================================
// ========================================================================
// ========================================================================
function challengeTransferDeliveryWithProofOfPassiveStateUpdate(
BimodalLib.Ledger storage ledger,
ERC20 token,
address[2] SR, // solhint-disable func-param-name-mixedcase
bytes32[2] txSetRootChecksum,
uint64[3] senderTransferRecipientTrails,
bytes32[] allotmentChain,
bytes32[] membershipChain,
uint256[] values,
uint256[2][4] lrDeltasPassiveMarkDummyAmount,
bytes32[] transferMembershipChain
)
public
/* payable */
/* onlyWithFairReimbursement() */
{
require(msg.sender == SR[0] || msg.sender == SR[1], 'd');
lrDeltasPassiveMarkDummyAmount[3][0] = ledger.currentEon().sub(1); // previousEon
// Assert that the challenged transaction ends the transfer set
require(MerkleVerifier.verifyProofOfMembership(
senderTransferRecipientTrails[1], // transferMembershipTrail
transferMembershipChain,
MerkleVerifier.transferChecksum(
SR[1], // recipientAddress
lrDeltasPassiveMarkDummyAmount[3][1], // amount
senderTransferRecipientTrails[2], // recipientTrail
2 ** 256 - 1), // nonce
txSetRootChecksum[0]), // txSetRoot
'e');
// Require committed transition to include transfer
txSetRootChecksum[0] = MerkleVerifier.activeStateUpdateChecksum(
token,
SR[0], // senderAddress
senderTransferRecipientTrails[0], // senderTrail
lrDeltasPassiveMarkDummyAmount[3][0], // previousEon
txSetRootChecksum[0], // txSetRoot
lrDeltasPassiveMarkDummyAmount[1]); // Deltas
// Assert that this transition was used to update the sender's stake
require(verifyProofOfExclusiveAccountBalanceAllotment(
ledger,
token,
SR[0], // senderAddress
txSetRootChecksum, // [activeStateChecksum, passiveChecksum]
senderTransferRecipientTrails[0], // senderTrail
[
lrDeltasPassiveMarkDummyAmount[3][0].add(1), // eonNumber
lrDeltasPassiveMarkDummyAmount[2][0], // passiveAmount
lrDeltasPassiveMarkDummyAmount[2][1] // passiveMark
],
allotmentChain,
membershipChain,
values,
lrDeltasPassiveMarkDummyAmount[0])); // LR
initTransferDeliveryChallenge(
ledger,
token,
SR[0], // sender
SR[1], // recipient
lrDeltasPassiveMarkDummyAmount[3][1], // amount
uint256(keccak256(abi.encodePacked(lrDeltasPassiveMarkDummyAmount[2][1], uint256(2 ** 256 - 1)))), // mark (nonce)
senderTransferRecipientTrails[2]); // recipientTrail
}
function answerTransferDeliveryChallengeWithProofOfPassiveStateUpdate(
BimodalLib.Ledger storage ledger,
ERC20 token,
address[2] SR, // solhint-disable func-param-name-mixedcase
uint64 transferMembershipTrail,
bytes32[] allotmentChain,
bytes32[] membershipChain,
uint256[] values,
uint256[2][3] lrPassiveMarkPositionNonce,
bytes32[2] checksums,
bytes32[] txChainValues
)
public
{
BimodalLib.Challenge storage challenge = ledger.challengeBook[token][SR[1]][SR[0]];
require(challenge.challengeType == BimodalLib.ChallengeType.TRANSFER_DELIVERY);
require(
challenge.deliveredTxNonce ==
uint256(keccak256(abi.encodePacked(lrPassiveMarkPositionNonce[2][0], lrPassiveMarkPositionNonce[2][1])))
);
// Assert that the challenged transaction belongs to the passively delivered set
require(
MerkleVerifier.verifyProofOfPassiveDelivery(
transferMembershipTrail,
MerkleVerifier.transferChecksum( // node
SR[0], // sender
challenge.finalStateBalance, // amount
challenge.trailIdentifier, // recipient trail
challenge.deliveredTxNonce),
checksums[1], // passiveChecksum
txChainValues,
[lrPassiveMarkPositionNonce[2][0], lrPassiveMarkPositionNonce[2][0].add(challenge.finalStateBalance)])
<=
lrPassiveMarkPositionNonce[1][0]);
// Assert that this transition was used to update the recipient's stake
require(verifyProofOfExclusiveAccountBalanceAllotment(
ledger,
token,
SR[1], // recipient
checksums, // [activeStateChecksum, passiveChecksum]
challenge.trailIdentifier, // recipientTrail
[
challenge.initialStateEon.add(1), // eonNumber
lrPassiveMarkPositionNonce[1][0], // passiveAmount
lrPassiveMarkPositionNonce[1][1] // passiveMark
],
allotmentChain,
membershipChain,
values,
lrPassiveMarkPositionNonce[0])); // LR
markChallengeAnswered(ledger, challenge);
}
// ========================================================================
// ========================================================================
// ========================================================================
// ==================================== SWAP Challenge
// ========================================================================
// ========================================================================
// ========================================================================
function initSwapEnactmentChallenge(
BimodalLib.Ledger storage ledger,
ERC20[2] tokens,
uint256[4] updatedSpentGainedPassive,
uint256[4] sellBuyBalanceNonce,
uint64 recipientTrail
)
private
{
ERC20 conduit = ERC20(address(keccak256(abi.encodePacked(tokens[0], tokens[1]))));
BimodalLib.Challenge storage challenge = ledger.challengeBook[conduit][msg.sender][msg.sender];
require(challenge.challengeType == BimodalLib.ChallengeType.NONE);
require(challenge.initialStateEon < ledger.currentEon().sub(1));
challenge.initialStateEon = ledger.currentEon().sub(1);
challenge.deliveredTxNonce = sellBuyBalanceNonce[3];
challenge.challengeType = BimodalLib.ChallengeType.SWAP_ENACTMENT;
challenge.block = block.number;
challenge.trailIdentifier = recipientTrail;
challenge.deltaHighestSpendings = sellBuyBalanceNonce[0];
challenge.deltaHighestGains = sellBuyBalanceNonce[1];
(uint256 deposits, uint256 withdrawals) = ledger.getCurrentEonDepositsWithdrawals(tokens[0], msg.sender);
challenge.initialStateBalance =
sellBuyBalanceNonce[2] // allotment from eon e - 1
.add(updatedSpentGainedPassive[2]) // gained
.add(updatedSpentGainedPassive[3]) // passively delivered
.add(deposits)
.sub(updatedSpentGainedPassive[1]) // spent
.sub(withdrawals);
challenge.finalStateBalance = updatedSpentGainedPassive[0];
require(challenge.finalStateBalance >= challenge.initialStateBalance, 'd');
markChallengeLive(ledger, conduit, msg.sender, msg.sender);
}
function challengeSwapEnactmentWithProofOfActiveStateUpdateAgreement(
BimodalLib.Ledger storage ledger,
ERC20[2] tokens,
uint64[3] senderTransferRecipientTrails, // senderTransferRecipientTrails
bytes32[] allotmentChain,
bytes32[] membershipChain,
bytes32[] txChain,
uint256[] values,
uint256[2][3] lrDeltasPassiveMark,
uint256[4] sellBuyBalanceNonce,
bytes32[3] txSetRootChecksumDummy
)
public
/* payable */
/* onlyWithFairReimbursement() */
{
// Require swap to exist in transition
txSetRootChecksumDummy[2] = MerkleVerifier.swapOrderChecksum(
tokens,
senderTransferRecipientTrails[2],
sellBuyBalanceNonce[0], // sell
sellBuyBalanceNonce[1], // buy
sellBuyBalanceNonce[2], // balance
sellBuyBalanceNonce[3]); // nonce
require(MerkleVerifier.verifyProofOfMembership(
senderTransferRecipientTrails[1],
txChain,
txSetRootChecksumDummy[2], // swapOrderChecksum
txSetRootChecksumDummy[0]), // txSetRoot
'e');
uint256 previousEon = ledger.currentEon().sub(1);
// Require committed transition to include swap
txSetRootChecksumDummy[2] = MerkleVerifier.activeStateUpdateChecksum(
tokens[0],
msg.sender,
senderTransferRecipientTrails[0],
previousEon,
txSetRootChecksumDummy[0],
lrDeltasPassiveMark[1]); // deltas
uint256 updatedBalance = lrDeltasPassiveMark[0][1].sub(lrDeltasPassiveMark[0][0]);
// The state must have been ratified in the commitment
require(verifyProofOfExclusiveAccountBalanceAllotment(
ledger,
tokens[0],
msg.sender,
[txSetRootChecksumDummy[2], txSetRootChecksumDummy[1]], // [activeStateChecksum, passiveChecksum]
senderTransferRecipientTrails[0],
[
previousEon.add(1), // eonNumber
lrDeltasPassiveMark[2][0], // passiveAmount
lrDeltasPassiveMark[2][1] // passiveMark
],
allotmentChain,
membershipChain,
values,
lrDeltasPassiveMark[0])); // LR
initSwapEnactmentChallenge(
ledger,
tokens,
[
updatedBalance, // updated
lrDeltasPassiveMark[1][0], // spent
lrDeltasPassiveMark[1][1], // gained
lrDeltasPassiveMark[2][0]], // passiveAmount
sellBuyBalanceNonce,
senderTransferRecipientTrails[2]);
}
/**
* This method just calculates the total expected balance.
*/
function calculateSwapConsistencyBalance(
BimodalLib.Ledger storage ledger,
ERC20 token,
uint256[2] deltas,
uint256 passiveAmount,
uint256 balance
)
private
view
returns (uint256)
{
(uint256 deposits, uint256 withdrawals) = ledger.getCurrentEonDepositsWithdrawals(token, msg.sender);
return balance
.add(deltas[1]) // gained
.add(passiveAmount) // passively delivered
.add(deposits)
.sub(withdrawals)
.sub(deltas[0]); // spent
}
/**
* This method calculates the balance expected to be credited in return for that
* debited in another token according to the swapping price and is adjusted to
* ignore numerical errors up to 2 decimal places.
*/
function verifySwapConsistency(
BimodalLib.Ledger storage ledger,
ERC20[2] tokens,
BimodalLib.Challenge challenge,
uint256[2] LR, // solhint-disable func-param-name-mixedcase
uint256[2] deltas,
uint256 passiveAmount,
uint256 balance
)
private
view
returns (bool)
{
balance = calculateSwapConsistencyBalance(ledger, tokens[1], deltas, passiveAmount, balance);
require(LR[1].sub(LR[0]) >= balance);
uint256 taken = challenge.deltaHighestSpendings // sell amount
.sub(challenge.finalStateBalance.sub(challenge.initialStateBalance)); // refund
uint256 given = LR[1].sub(LR[0]) // recipient allotment
.sub(balance); // authorized allotment
return taken.mul(challenge.deltaHighestGains).div(100) >= challenge.deltaHighestSpendings.mul(given).div(100);
}
function answerSwapChallengeWithProofOfExclusiveBalanceAllotment(
BimodalLib.Ledger storage ledger,
ERC20[2] tokens,
address issuer,
uint64 transferMembershipTrail,
bytes32[] allotmentChain,
bytes32[] membershipChain,
bytes32[] txChain,
uint256[] values,
uint256[2][3] lrDeltasPassiveMark,
uint256 balance,
bytes32[3] txSetRootChecksumDummy
)
public
{
ERC20 conduit = ERC20(address(keccak256(abi.encodePacked(tokens[0], tokens[1]))));
BimodalLib.Challenge storage challenge = ledger.challengeBook[conduit][issuer][issuer];
require(challenge.challengeType == BimodalLib.ChallengeType.SWAP_ENACTMENT);
// Assert that the challenged swap belongs to the transition
txSetRootChecksumDummy[2] = MerkleVerifier.swapOrderChecksum(
tokens,
challenge.trailIdentifier, // recipient trail
challenge.deltaHighestSpendings, // sell amount
challenge.deltaHighestGains, // buy amount
balance, // starting balance
challenge.deliveredTxNonce);
require(MerkleVerifier.verifyProofOfMembership(
transferMembershipTrail,
txChain,
txSetRootChecksumDummy[2], // order checksum
txSetRootChecksumDummy[0]), 'M'); // txSetRoot
// Require committed transition to include swap
txSetRootChecksumDummy[2] = MerkleVerifier.activeStateUpdateChecksum(
tokens[1],
issuer,
challenge.trailIdentifier,
challenge.initialStateEon,
txSetRootChecksumDummy[0], // txSetRoot
lrDeltasPassiveMark[1]); // deltas
if (balance != 2 ** 256 - 1) {
require(verifySwapConsistency(
ledger,
tokens,
challenge,
lrDeltasPassiveMark[0],
lrDeltasPassiveMark[1],
lrDeltasPassiveMark[2][0],
balance),
'v');
}
// Assert that this transition was used to update the recipient's stake
require(verifyProofOfExclusiveAccountBalanceAllotment(
ledger,
tokens[1],
issuer,
[txSetRootChecksumDummy[2], txSetRootChecksumDummy[1]], // activeStateChecksum, passiveChecksum
challenge.trailIdentifier,
[challenge.initialStateEon.add(1), lrDeltasPassiveMark[2][0], lrDeltasPassiveMark[2][1]],
allotmentChain,
membershipChain,
values,
lrDeltasPassiveMark[0]), // LR
's');
markChallengeAnswered(ledger, challenge);
}
// ========================================================================
// ========================================================================
// ========================================================================
// ==================================== WITHDRAWAL Challenge
// ========================================================================
// ========================================================================
// ========================================================================
function slashWithdrawalWithProofOfMinimumAvailableBalance(
BimodalLib.Ledger storage ledger,
ERC20 token,
address withdrawer,
uint256[2] markerEonAvailable,
bytes32[2] rs,
uint8 v
)
public
returns (uint256[2] amounts)
{
uint256 latestEon = ledger.currentEon();
require(
latestEon < markerEonAvailable[0].add(3),
'm');
bytes32 checksum = keccak256(abi.encodePacked(
keccak256(abi.encodePacked(address(this))),
keccak256(abi.encodePacked(token)),
keccak256(abi.encodePacked(withdrawer)),
markerEonAvailable[0],
markerEonAvailable[1]
));
require(withdrawer == BimodalLib.signedMessageECRECOVER(checksum, rs[0], rs[1], v));
BimodalLib.Wallet storage entry = ledger.walletBook[token][withdrawer];
BimodalLib.Withdrawal[] storage withdrawals = entry.withdrawals;
for (uint32 i = 1; i <= withdrawals.length; i++) {
BimodalLib.Withdrawal storage withdrawal = withdrawals[withdrawals.length.sub(i)];
if (withdrawal.eon.add(1) < latestEon) {
break;
} else if (withdrawal.eon == latestEon.sub(1)) {
amounts[0] = amounts[0].add(withdrawal.amount);
} else if (withdrawal.eon == latestEon) {
amounts[1] = amounts[1].add(withdrawal.amount);
}
}
require(amounts[0].add(amounts[1]) > markerEonAvailable[1]);
withdrawals.length = withdrawals.length.sub(i.sub(1)); // i >= 1
if (amounts[1] > 0) {
ledger.deductFromRunningPendingWithdrawals(token, latestEon, latestEon, amounts[1]);
ledger.appendOperationToEonAccumulator(
latestEon,
token,
withdrawer,
BimodalLib.Operation.CANCELLATION,
amounts[1]);
}
if (amounts[0] > 0) {
ledger.deductFromRunningPendingWithdrawals(token, latestEon.sub(1), latestEon, amounts[0]);
ledger.appendOperationToEonAccumulator(
latestEon.sub(1),
token, withdrawer,
BimodalLib.Operation.CANCELLATION,
amounts[0]);
}
}
}
|
Assert that the challenged swap belongs to the transition Require committed transition to include swap
|
function answerSwapChallengeWithProofOfExclusiveBalanceAllotment(
BimodalLib.Ledger storage ledger,
ERC20[2] tokens,
address issuer,
uint64 transferMembershipTrail,
bytes32[] allotmentChain,
bytes32[] membershipChain,
bytes32[] txChain,
uint256[] values,
uint256[2][3] lrDeltasPassiveMark,
uint256 balance,
bytes32[3] txSetRootChecksumDummy
)
public
{
ERC20 conduit = ERC20(address(keccak256(abi.encodePacked(tokens[0], tokens[1]))));
BimodalLib.Challenge storage challenge = ledger.challengeBook[conduit][issuer][issuer];
require(challenge.challengeType == BimodalLib.ChallengeType.SWAP_ENACTMENT);
txSetRootChecksumDummy[2] = MerkleVerifier.swapOrderChecksum(
tokens,
challenge.deliveredTxNonce);
require(MerkleVerifier.verifyProofOfMembership(
transferMembershipTrail,
txChain,
txSetRootChecksumDummy[2] = MerkleVerifier.activeStateUpdateChecksum(
tokens[1],
issuer,
challenge.trailIdentifier,
challenge.initialStateEon,
if (balance != 2 ** 256 - 1) {
require(verifySwapConsistency(
ledger,
tokens,
challenge,
lrDeltasPassiveMark[0],
lrDeltasPassiveMark[1],
lrDeltasPassiveMark[2][0],
balance),
'v');
}
ledger,
tokens[1],
issuer,
challenge.trailIdentifier,
[challenge.initialStateEon.add(1), lrDeltasPassiveMark[2][0], lrDeltasPassiveMark[2][1]],
allotmentChain,
membershipChain,
values,
's');
markChallengeAnswered(ledger, challenge);
}
| 12,584,742 |
./full_match/80001/0x3707FA12Ce5d803b6598d3AD861FCF6c51ADfA5A/sources/contracts/Greeter.sol
|
Write function (requires a transaction to be called)
|
function setGreeting(string memory _greeting) public {
greeting = _greeting;
emit GreetingChanged(_greeting);
}
event GreetingChanged(string newGreeting);
| 5,654,638 |
pragma solidity ^0.4.24;
/**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0); // Solidity only automatically asserts when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
/**
* @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.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
}
/* Required code start */
contract MarketplaceProxy {
function calculatePlatformCommission(uint256 weiAmount) public view returns (uint256);
function payPlatformIncomingTransactionCommission(address clientAddress) public payable;
function payPlatformOutgoingTransactionCommission() public payable;
function isUserBlockedByContract(address contractAddress) public view returns (bool);
}
/* Required code end */
contract Deposit is Ownable {
using SafeMath for uint256;
struct ClientDeposit {
uint256 balance;
// We should reject incoming transactions on payable
// methods that not equals this variable
uint256 nextPaymentTotalAmount;
uint256 nextPaymentDepositCommission; // deposit commission stored on contract
uint256 nextPaymentPlatformCommission;
bool exists;
bool isBlocked;
}
mapping(address => ClientDeposit) public depositsMap;
/* Required code start */
MarketplaceProxy public mp;
event PlatformIncomingTransactionCommission(uint256 amount, address clientAddress);
event PlatformOutgoingTransactionCommission(uint256 amount);
event Blocked();
/* Required code end */
event DepositCommission(uint256 amount, address clientAddress);
constructor () public {
/* Required code start */
// NOTE: CHANGE ADDRESS ON PRODUCTION
mp = MarketplaceProxy(0x17b38d3779debcf1079506522e10284d3c6b0fef);
/* Required code end */
}
/**
* @dev Handles direct clients transactions
*/
function () public payable {
handleIncomingPayment(msg.sender, msg.value);
}
/**
* @dev Handles payment gateway transactions
* @param clientAddress when payment method is fiat money
*/
function fromPaymentGateway(address clientAddress) public payable {
handleIncomingPayment(clientAddress, msg.value);
}
/**
* @dev Send commission to marketplace and increases client balance
* @param clientAddress client wallet for deposit
* @param amount transaction value (msg.value)
*/
function handleIncomingPayment(address clientAddress, uint256 amount) private {
ClientDeposit storage clientDeposit = depositsMap[clientAddress];
require(clientDeposit.exists);
require(clientDeposit.nextPaymentTotalAmount == amount);
/* Required code start */
// Send all incoming eth if user blocked
if (mp.isUserBlockedByContract(address(this))) {
mp.payPlatformIncomingTransactionCommission.value(amount)(clientAddress);
emit Blocked();
} else {
mp.payPlatformIncomingTransactionCommission.value(clientDeposit.nextPaymentPlatformCommission)(clientAddress);
emit PlatformIncomingTransactionCommission(clientDeposit.nextPaymentPlatformCommission, clientAddress);
}
/* Required code end */
// Virtually add ETH to client deposit (sended ETH subtract platform and deposit commissions)
clientDeposit.balance += amount.sub(clientDeposit.nextPaymentPlatformCommission).sub(clientDeposit.nextPaymentDepositCommission);
emit DepositCommission(clientDeposit.nextPaymentDepositCommission, clientAddress);
}
/**
* @dev Owner can add ETH to contract without commission
*/
function addEth() public payable onlyOwner {
}
/**
* @dev Owner can transfer ETH from contract to address
* @param to address
* @param amount 18 decimals (wei)
*/
function transferEthTo(address to, uint256 amount) public onlyOwner {
require(address(this).balance > amount);
/* Required code start */
// Get commission amount from marketplace
uint256 commission = mp.calculatePlatformCommission(amount);
require(address(this).balance > amount.add(commission));
// Send commission to marketplace
mp.payPlatformOutgoingTransactionCommission.value(commission)();
emit PlatformOutgoingTransactionCommission(commission);
/* Required code end */
to.transfer(amount);
}
/**
* @dev Send client's balance to some address on claim
* @param from client address
* @param to send ETH on this address
* @param amount 18 decimals (wei)
*/
function claim(address from, address to, uint256 amount) public onlyOwner{
require(depositsMap[from].exists);
/* Required code start */
// Get commission amount from marketplace
uint256 commission = mp.calculatePlatformCommission(amount);
require(address(this).balance > amount.add(commission));
require(depositsMap[from].balance > amount);
// Send commission to marketplace
mp.payPlatformOutgoingTransactionCommission.value(commission)();
emit PlatformOutgoingTransactionCommission(commission);
/* Required code end */
// Virtually subtract amount from client deposit
depositsMap[from].balance -= amount;
to.transfer(amount);
}
/**
* @return bool, client exist or not
*/
function isClient(address clientAddress) public view onlyOwner returns(bool) {
return depositsMap[clientAddress].exists;
}
/**
* @dev Add new client to structure
* @param clientAddress wallet
* @param _nextPaymentTotalAmount reject next incoming payable transaction if it's amount not equal to this variable
* @param _nextPaymentDepositCommission deposit commission stored on contract
* @param _nextPaymentPlatformCommission marketplace commission to send
*/
function addClient(address clientAddress, uint256 _nextPaymentTotalAmount, uint256 _nextPaymentDepositCommission, uint256 _nextPaymentPlatformCommission) public onlyOwner {
require( (clientAddress != address(0)));
// Can be called only once for address
require(!depositsMap[clientAddress].exists);
// Add new element to structure
depositsMap[clientAddress] = ClientDeposit(
0, // balance
_nextPaymentTotalAmount, // nextPaymentTotalAmount
_nextPaymentDepositCommission, // nextPaymentDepositCommission
_nextPaymentPlatformCommission, // nextPaymentPlatformCommission
true, // exists
false // isBlocked
);
}
/**
* @return uint256 client balance
*/
function getClientBalance(address clientAddress) public view returns(uint256) {
return depositsMap[clientAddress].balance;
}
/**
* @dev Update client payment details
* @param clientAddress wallet
* @param _nextPaymentTotalAmount reject next incoming payable transaction if it's amount not equal to this variable
* @param _nextPaymentDepositCommission deposit commission stored on contract
* @param _nextPaymentPlatformCommission marketplace commission to send
*/
function repeatedPayment(address clientAddress, uint256 _nextPaymentTotalAmount, uint256 _nextPaymentDepositCommission, uint256 _nextPaymentPlatformCommission) public onlyOwner {
ClientDeposit storage clientDeposit = depositsMap[clientAddress];
require(clientAddress != address(0));
require(clientDeposit.exists);
clientDeposit.nextPaymentTotalAmount = _nextPaymentTotalAmount;
clientDeposit.nextPaymentDepositCommission = _nextPaymentDepositCommission;
clientDeposit.nextPaymentPlatformCommission = _nextPaymentPlatformCommission;
}
}
|
Handles direct clients transactions/
|
function () public payable {
handleIncomingPayment(msg.sender, msg.value);
}
| 12,808,409 |
pragma solidity ^0.5.16;
import "./CErc20.sol";
/**
* @title Compound's CErc20Immutable Contract
* @notice CTokens which wrap an EIP-20 underlying and are immutable
* @author Compound
*/
contract CErc20Immutable is CErc20 {
/**
* @notice Construct a new money market
* @param underlying_ The address of the underlying asset
* @param comptroller_ The address of the Comptroller
* @param interestRateModel_ The address of the interest rate model
* @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18
* @param name_ ERC-20 name of this token
* @param symbol_ ERC-20 symbol of this token
* @param decimals_ ERC-20 decimal precision of this token
* @param admin_ Address of the administrator of this token
*/
constructor(address underlying_,
ComptrollerInterface comptroller_,
InterestRateModel interestRateModel_,
uint initialExchangeRateMantissa_,
string memory name_,
string memory symbol_,
uint8 decimals_,
address payable admin_) public {
// Creator of the contract is admin during initialization
admin = msg.sender;
// Initialize the market
initialize(underlying_, comptroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_);
// Set the proper admin now that initialization is done
admin = admin_;
}
}
pragma solidity ^0.5.16;
import "./CToken.sol";
/**
* @title Compound's CErc20 Contract
* @notice CTokens which wrap an EIP-20 underlying
* @author Compound
*/
contract CErc20 is CToken, CErc20Interface {
/**
* @notice Initialize the new money market
* @param underlying_ The address of the underlying asset
* @param comptroller_ The address of the Comptroller
* @param interestRateModel_ The address of the interest rate model
* @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18
* @param name_ ERC-20 name of this token
* @param symbol_ ERC-20 symbol of this token
* @param decimals_ ERC-20 decimal precision of this token
*/
function initialize(address underlying_,
ComptrollerInterface comptroller_,
InterestRateModel interestRateModel_,
uint initialExchangeRateMantissa_,
string memory name_,
string memory symbol_,
uint8 decimals_) public {
// CToken initialize does the bulk of the work
super.initialize(comptroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_);
// Set underlying and sanity check it
underlying = underlying_;
EIP20Interface(underlying).totalSupply();
}
/*** User Interface ***/
/**
* @notice Sender supplies assets into the market and receives cTokens in exchange
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param mintAmount The amount of the underlying asset to supply
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function mint(uint mintAmount) external returns (uint) {
(uint err,) = mintInternal(mintAmount);
return err;
}
/**
* @notice Sender redeems cTokens in exchange for the underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemTokens The number of cTokens to redeem into underlying
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeem(uint redeemTokens) external returns (uint) {
return redeemInternal(redeemTokens);
}
/**
* @notice Sender redeems cTokens in exchange for a specified amount of underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemAmount The amount of underlying to redeem
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemUnderlying(uint redeemAmount) external returns (uint) {
return redeemUnderlyingInternal(redeemAmount);
}
/**
* @notice Sender borrows assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrow(uint borrowAmount) external returns (uint) {
return borrowInternal(borrowAmount);
}
/**
* @notice Sender repays their own borrow
* @param repayAmount The amount to repay
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function repayBorrow(uint repayAmount) external returns (uint) {
(uint err,) = repayBorrowInternal(repayAmount);
return err;
}
/**
* @notice Sender repays a borrow belonging to borrower
* @param borrower the account with the debt being payed off
* @param repayAmount The amount to repay
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint) {
(uint err,) = repayBorrowBehalfInternal(borrower, repayAmount);
return err;
}
/**
* @notice The sender liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this cToken to be liquidated
* @param repayAmount The amount of the underlying borrowed asset to repay
* @param cTokenCollateral The market in which to seize collateral from the borrower
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function liquidateBorrow(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) external returns (uint) {
(uint err,) = liquidateBorrowInternal(borrower, repayAmount, cTokenCollateral);
return err;
}
/**
* @notice The sender adds to reserves.
* @param addAmount The amount fo underlying token to add as reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _addReserves(uint addAmount) external returns (uint) {
return _addReservesInternal(addAmount);
}
/*** Safe Token ***/
/**
* @notice Gets balance of this contract in terms of the underlying
* @dev This excludes the value of the current message, if any
* @return The quantity of underlying tokens owned by this contract
*/
function getCashPrior() internal view returns (uint) {
EIP20Interface token = EIP20Interface(underlying);
return token.balanceOf(address(this));
}
/**
* @dev Similar to EIP20 transfer, except it handles a False result from `transferFrom` and reverts in that case.
* This will revert due to insufficient balance or insufficient allowance.
* This function returns the actual amount received,
* which may be less than `amount` if there is a fee attached to the transfer.
*
* Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value.
* See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
function doTransferIn(address from, uint amount) internal returns (uint) {
EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying);
uint balanceBefore = EIP20Interface(underlying).balanceOf(address(this));
token.transferFrom(from, address(this), amount);
bool success;
assembly {
switch returndatasize()
case 0 { // This is a non-standard ERC-20
success := not(0) // set success to true
}
case 32 { // This is a compliant ERC-20
returndatacopy(0, 0, 32)
success := mload(0) // Set `success = returndata` of external call
}
default { // This is an excessively non-compliant ERC-20, revert.
revert(0, 0)
}
}
require(success, "TOKEN_TRANSFER_IN_FAILED");
// Calculate the amount that was *actually* transferred
uint balanceAfter = EIP20Interface(underlying).balanceOf(address(this));
require(balanceAfter >= balanceBefore, "TOKEN_TRANSFER_IN_OVERFLOW");
return balanceAfter - balanceBefore; // underflow already checked above, just subtract
}
/**
* @dev Similar to EIP20 transfer, except it handles a False success from `transfer` and returns an explanatory
* error code rather than reverting. If caller has not called checked protocol's balance, this may revert due to
* insufficient cash held in this contract. If caller has checked protocol's balance prior to this call, and verified
* it is >= amount, this should not revert in normal conditions.
*
* Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value.
* See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
function doTransferOut(address payable to, uint amount) internal {
EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying);
token.transfer(to, amount);
bool success;
assembly {
switch returndatasize()
case 0 { // This is a non-standard ERC-20
success := not(0) // set success to true
}
case 32 { // This is a complaint ERC-20
returndatacopy(0, 0, 32)
success := mload(0) // Set `success = returndata` of external call
}
default { // This is an excessively non-compliant ERC-20, revert.
revert(0, 0)
}
}
require(success, "TOKEN_TRANSFER_OUT_FAILED");
}
}
pragma solidity ^0.5.16;
import "./ComptrollerInterface.sol";
import "./CTokenInterfaces.sol";
import "./ErrorReporter.sol";
import "./Exponential.sol";
import "./EIP20Interface.sol";
import "./EIP20NonStandardInterface.sol";
import "./InterestRateModel.sol";
/**
* @title Compound's CToken Contract
* @notice Abstract base for CTokens
* @author Compound
*/
contract CToken is CTokenInterface, Exponential, TokenErrorReporter {
/**
* @notice Initialize the money market
* @param comptroller_ The address of the Comptroller
* @param interestRateModel_ The address of the interest rate model
* @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18
* @param name_ EIP-20 name of this token
* @param symbol_ EIP-20 symbol of this token
* @param decimals_ EIP-20 decimal precision of this token
*/
function initialize(ComptrollerInterface comptroller_,
InterestRateModel interestRateModel_,
uint initialExchangeRateMantissa_,
string memory name_,
string memory symbol_,
uint8 decimals_) public {
require(msg.sender == admin, "only admin may initialize the market");
require(accrualBlockNumber == 0 && borrowIndex == 0, "market may only be initialized once");
// Set initial exchange rate
initialExchangeRateMantissa = initialExchangeRateMantissa_;
require(initialExchangeRateMantissa > 0, "initial exchange rate must be greater than zero.");
// Set the comptroller
uint err = _setComptroller(comptroller_);
require(err == uint(Error.NO_ERROR), "setting comptroller failed");
// Initialize block number and borrow index (block number mocks depend on comptroller being set)
accrualBlockNumber = getBlockNumber();
borrowIndex = mantissaOne;
// Set the interest rate model (depends on block number / borrow index)
err = _setInterestRateModelFresh(interestRateModel_);
require(err == uint(Error.NO_ERROR), "setting interest rate model failed");
name = name_;
symbol = symbol_;
decimals = decimals_;
// The counter starts true to prevent changing it from zero to non-zero (i.e. smaller cost/refund)
_notEntered = true;
}
/**
* @notice Transfer `tokens` tokens from `src` to `dst` by `spender`
* @dev Called by both `transfer` and `transferFrom` internally
* @param spender The address of the account performing the transfer
* @param src The address of the source account
* @param dst The address of the destination account
* @param tokens The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferTokens(address spender, address src, address dst, uint tokens) internal returns (uint) {
/* Fail if transfer not allowed */
uint allowed = comptroller.transferAllowed(address(this), src, dst, tokens);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.TRANSFER_COMPTROLLER_REJECTION, allowed);
}
/* Do not allow self-transfers */
if (src == dst) {
return fail(Error.BAD_INPUT, FailureInfo.TRANSFER_NOT_ALLOWED);
}
/* Get the allowance, infinite for the account owner */
uint startingAllowance = 0;
if (spender == src) {
startingAllowance = uint(-1);
} else {
startingAllowance = transferAllowances[src][spender];
}
/* Do the calculations, checking for {under,over}flow */
MathError mathErr;
uint allowanceNew;
uint srcTokensNew;
uint dstTokensNew;
(mathErr, allowanceNew) = subUInt(startingAllowance, tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ALLOWED);
}
(mathErr, srcTokensNew) = subUInt(accountTokens[src], tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ENOUGH);
}
(mathErr, dstTokensNew) = addUInt(accountTokens[dst], tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_TOO_MUCH);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
accountTokens[src] = srcTokensNew;
accountTokens[dst] = dstTokensNew;
/* Eat some of the allowance (if necessary) */
if (startingAllowance != uint(-1)) {
transferAllowances[src][spender] = allowanceNew;
}
/* We emit a Transfer event */
emit Transfer(src, dst, tokens);
comptroller.transferVerify(address(this), src, dst, tokens);
return uint(Error.NO_ERROR);
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 amount) external nonReentrant returns (bool) {
return transferTokens(msg.sender, msg.sender, dst, amount) == uint(Error.NO_ERROR);
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint256 amount) external nonReentrant returns (bool) {
return transferTokens(msg.sender, src, dst, amount) == uint(Error.NO_ERROR);
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool) {
address src = msg.sender;
transferAllowances[src][spender] = amount;
emit Approval(src, spender, amount);
return true;
}
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent (-1 means infinite)
*/
function allowance(address owner, address spender) external view returns (uint256) {
return transferAllowances[owner][spender];
}
/**
* @notice Get the token balance of the `owner`
* @param owner The address of the account to query
* @return The number of tokens owned by `owner`
*/
function balanceOf(address owner) external view returns (uint256) {
return accountTokens[owner];
}
/**
* @notice Get the underlying balance of the `owner`
* @dev This also accrues interest in a transaction
* @param owner The address of the account to query
* @return The amount of underlying owned by `owner`
*/
function balanceOfUnderlying(address owner) external returns (uint) {
Exp memory exchangeRate = Exp({mantissa: exchangeRateCurrent()});
(MathError mErr, uint balance) = mulScalarTruncate(exchangeRate, accountTokens[owner]);
require(mErr == MathError.NO_ERROR, "balance could not be calculated");
return balance;
}
/**
* @notice Get a snapshot of the account's balances, and the cached exchange rate
* @dev This is used by comptroller to more efficiently perform liquidity checks.
* @param account Address of the account to snapshot
* @return (possible error, token balance, borrow balance, exchange rate mantissa)
*/
function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint) {
uint cTokenBalance = accountTokens[account];
uint borrowBalance;
uint exchangeRateMantissa;
MathError mErr;
(mErr, borrowBalance) = borrowBalanceStoredInternal(account);
if (mErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0, 0, 0);
}
(mErr, exchangeRateMantissa) = exchangeRateStoredInternal();
if (mErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0, 0, 0);
}
return (uint(Error.NO_ERROR), cTokenBalance, borrowBalance, exchangeRateMantissa);
}
/**
* @dev Function to simply retrieve block number
* This exists mainly for inheriting test contracts to stub this result.
*/
function getBlockNumber() internal view returns (uint) {
return block.number;
}
/**
* @notice Returns the current per-block borrow interest rate for this cToken
* @return The borrow interest rate per block, scaled by 1e18
*/
function borrowRatePerBlock() external view returns (uint) {
return interestRateModel.getBorrowRate(getCashPrior(), totalBorrows, totalReserves);
}
/**
* @notice Returns the current per-block supply interest rate for this cToken
* @return The supply interest rate per block, scaled by 1e18
*/
function supplyRatePerBlock() external view returns (uint) {
return interestRateModel.getSupplyRate(getCashPrior(), totalBorrows, totalReserves, reserveFactorMantissa);
}
/**
* @notice Returns the current total borrows plus accrued interest
* @return The total borrows with interest
*/
function totalBorrowsCurrent() external nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return totalBorrows;
}
/**
* @notice Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex
* @param account The address whose balance should be calculated after updating borrowIndex
* @return The calculated balance
*/
function borrowBalanceCurrent(address account) external nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return borrowBalanceStored(account);
}
/**
* @notice Return the borrow balance of account based on stored data
* @param account The address whose balance should be calculated
* @return The calculated balance
*/
function borrowBalanceStored(address account) public view returns (uint) {
(MathError err, uint result) = borrowBalanceStoredInternal(account);
require(err == MathError.NO_ERROR, "borrowBalanceStored: borrowBalanceStoredInternal failed");
return result;
}
/**
* @notice Return the borrow balance of account based on stored data
* @param account The address whose balance should be calculated
* @return (error code, the calculated balance or 0 if error code is non-zero)
*/
function borrowBalanceStoredInternal(address account) internal view returns (MathError, uint) {
/* Note: we do not assert that the market is up to date */
MathError mathErr;
uint principalTimesIndex;
uint result;
/* Get borrowBalance and borrowIndex */
BorrowSnapshot storage borrowSnapshot = accountBorrows[account];
/* If borrowBalance = 0 then borrowIndex is likely also 0.
* Rather than failing the calculation with a division by 0, we immediately return 0 in this case.
*/
if (borrowSnapshot.principal == 0) {
return (MathError.NO_ERROR, 0);
}
/* Calculate new borrow balance using the interest index:
* recentBorrowBalance = borrower.borrowBalance * market.borrowIndex / borrower.borrowIndex
*/
(mathErr, principalTimesIndex) = mulUInt(borrowSnapshot.principal, borrowIndex);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
(mathErr, result) = divUInt(principalTimesIndex, borrowSnapshot.interestIndex);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
return (MathError.NO_ERROR, result);
}
/**
* @notice Accrue interest then return the up-to-date exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateCurrent() public nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return exchangeRateStored();
}
/**
* @notice Calculates the exchange rate from the underlying to the CToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateStored() public view returns (uint) {
(MathError err, uint result) = exchangeRateStoredInternal();
require(err == MathError.NO_ERROR, "exchangeRateStored: exchangeRateStoredInternal failed");
return result;
}
/**
* @notice Calculates the exchange rate from the underlying to the CToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return (error code, calculated exchange rate scaled by 1e18)
*/
function exchangeRateStoredInternal() internal view returns (MathError, uint) {
uint _totalSupply = totalSupply;
if (_totalSupply == 0) {
/*
* If there are no tokens minted:
* exchangeRate = initialExchangeRate
*/
return (MathError.NO_ERROR, initialExchangeRateMantissa);
} else {
/*
* Otherwise:
* exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply
*/
uint totalCash = getCashPrior();
uint cashPlusBorrowsMinusReserves;
Exp memory exchangeRate;
MathError mathErr;
(mathErr, cashPlusBorrowsMinusReserves) = addThenSubUInt(totalCash, totalBorrows, totalReserves);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
(mathErr, exchangeRate) = getExp(cashPlusBorrowsMinusReserves, _totalSupply);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
return (MathError.NO_ERROR, exchangeRate.mantissa);
}
}
/**
* @notice Get cash balance of this cToken in the underlying asset
* @return The quantity of underlying asset owned by this contract
*/
function getCash() external view returns (uint) {
return getCashPrior();
}
/**
* @notice Applies accrued interest to total borrows and reserves
* @dev This calculates interest accrued from the last checkpointed block
* up to the current block and writes new checkpoint to storage.
*/
function accrueInterest() public returns (uint) {
/* Remember the initial block number */
uint currentBlockNumber = getBlockNumber();
uint accrualBlockNumberPrior = accrualBlockNumber;
/* Short-circuit accumulating 0 interest */
if (accrualBlockNumberPrior == currentBlockNumber) {
return uint(Error.NO_ERROR);
}
/* Read the previous values out of storage */
uint cashPrior = getCashPrior();
uint borrowsPrior = totalBorrows;
uint reservesPrior = totalReserves;
uint borrowIndexPrior = borrowIndex;
/* Calculate the current borrow interest rate */
uint borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, borrowsPrior, reservesPrior);
require(borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate is absurdly high");
/* Calculate the number of blocks elapsed since the last accrual */
(MathError mathErr, uint blockDelta) = subUInt(currentBlockNumber, accrualBlockNumberPrior);
require(mathErr == MathError.NO_ERROR, "could not calculate block delta");
/*
* Calculate the interest accumulated into borrows and reserves and the new index:
* simpleInterestFactor = borrowRate * blockDelta
* interestAccumulated = simpleInterestFactor * totalBorrows
* totalBorrowsNew = interestAccumulated + totalBorrows
* totalReservesNew = interestAccumulated * reserveFactor + totalReserves
* borrowIndexNew = simpleInterestFactor * borrowIndex + borrowIndex
*/
Exp memory simpleInterestFactor;
uint interestAccumulated;
uint totalBorrowsNew;
uint totalReservesNew;
uint borrowIndexNew;
(mathErr, simpleInterestFactor) = mulScalar(Exp({mantissa: borrowRateMantissa}), blockDelta);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, interestAccumulated) = mulScalarTruncate(simpleInterestFactor, borrowsPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, totalBorrowsNew) = addUInt(interestAccumulated, borrowsPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, totalReservesNew) = mulScalarTruncateAddUInt(Exp({mantissa: reserveFactorMantissa}), interestAccumulated, reservesPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, borrowIndexNew) = mulScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, uint(mathErr));
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We write the previously calculated values into storage */
accrualBlockNumber = currentBlockNumber;
borrowIndex = borrowIndexNew;
totalBorrows = totalBorrowsNew;
totalReserves = totalReservesNew;
/* We emit an AccrueInterest event */
emit AccrueInterest(cashPrior, interestAccumulated, borrowIndexNew, totalBorrowsNew);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender supplies assets into the market and receives cTokens in exchange
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param mintAmount The amount of the underlying asset to supply
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.
*/
function mintInternal(uint mintAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.MINT_ACCRUE_INTEREST_FAILED), 0);
}
// mintFresh emits the actual Mint event if successful and logs on errors, so we don't need to
return mintFresh(msg.sender, mintAmount);
}
struct MintLocalVars {
Error err;
MathError mathErr;
uint exchangeRateMantissa;
uint mintTokens;
uint totalSupplyNew;
uint accountTokensNew;
uint actualMintAmount;
}
/**
* @notice User supplies assets into the market and receives cTokens in exchange
* @dev Assumes interest has already been accrued up to the current block
* @param minter The address of the account which is supplying the assets
* @param mintAmount The amount of the underlying asset to supply
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.
*/
function mintFresh(address minter, uint mintAmount) internal returns (uint, uint) {
/* Fail if mint not allowed */
uint allowed = comptroller.mintAllowed(address(this), minter, mintAmount);
if (allowed != 0) {
return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.MINT_COMPTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.MINT_FRESHNESS_CHECK), 0);
}
MintLocalVars memory vars;
(vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal();
if (vars.mathErr != MathError.NO_ERROR) {
return (failOpaque(Error.MATH_ERROR, FailureInfo.MINT_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr)), 0);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call `doTransferIn` for the minter and the mintAmount.
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* `doTransferIn` reverts if anything goes wrong, since we can't be sure if
* side-effects occurred. The function returns the amount actually transferred,
* in case of a fee. On success, the cToken holds an additional `actualMintAmount`
* of cash.
*/
vars.actualMintAmount = doTransferIn(minter, mintAmount);
/*
* We get the current exchange rate and calculate the number of cTokens to be minted:
* mintTokens = actualMintAmount / exchangeRate
*/
(vars.mathErr, vars.mintTokens) = divScalarByExpTruncate(vars.actualMintAmount, Exp({mantissa: vars.exchangeRateMantissa}));
require(vars.mathErr == MathError.NO_ERROR, "MINT_EXCHANGE_CALCULATION_FAILED");
/*
* We calculate the new total supply of cTokens and minter token balance, checking for overflow:
* totalSupplyNew = totalSupply + mintTokens
* accountTokensNew = accountTokens[minter] + mintTokens
*/
(vars.mathErr, vars.totalSupplyNew) = addUInt(totalSupply, vars.mintTokens);
require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED");
(vars.mathErr, vars.accountTokensNew) = addUInt(accountTokens[minter], vars.mintTokens);
require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED");
/* We write previously calculated values into storage */
totalSupply = vars.totalSupplyNew;
accountTokens[minter] = vars.accountTokensNew;
/* We emit a Mint event, and a Transfer event */
emit Mint(minter, vars.actualMintAmount, vars.mintTokens);
emit Transfer(address(this), minter, vars.mintTokens);
/* We call the defense hook */
comptroller.mintVerify(address(this), minter, vars.actualMintAmount, vars.mintTokens);
return (uint(Error.NO_ERROR), vars.actualMintAmount);
}
/**
* @notice Sender redeems cTokens in exchange for the underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemTokens The number of cTokens to redeem into underlying
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemInternal(uint redeemTokens) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed
return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED);
}
// redeemFresh emits redeem-specific logs on errors, so we don't need to
return redeemFresh(msg.sender, redeemTokens, 0);
}
/**
* @notice Sender redeems cTokens in exchange for a specified amount of underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemAmount The amount of underlying to receive from redeeming cTokens
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemUnderlyingInternal(uint redeemAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed
return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED);
}
// redeemFresh emits redeem-specific logs on errors, so we don't need to
return redeemFresh(msg.sender, 0, redeemAmount);
}
struct RedeemLocalVars {
Error err;
MathError mathErr;
uint exchangeRateMantissa;
uint redeemTokens;
uint redeemAmount;
uint totalSupplyNew;
uint accountTokensNew;
}
/**
* @notice User redeems cTokens in exchange for the underlying asset
* @dev Assumes interest has already been accrued up to the current block
* @param redeemer The address of the account which is redeeming the tokens
* @param redeemTokensIn The number of cTokens to redeem into underlying (only one of redeemTokensIn or redeemAmountIn may be non-zero)
* @param redeemAmountIn The number of underlying tokens to receive from redeeming cTokens (only one of redeemTokensIn or redeemAmountIn may be non-zero)
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemFresh(address payable redeemer, uint redeemTokensIn, uint redeemAmountIn) internal returns (uint) {
require(redeemTokensIn == 0 || redeemAmountIn == 0, "one of redeemTokensIn or redeemAmountIn must be zero");
RedeemLocalVars memory vars;
/* exchangeRate = invoke Exchange Rate Stored() */
(vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal();
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr));
}
/* If redeemTokensIn > 0: */
if (redeemTokensIn > 0) {
/*
* We calculate the exchange rate and the amount of underlying to be redeemed:
* redeemTokens = redeemTokensIn
* redeemAmount = redeemTokensIn x exchangeRateCurrent
*/
vars.redeemTokens = redeemTokensIn;
(vars.mathErr, vars.redeemAmount) = mulScalarTruncate(Exp({mantissa: vars.exchangeRateMantissa}), redeemTokensIn);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, uint(vars.mathErr));
}
} else {
/*
* We get the current exchange rate and calculate the amount to be redeemed:
* redeemTokens = redeemAmountIn / exchangeRate
* redeemAmount = redeemAmountIn
*/
(vars.mathErr, vars.redeemTokens) = divScalarByExpTruncate(redeemAmountIn, Exp({mantissa: vars.exchangeRateMantissa}));
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, uint(vars.mathErr));
}
vars.redeemAmount = redeemAmountIn;
}
/* Fail if redeem not allowed */
uint allowed = comptroller.redeemAllowed(address(this), redeemer, vars.redeemTokens);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REDEEM_COMPTROLLER_REJECTION, allowed);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDEEM_FRESHNESS_CHECK);
}
/*
* We calculate the new total supply and redeemer balance, checking for underflow:
* totalSupplyNew = totalSupply - redeemTokens
* accountTokensNew = accountTokens[redeemer] - redeemTokens
*/
(vars.mathErr, vars.totalSupplyNew) = subUInt(totalSupply, vars.redeemTokens);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.accountTokensNew) = subUInt(accountTokens[redeemer], vars.redeemTokens);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
/* Fail gracefully if protocol has insufficient cash */
if (getCashPrior() < vars.redeemAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We invoke doTransferOut for the redeemer and the redeemAmount.
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* On success, the cToken has redeemAmount less of cash.
* doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
*/
doTransferOut(redeemer, vars.redeemAmount);
/* We write previously calculated values into storage */
totalSupply = vars.totalSupplyNew;
accountTokens[redeemer] = vars.accountTokensNew;
/* We emit a Transfer event, and a Redeem event */
emit Transfer(redeemer, address(this), vars.redeemTokens);
emit Redeem(redeemer, vars.redeemAmount, vars.redeemTokens);
/* We call the defense hook */
comptroller.redeemVerify(address(this), redeemer, vars.redeemAmount, vars.redeemTokens);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender borrows assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrowInternal(uint borrowAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return fail(Error(error), FailureInfo.BORROW_ACCRUE_INTEREST_FAILED);
}
// borrowFresh emits borrow-specific logs on errors, so we don't need to
return borrowFresh(msg.sender, borrowAmount);
}
struct BorrowLocalVars {
MathError mathErr;
uint accountBorrows;
uint accountBorrowsNew;
uint totalBorrowsNew;
}
/**
* @notice Users borrow assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrowFresh(address payable borrower, uint borrowAmount) internal returns (uint) {
/* Fail if borrow not allowed */
uint allowed = comptroller.borrowAllowed(address(this), borrower, borrowAmount);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.BORROW_COMPTROLLER_REJECTION, allowed);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.BORROW_FRESHNESS_CHECK);
}
/* Fail gracefully if protocol has insufficient underlying cash */
if (getCashPrior() < borrowAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_CASH_NOT_AVAILABLE);
}
BorrowLocalVars memory vars;
/*
* We calculate the new borrower and total borrow balances, failing on overflow:
* accountBorrowsNew = accountBorrows + borrowAmount
* totalBorrowsNew = totalBorrows + borrowAmount
*/
(vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.accountBorrowsNew) = addUInt(vars.accountBorrows, borrowAmount);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.totalBorrowsNew) = addUInt(totalBorrows, borrowAmount);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We invoke doTransferOut for the borrower and the borrowAmount.
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* On success, the cToken borrowAmount less of cash.
* doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
*/
doTransferOut(borrower, borrowAmount);
/* We write the previously calculated values into storage */
accountBorrows[borrower].principal = vars.accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = vars.totalBorrowsNew;
/* We emit a Borrow event */
emit Borrow(borrower, borrowAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);
/* We call the defense hook */
comptroller.borrowVerify(address(this), borrower, borrowAmount);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender repays their own borrow
* @param repayAmount The amount to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowInternal(uint repayAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.REPAY_BORROW_ACCRUE_INTEREST_FAILED), 0);
}
// repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to
return repayBorrowFresh(msg.sender, msg.sender, repayAmount);
}
/**
* @notice Sender repays a borrow belonging to borrower
* @param borrower the account with the debt being payed off
* @param repayAmount The amount to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowBehalfInternal(address borrower, uint repayAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.REPAY_BEHALF_ACCRUE_INTEREST_FAILED), 0);
}
// repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to
return repayBorrowFresh(msg.sender, borrower, repayAmount);
}
struct RepayBorrowLocalVars {
Error err;
MathError mathErr;
uint repayAmount;
uint borrowerIndex;
uint accountBorrows;
uint accountBorrowsNew;
uint totalBorrowsNew;
uint actualRepayAmount;
}
/**
* @notice Borrows are repaid by another user (possibly the borrower).
* @param payer the account paying off the borrow
* @param borrower the account with the debt being payed off
* @param repayAmount the amount of undelrying tokens being returned
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowFresh(address payer, address borrower, uint repayAmount) internal returns (uint, uint) {
/* Fail if repayBorrow not allowed */
uint allowed = comptroller.repayBorrowAllowed(address(this), payer, borrower, repayAmount);
if (allowed != 0) {
return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REPAY_BORROW_COMPTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.REPAY_BORROW_FRESHNESS_CHECK), 0);
}
RepayBorrowLocalVars memory vars;
/* We remember the original borrowerIndex for verification purposes */
vars.borrowerIndex = accountBorrows[borrower].interestIndex;
/* We fetch the amount the borrower owes, with accumulated interest */
(vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower);
if (vars.mathErr != MathError.NO_ERROR) {
return (failOpaque(Error.MATH_ERROR, FailureInfo.REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)), 0);
}
/* If repayAmount == -1, repayAmount = accountBorrows */
if (repayAmount == uint(-1)) {
vars.repayAmount = vars.accountBorrows;
} else {
vars.repayAmount = repayAmount;
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call doTransferIn for the payer and the repayAmount
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* On success, the cToken holds an additional repayAmount of cash.
* doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred.
* it returns the amount actually transferred, in case of a fee.
*/
vars.actualRepayAmount = doTransferIn(payer, vars.repayAmount);
/*
* We calculate the new borrower and total borrow balances, failing on underflow:
* accountBorrowsNew = accountBorrows - actualRepayAmount
* totalBorrowsNew = totalBorrows - actualRepayAmount
*/
(vars.mathErr, vars.accountBorrowsNew) = subUInt(vars.accountBorrows, vars.actualRepayAmount);
require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED");
(vars.mathErr, vars.totalBorrowsNew) = subUInt(totalBorrows, vars.actualRepayAmount);
require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED");
/* We write the previously calculated values into storage */
accountBorrows[borrower].principal = vars.accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = vars.totalBorrowsNew;
/* We emit a RepayBorrow event */
emit RepayBorrow(payer, borrower, vars.actualRepayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);
/* We call the defense hook */
comptroller.repayBorrowVerify(address(this), payer, borrower, vars.actualRepayAmount, vars.borrowerIndex);
return (uint(Error.NO_ERROR), vars.actualRepayAmount);
}
/**
* @notice The sender liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this cToken to be liquidated
* @param cTokenCollateral The market in which to seize collateral from the borrower
* @param repayAmount The amount of the underlying borrowed asset to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function liquidateBorrowInternal(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed
return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED), 0);
}
error = cTokenCollateral.accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed
return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED), 0);
}
// liquidateBorrowFresh emits borrow-specific logs on errors, so we don't need to
return liquidateBorrowFresh(msg.sender, borrower, repayAmount, cTokenCollateral);
}
/**
* @notice The liquidator liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this cToken to be liquidated
* @param liquidator The address repaying the borrow and seizing collateral
* @param cTokenCollateral The market in which to seize collateral from the borrower
* @param repayAmount The amount of the underlying borrowed asset to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function liquidateBorrowFresh(address liquidator, address borrower, uint repayAmount, CTokenInterface cTokenCollateral) internal returns (uint, uint) {
/* Fail if liquidate not allowed */
uint allowed = comptroller.liquidateBorrowAllowed(address(this), address(cTokenCollateral), liquidator, borrower, repayAmount);
if (allowed != 0) {
return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_COMPTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_FRESHNESS_CHECK), 0);
}
/* Verify cTokenCollateral market's block number equals current block number */
if (cTokenCollateral.accrualBlockNumber() != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_COLLATERAL_FRESHNESS_CHECK), 0);
}
/* Fail if borrower = liquidator */
if (borrower == liquidator) {
return (fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_LIQUIDATOR_IS_BORROWER), 0);
}
/* Fail if repayAmount = 0 */
if (repayAmount == 0) {
return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_ZERO), 0);
}
/* Fail if repayAmount = -1 */
if (repayAmount == uint(-1)) {
return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX), 0);
}
/* Fail if repayBorrow fails */
(uint repayBorrowError, uint actualRepayAmount) = repayBorrowFresh(liquidator, borrower, repayAmount);
if (repayBorrowError != uint(Error.NO_ERROR)) {
return (fail(Error(repayBorrowError), FailureInfo.LIQUIDATE_REPAY_BORROW_FRESH_FAILED), 0);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We calculate the number of collateral tokens that will be seized */
(uint amountSeizeError, uint seizeTokens) = comptroller.liquidateCalculateSeizeTokens(address(this), address(cTokenCollateral), actualRepayAmount);
require(amountSeizeError == uint(Error.NO_ERROR), "LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED");
/* Revert if borrower collateral token balance < seizeTokens */
require(cTokenCollateral.balanceOf(borrower) >= seizeTokens, "LIQUIDATE_SEIZE_TOO_MUCH");
// If this is also the collateral, run seizeInternal to avoid re-entrancy, otherwise make an external call
uint seizeError;
if (address(cTokenCollateral) == address(this)) {
seizeError = seizeInternal(address(this), liquidator, borrower, seizeTokens);
} else {
seizeError = cTokenCollateral.seize(liquidator, borrower, seizeTokens);
}
/* Revert if seize tokens fails (since we cannot be sure of side effects) */
require(seizeError == uint(Error.NO_ERROR), "token seizure failed");
/* We emit a LiquidateBorrow event */
emit LiquidateBorrow(liquidator, borrower, actualRepayAmount, address(cTokenCollateral), seizeTokens);
/* We call the defense hook */
comptroller.liquidateBorrowVerify(address(this), address(cTokenCollateral), liquidator, borrower, actualRepayAmount, seizeTokens);
return (uint(Error.NO_ERROR), actualRepayAmount);
}
/**
* @notice Transfers collateral tokens (this market) to the liquidator.
* @dev Will fail unless called by another cToken during the process of liquidation.
* Its absolutely critical to use msg.sender as the borrowed cToken and not a parameter.
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of cTokens to seize
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function seize(address liquidator, address borrower, uint seizeTokens) external nonReentrant returns (uint) {
return seizeInternal(msg.sender, liquidator, borrower, seizeTokens);
}
/**
* @notice Transfers collateral tokens (this market) to the liquidator.
* @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another CToken.
* Its absolutely critical to use msg.sender as the seizer cToken and not a parameter.
* @param seizerToken The contract seizing the collateral (i.e. borrowed cToken)
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of cTokens to seize
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function seizeInternal(address seizerToken, address liquidator, address borrower, uint seizeTokens) internal returns (uint) {
/* Fail if seize not allowed */
uint allowed = comptroller.seizeAllowed(address(this), seizerToken, liquidator, borrower, seizeTokens);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_SEIZE_COMPTROLLER_REJECTION, allowed);
}
/* Fail if borrower = liquidator */
if (borrower == liquidator) {
return fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER);
}
MathError mathErr;
uint borrowerTokensNew;
uint liquidatorTokensNew;
/*
* We calculate the new borrower and liquidator token balances, failing on underflow/overflow:
* borrowerTokensNew = accountTokens[borrower] - seizeTokens
* liquidatorTokensNew = accountTokens[liquidator] + seizeTokens
*/
(mathErr, borrowerTokensNew) = subUInt(accountTokens[borrower], seizeTokens);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, uint(mathErr));
}
(mathErr, liquidatorTokensNew) = addUInt(accountTokens[liquidator], seizeTokens);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, uint(mathErr));
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We write the previously calculated values into storage */
accountTokens[borrower] = borrowerTokensNew;
accountTokens[liquidator] = liquidatorTokensNew;
/* Emit a Transfer event */
emit Transfer(borrower, liquidator, seizeTokens);
/* We call the defense hook */
comptroller.seizeVerify(address(this), seizerToken, liquidator, borrower, seizeTokens);
return uint(Error.NO_ERROR);
}
/*** Admin Functions ***/
/**
* @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @param newPendingAdmin New pending admin.
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setPendingAdmin(address payable newPendingAdmin) external returns (uint) {
// Check caller = admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK);
}
// Save current value, if any, for inclusion in log
address oldPendingAdmin = pendingAdmin;
// Store pendingAdmin with value newPendingAdmin
pendingAdmin = newPendingAdmin;
// Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin)
emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin);
return uint(Error.NO_ERROR);
}
/**
* @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin
* @dev Admin function for pending admin to accept role and update admin
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _acceptAdmin() external returns (uint) {
// Check caller is pendingAdmin and pendingAdmin ≠ address(0)
if (msg.sender != pendingAdmin || msg.sender == address(0)) {
return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK);
}
// Save current values for inclusion in log
address oldAdmin = admin;
address oldPendingAdmin = pendingAdmin;
// Store admin with value pendingAdmin
admin = pendingAdmin;
// Clear the pending value
pendingAdmin = address(0);
emit NewAdmin(oldAdmin, admin);
emit NewPendingAdmin(oldPendingAdmin, pendingAdmin);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets a new comptroller for the market
* @dev Admin function to set a new comptroller
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setComptroller(ComptrollerInterface newComptroller) public returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_COMPTROLLER_OWNER_CHECK);
}
ComptrollerInterface oldComptroller = comptroller;
// Ensure invoke comptroller.isComptroller() returns true
require(newComptroller.isComptroller(), "marker method returned false");
// Set market's comptroller to newComptroller
comptroller = newComptroller;
// Emit NewComptroller(oldComptroller, newComptroller)
emit NewComptroller(oldComptroller, newComptroller);
return uint(Error.NO_ERROR);
}
/**
* @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh
* @dev Admin function to accrue interest and set a new reserve factor
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setReserveFactor(uint newReserveFactorMantissa) external nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reserve factor change failed.
return fail(Error(error), FailureInfo.SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED);
}
// _setReserveFactorFresh emits reserve-factor-specific logs on errors, so we don't need to.
return _setReserveFactorFresh(newReserveFactorMantissa);
}
/**
* @notice Sets a new reserve factor for the protocol (*requires fresh interest accrual)
* @dev Admin function to set a new reserve factor
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setReserveFactorFresh(uint newReserveFactorMantissa) internal returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK);
}
// Verify market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_RESERVE_FACTOR_FRESH_CHECK);
}
// Check newReserveFactor ≤ maxReserveFactor
if (newReserveFactorMantissa > reserveFactorMaxMantissa) {
return fail(Error.BAD_INPUT, FailureInfo.SET_RESERVE_FACTOR_BOUNDS_CHECK);
}
uint oldReserveFactorMantissa = reserveFactorMantissa;
reserveFactorMantissa = newReserveFactorMantissa;
emit NewReserveFactor(oldReserveFactorMantissa, newReserveFactorMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Accrues interest and reduces reserves by transferring from msg.sender
* @param addAmount Amount of addition to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _addReservesInternal(uint addAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed.
return fail(Error(error), FailureInfo.ADD_RESERVES_ACCRUE_INTEREST_FAILED);
}
// _addReservesFresh emits reserve-addition-specific logs on errors, so we don't need to.
(error, ) = _addReservesFresh(addAmount);
return error;
}
/**
* @notice Add reserves by transferring from caller
* @dev Requires fresh interest accrual
* @param addAmount Amount of addition to reserves
* @return (uint, uint) An error code (0=success, otherwise a failure (see ErrorReporter.sol for details)) and the actual amount added, net token fees
*/
function _addReservesFresh(uint addAmount) internal returns (uint, uint) {
// totalReserves + actualAddAmount
uint totalReservesNew;
uint actualAddAmount;
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.ADD_RESERVES_FRESH_CHECK), actualAddAmount);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call doTransferIn for the caller and the addAmount
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* On success, the cToken holds an additional addAmount of cash.
* doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred.
* it returns the amount actually transferred, in case of a fee.
*/
actualAddAmount = doTransferIn(msg.sender, addAmount);
totalReservesNew = totalReserves + actualAddAmount;
/* Revert on overflow */
require(totalReservesNew >= totalReserves, "add reserves unexpected overflow");
// Store reserves[n+1] = reserves[n] + actualAddAmount
totalReserves = totalReservesNew;
/* Emit NewReserves(admin, actualAddAmount, reserves[n+1]) */
emit ReservesAdded(msg.sender, actualAddAmount, totalReservesNew);
/* Return (NO_ERROR, actualAddAmount) */
return (uint(Error.NO_ERROR), actualAddAmount);
}
/**
* @notice Accrues interest and reduces reserves by transferring to admin
* @param reduceAmount Amount of reduction to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _reduceReserves(uint reduceAmount) external nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed.
return fail(Error(error), FailureInfo.REDUCE_RESERVES_ACCRUE_INTEREST_FAILED);
}
// _reduceReservesFresh emits reserve-reduction-specific logs on errors, so we don't need to.
return _reduceReservesFresh(reduceAmount);
}
/**
* @notice Reduces reserves by transferring to admin
* @dev Requires fresh interest accrual
* @param reduceAmount Amount of reduction to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _reduceReservesFresh(uint reduceAmount) internal returns (uint) {
// totalReserves - reduceAmount
uint totalReservesNew;
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.REDUCE_RESERVES_ADMIN_CHECK);
}
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDUCE_RESERVES_FRESH_CHECK);
}
// Fail gracefully if protocol has insufficient underlying cash
if (getCashPrior() < reduceAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDUCE_RESERVES_CASH_NOT_AVAILABLE);
}
// Check reduceAmount ≤ reserves[n] (totalReserves)
if (reduceAmount > totalReserves) {
return fail(Error.BAD_INPUT, FailureInfo.REDUCE_RESERVES_VALIDATION);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
totalReservesNew = totalReserves - reduceAmount;
// We checked reduceAmount <= totalReserves above, so this should never revert.
require(totalReservesNew <= totalReserves, "reduce reserves unexpected underflow");
// Store reserves[n+1] = reserves[n] - reduceAmount
totalReserves = totalReservesNew;
// doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
doTransferOut(admin, reduceAmount);
emit ReservesReduced(admin, reduceAmount, totalReservesNew);
return uint(Error.NO_ERROR);
}
/**
* @notice accrues interest and updates the interest rate model using _setInterestRateModelFresh
* @dev Admin function to accrue interest and update the interest rate model
* @param newInterestRateModel the new interest rate model to use
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted change of interest rate model failed
return fail(Error(error), FailureInfo.SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED);
}
// _setInterestRateModelFresh emits interest-rate-model-update-specific logs on errors, so we don't need to.
return _setInterestRateModelFresh(newInterestRateModel);
}
/**
* @notice updates the interest rate model (*requires fresh interest accrual)
* @dev Admin function to update the interest rate model
* @param newInterestRateModel the new interest rate model to use
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setInterestRateModelFresh(InterestRateModel newInterestRateModel) internal returns (uint) {
// Used to store old model for use in the event that is emitted on success
InterestRateModel oldInterestRateModel;
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_INTEREST_RATE_MODEL_OWNER_CHECK);
}
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_INTEREST_RATE_MODEL_FRESH_CHECK);
}
// Track the market's current interest rate model
oldInterestRateModel = interestRateModel;
// Ensure invoke newInterestRateModel.isInterestRateModel() returns true
require(newInterestRateModel.isInterestRateModel(), "marker method returned false");
// Set the interest rate model to newInterestRateModel
interestRateModel = newInterestRateModel;
// Emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel)
emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel);
return uint(Error.NO_ERROR);
}
/*** Safe Token ***/
/**
* @notice Gets balance of this contract in terms of the underlying
* @dev This excludes the value of the current message, if any
* @return The quantity of underlying owned by this contract
*/
function getCashPrior() internal view returns (uint);
/**
* @dev Performs a transfer in, reverting upon failure. Returns the amount actually transferred to the protocol, in case of a fee.
* This may revert due to insufficient balance or insufficient allowance.
*/
function doTransferIn(address from, uint amount) internal returns (uint);
/**
* @dev Performs a transfer out, ideally returning an explanatory error code upon failure tather than reverting.
* If caller has not called checked protocol's balance, may revert due to insufficient cash held in the contract.
* If caller has checked protocol's balance, and verified it is >= amount, this should not revert in normal conditions.
*/
function doTransferOut(address payable to, uint amount) internal;
/*** Reentrancy Guard ***/
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
*/
modifier nonReentrant() {
require(_notEntered, "re-entered");
_notEntered = false;
_;
_notEntered = true; // get a gas-refund post-Istanbul
}
}
pragma solidity ^0.5.16;
contract ComptrollerInterface {
/// @notice Indicator that this is a Comptroller contract (for inspection)
bool public constant isComptroller = true;
/*** Assets You Are In ***/
function enterMarkets(address[] calldata cTokens) external returns (uint[] memory);
function exitMarket(address cToken) external returns (uint);
/*** Policy Hooks ***/
function mintAllowed(address cToken, address minter, uint mintAmount) external returns (uint);
function mintVerify(address cToken, address minter, uint mintAmount, uint mintTokens) external;
function redeemAllowed(address cToken, address redeemer, uint redeemTokens) external returns (uint);
function redeemVerify(address cToken, address redeemer, uint redeemAmount, uint redeemTokens) external;
function borrowAllowed(address cToken, address borrower, uint borrowAmount) external returns (uint);
function borrowVerify(address cToken, address borrower, uint borrowAmount) external;
function repayBorrowAllowed(
address cToken,
address payer,
address borrower,
uint repayAmount) external returns (uint);
function repayBorrowVerify(
address cToken,
address payer,
address borrower,
uint repayAmount,
uint borrowerIndex) external;
function liquidateBorrowAllowed(
address cTokenBorrowed,
address cTokenCollateral,
address liquidator,
address borrower,
uint repayAmount) external returns (uint);
function liquidateBorrowVerify(
address cTokenBorrowed,
address cTokenCollateral,
address liquidator,
address borrower,
uint repayAmount,
uint seizeTokens) external;
function seizeAllowed(
address cTokenCollateral,
address cTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external returns (uint);
function seizeVerify(
address cTokenCollateral,
address cTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external;
function transferAllowed(address cToken, address src, address dst, uint transferTokens) external returns (uint);
function transferVerify(address cToken, address src, address dst, uint transferTokens) external;
/*** Liquidity/Liquidation Calculations ***/
function liquidateCalculateSeizeTokens(
address cTokenBorrowed,
address cTokenCollateral,
uint repayAmount) external view returns (uint, uint);
}
pragma solidity ^0.5.16;
import "./ComptrollerInterface.sol";
import "./InterestRateModel.sol";
contract CTokenStorage {
/**
* @dev Guard variable for re-entrancy checks
*/
bool internal _notEntered;
/**
* @notice EIP-20 token name for this token
*/
string public name;
/**
* @notice EIP-20 token symbol for this token
*/
string public symbol;
/**
* @notice EIP-20 token decimals for this token
*/
uint8 public decimals;
/**
* @notice Maximum borrow rate that can ever be applied (.0005% / block)
*/
uint internal constant borrowRateMaxMantissa = 0.0005e16;
/**
* @notice Maximum fraction of interest that can be set aside for reserves
*/
uint internal constant reserveFactorMaxMantissa = 1e18;
/**
* @notice Administrator for this contract
*/
address payable public admin;
/**
* @notice Pending administrator for this contract
*/
address payable public pendingAdmin;
/**
* @notice Contract which oversees inter-cToken operations
*/
ComptrollerInterface public comptroller;
/**
* @notice Model which tells what the current interest rate should be
*/
InterestRateModel public interestRateModel;
/**
* @notice Initial exchange rate used when minting the first CTokens (used when totalSupply = 0)
*/
uint internal initialExchangeRateMantissa;
/**
* @notice Fraction of interest currently set aside for reserves
*/
uint public reserveFactorMantissa;
/**
* @notice Block number that interest was last accrued at
*/
uint public accrualBlockNumber;
/**
* @notice Accumulator of the total earned interest rate since the opening of the market
*/
uint public borrowIndex;
/**
* @notice Total amount of outstanding borrows of the underlying in this market
*/
uint public totalBorrows;
/**
* @notice Total amount of reserves of the underlying held in this market
*/
uint public totalReserves;
/**
* @notice Total number of tokens in circulation
*/
uint public totalSupply;
/**
* @notice Official record of token balances for each account
*/
mapping (address => uint) internal accountTokens;
/**
* @notice Approved token transfer amounts on behalf of others
*/
mapping (address => mapping (address => uint)) internal transferAllowances;
/**
* @notice Container for borrow balance information
* @member principal Total balance (with accrued interest), after applying the most recent balance-changing action
* @member interestIndex Global borrowIndex as of the most recent balance-changing action
*/
struct BorrowSnapshot {
uint principal;
uint interestIndex;
}
/**
* @notice Mapping of account addresses to outstanding borrow balances
*/
mapping(address => BorrowSnapshot) internal accountBorrows;
}
contract CTokenInterface is CTokenStorage {
/**
* @notice Indicator that this is a CToken contract (for inspection)
*/
bool public constant isCToken = true;
/*** Market Events ***/
/**
* @notice Event emitted when interest is accrued
*/
event AccrueInterest(uint cashPrior, uint interestAccumulated, uint borrowIndex, uint totalBorrows);
/**
* @notice Event emitted when tokens are minted
*/
event Mint(address minter, uint mintAmount, uint mintTokens);
/**
* @notice Event emitted when tokens are redeemed
*/
event Redeem(address redeemer, uint redeemAmount, uint redeemTokens);
/**
* @notice Event emitted when underlying is borrowed
*/
event Borrow(address borrower, uint borrowAmount, uint accountBorrows, uint totalBorrows);
/**
* @notice Event emitted when a borrow is repaid
*/
event RepayBorrow(address payer, address borrower, uint repayAmount, uint accountBorrows, uint totalBorrows);
/**
* @notice Event emitted when a borrow is liquidated
*/
event LiquidateBorrow(address liquidator, address borrower, uint repayAmount, address cTokenCollateral, uint seizeTokens);
/*** Admin Events ***/
/**
* @notice Event emitted when pendingAdmin is changed
*/
event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin);
/**
* @notice Event emitted when pendingAdmin is accepted, which means admin is updated
*/
event NewAdmin(address oldAdmin, address newAdmin);
/**
* @notice Event emitted when comptroller is changed
*/
event NewComptroller(ComptrollerInterface oldComptroller, ComptrollerInterface newComptroller);
/**
* @notice Event emitted when interestRateModel is changed
*/
event NewMarketInterestRateModel(InterestRateModel oldInterestRateModel, InterestRateModel newInterestRateModel);
/**
* @notice Event emitted when the reserve factor is changed
*/
event NewReserveFactor(uint oldReserveFactorMantissa, uint newReserveFactorMantissa);
/**
* @notice Event emitted when the reserves are added
*/
event ReservesAdded(address benefactor, uint addAmount, uint newTotalReserves);
/**
* @notice Event emitted when the reserves are reduced
*/
event ReservesReduced(address admin, uint reduceAmount, uint newTotalReserves);
/**
* @notice EIP20 Transfer event
*/
event Transfer(address indexed from, address indexed to, uint amount);
/**
* @notice EIP20 Approval event
*/
event Approval(address indexed owner, address indexed spender, uint amount);
/**
* @notice Failure event
*/
event Failure(uint error, uint info, uint detail);
/*** User Interface ***/
function transfer(address dst, uint amount) external returns (bool);
function transferFrom(address src, address dst, uint amount) external returns (bool);
function approve(address spender, uint amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function balanceOfUnderlying(address owner) external returns (uint);
function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint);
function borrowRatePerBlock() external view returns (uint);
function supplyRatePerBlock() external view returns (uint);
function totalBorrowsCurrent() external returns (uint);
function borrowBalanceCurrent(address account) external returns (uint);
function borrowBalanceStored(address account) public view returns (uint);
function exchangeRateCurrent() public returns (uint);
function exchangeRateStored() public view returns (uint);
function getCash() external view returns (uint);
function accrueInterest() public returns (uint);
function seize(address liquidator, address borrower, uint seizeTokens) external returns (uint);
/*** Admin Functions ***/
function _setPendingAdmin(address payable newPendingAdmin) external returns (uint);
function _acceptAdmin() external returns (uint);
function _setComptroller(ComptrollerInterface newComptroller) public returns (uint);
function _setReserveFactor(uint newReserveFactorMantissa) external returns (uint);
function _reduceReserves(uint reduceAmount) external returns (uint);
function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint);
}
contract CErc20Storage {
/**
* @notice Underlying asset for this CToken
*/
address public underlying;
}
contract CErc20Interface is CErc20Storage {
/*** User Interface ***/
function mint(uint mintAmount) external returns (uint);
function redeem(uint redeemTokens) external returns (uint);
function redeemUnderlying(uint redeemAmount) external returns (uint);
function borrow(uint borrowAmount) external returns (uint);
function repayBorrow(uint repayAmount) external returns (uint);
function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint);
function liquidateBorrow(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) external returns (uint);
/*** Admin Functions ***/
function _addReserves(uint addAmount) external returns (uint);
}
contract CDelegationStorage {
/**
* @notice Implementation address for this contract
*/
address public implementation;
}
contract CDelegatorInterface is CDelegationStorage {
/**
* @notice Emitted when implementation is changed
*/
event NewImplementation(address oldImplementation, address newImplementation);
/**
* @notice Called by the admin to update the implementation of the delegator
* @param implementation_ The address of the new implementation for delegation
* @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation
* @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation
*/
function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public;
}
contract CDelegateInterface is CDelegationStorage {
/**
* @notice Called by the delegator on a delegate to initialize it for duty
* @dev Should revert if any issues arise which make it unfit for delegation
* @param data The encoded bytes data for any initialization
*/
function _becomeImplementation(bytes memory data) public;
/**
* @notice Called by the delegator on a delegate to forfeit its responsibility
*/
function _resignImplementation() public;
}
pragma solidity ^0.5.16;
contract ComptrollerErrorReporter {
enum Error {
NO_ERROR,
UNAUTHORIZED,
COMPTROLLER_MISMATCH,
INSUFFICIENT_SHORTFALL,
INSUFFICIENT_LIQUIDITY,
INVALID_CLOSE_FACTOR,
INVALID_COLLATERAL_FACTOR,
INVALID_LIQUIDATION_INCENTIVE,
MARKET_NOT_ENTERED, // no longer possible
MARKET_NOT_LISTED,
MARKET_ALREADY_LISTED,
MATH_ERROR,
NONZERO_BORROW_BALANCE,
PRICE_ERROR,
REJECTION,
SNAPSHOT_ERROR,
TOO_MANY_ASSETS,
TOO_MUCH_REPAY
}
enum FailureInfo {
ACCEPT_ADMIN_PENDING_ADMIN_CHECK,
ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK,
EXIT_MARKET_BALANCE_OWED,
EXIT_MARKET_REJECTION,
SET_CLOSE_FACTOR_OWNER_CHECK,
SET_CLOSE_FACTOR_VALIDATION,
SET_COLLATERAL_FACTOR_OWNER_CHECK,
SET_COLLATERAL_FACTOR_NO_EXISTS,
SET_COLLATERAL_FACTOR_VALIDATION,
SET_COLLATERAL_FACTOR_WITHOUT_PRICE,
SET_IMPLEMENTATION_OWNER_CHECK,
SET_LIQUIDATION_INCENTIVE_OWNER_CHECK,
SET_LIQUIDATION_INCENTIVE_VALIDATION,
SET_MAX_ASSETS_OWNER_CHECK,
SET_PENDING_ADMIN_OWNER_CHECK,
SET_PENDING_IMPLEMENTATION_OWNER_CHECK,
SET_PRICE_ORACLE_OWNER_CHECK,
SUPPORT_MARKET_EXISTS,
SUPPORT_MARKET_OWNER_CHECK,
SET_PAUSE_GUARDIAN_OWNER_CHECK
}
/**
* @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary
* contract-specific code that enables us to report opaque error codes from upgradeable contracts.
**/
event Failure(uint error, uint info, uint detail);
/**
* @dev use this when reporting a known error from the money market or a non-upgradeable collaborator
*/
function fail(Error err, FailureInfo info) internal returns (uint) {
emit Failure(uint(err), uint(info), 0);
return uint(err);
}
/**
* @dev use this when reporting an opaque error from an upgradeable collaborator contract
*/
function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) {
emit Failure(uint(err), uint(info), opaqueError);
return uint(err);
}
}
contract TokenErrorReporter {
enum Error {
NO_ERROR,
UNAUTHORIZED,
BAD_INPUT,
COMPTROLLER_REJECTION,
COMPTROLLER_CALCULATION_ERROR,
INTEREST_RATE_MODEL_ERROR,
INVALID_ACCOUNT_PAIR,
INVALID_CLOSE_AMOUNT_REQUESTED,
INVALID_COLLATERAL_FACTOR,
MATH_ERROR,
MARKET_NOT_FRESH,
MARKET_NOT_LISTED,
TOKEN_INSUFFICIENT_ALLOWANCE,
TOKEN_INSUFFICIENT_BALANCE,
TOKEN_INSUFFICIENT_CASH,
TOKEN_TRANSFER_IN_FAILED,
TOKEN_TRANSFER_OUT_FAILED
}
/*
* Note: FailureInfo (but not Error) is kept in alphabetical order
* This is because FailureInfo grows significantly faster, and
* the order of Error has some meaning, while the order of FailureInfo
* is entirely arbitrary.
*/
enum FailureInfo {
ACCEPT_ADMIN_PENDING_ADMIN_CHECK,
ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED,
ACCRUE_INTEREST_BORROW_RATE_CALCULATION_FAILED,
ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED,
ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED,
ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED,
ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED,
BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED,
BORROW_ACCRUE_INTEREST_FAILED,
BORROW_CASH_NOT_AVAILABLE,
BORROW_FRESHNESS_CHECK,
BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED,
BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED,
BORROW_MARKET_NOT_LISTED,
BORROW_COMPTROLLER_REJECTION,
LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED,
LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED,
LIQUIDATE_COLLATERAL_FRESHNESS_CHECK,
LIQUIDATE_COMPTROLLER_REJECTION,
LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED,
LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX,
LIQUIDATE_CLOSE_AMOUNT_IS_ZERO,
LIQUIDATE_FRESHNESS_CHECK,
LIQUIDATE_LIQUIDATOR_IS_BORROWER,
LIQUIDATE_REPAY_BORROW_FRESH_FAILED,
LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED,
LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED,
LIQUIDATE_SEIZE_COMPTROLLER_REJECTION,
LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER,
LIQUIDATE_SEIZE_TOO_MUCH,
MINT_ACCRUE_INTEREST_FAILED,
MINT_COMPTROLLER_REJECTION,
MINT_EXCHANGE_CALCULATION_FAILED,
MINT_EXCHANGE_RATE_READ_FAILED,
MINT_FRESHNESS_CHECK,
MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED,
MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED,
MINT_TRANSFER_IN_FAILED,
MINT_TRANSFER_IN_NOT_POSSIBLE,
REDEEM_ACCRUE_INTEREST_FAILED,
REDEEM_COMPTROLLER_REJECTION,
REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED,
REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED,
REDEEM_EXCHANGE_RATE_READ_FAILED,
REDEEM_FRESHNESS_CHECK,
REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED,
REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED,
REDEEM_TRANSFER_OUT_NOT_POSSIBLE,
REDUCE_RESERVES_ACCRUE_INTEREST_FAILED,
REDUCE_RESERVES_ADMIN_CHECK,
REDUCE_RESERVES_CASH_NOT_AVAILABLE,
REDUCE_RESERVES_FRESH_CHECK,
REDUCE_RESERVES_VALIDATION,
REPAY_BEHALF_ACCRUE_INTEREST_FAILED,
REPAY_BORROW_ACCRUE_INTEREST_FAILED,
REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_COMPTROLLER_REJECTION,
REPAY_BORROW_FRESHNESS_CHECK,
REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE,
SET_COLLATERAL_FACTOR_OWNER_CHECK,
SET_COLLATERAL_FACTOR_VALIDATION,
SET_COMPTROLLER_OWNER_CHECK,
SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED,
SET_INTEREST_RATE_MODEL_FRESH_CHECK,
SET_INTEREST_RATE_MODEL_OWNER_CHECK,
SET_MAX_ASSETS_OWNER_CHECK,
SET_ORACLE_MARKET_NOT_LISTED,
SET_PENDING_ADMIN_OWNER_CHECK,
SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED,
SET_RESERVE_FACTOR_ADMIN_CHECK,
SET_RESERVE_FACTOR_FRESH_CHECK,
SET_RESERVE_FACTOR_BOUNDS_CHECK,
TRANSFER_COMPTROLLER_REJECTION,
TRANSFER_NOT_ALLOWED,
TRANSFER_NOT_ENOUGH,
TRANSFER_TOO_MUCH,
ADD_RESERVES_ACCRUE_INTEREST_FAILED,
ADD_RESERVES_FRESH_CHECK,
ADD_RESERVES_TRANSFER_IN_NOT_POSSIBLE
}
/**
* @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary
* contract-specific code that enables us to report opaque error codes from upgradeable contracts.
**/
event Failure(uint error, uint info, uint detail);
/**
* @dev use this when reporting a known error from the money market or a non-upgradeable collaborator
*/
function fail(Error err, FailureInfo info) internal returns (uint) {
emit Failure(uint(err), uint(info), 0);
return uint(err);
}
/**
* @dev use this when reporting an opaque error from an upgradeable collaborator contract
*/
function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) {
emit Failure(uint(err), uint(info), opaqueError);
return uint(err);
}
}
pragma solidity ^0.5.16;
import "./CarefulMath.sol";
import "./ExponentialNoError.sol";
/**
* @title Exponential module for storing fixed-precision decimals
* @author Compound
* @dev Legacy contract for compatibility reasons with existing contracts that still use MathError
* @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places.
* Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is:
* `Exp({mantissa: 5100000000000000000})`.
*/
contract Exponential is CarefulMath, ExponentialNoError {
/**
* @dev Creates an exponential from numerator and denominator values.
* Note: Returns an error if (`num` * 10e18) > MAX_INT,
* or if `denom` is zero.
*/
function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) {
(MathError err0, uint scaledNumerator) = mulUInt(num, expScale);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
(MathError err1, uint rational) = divUInt(scaledNumerator, denom);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: rational}));
}
/**
* @dev Adds two exponentials, returning a new exponential.
*/
function addExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError error, uint result) = addUInt(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
/**
* @dev Subtracts two exponentials, returning a new exponential.
*/
function subExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError error, uint result) = subUInt(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
/**
* @dev Multiply an Exp by a scalar, returning a new Exp.
*/
function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) {
(MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa}));
}
/**
* @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer.
*/
function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(product));
}
/**
* @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer.
*/
function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (MathError, uint) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return addUInt(truncate(product), addend);
}
/**
* @dev Divide an Exp by a scalar, returning a new Exp.
*/
function divScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) {
(MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa}));
}
/**
* @dev Divide a scalar by an Exp, returning a new Exp.
*/
function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) {
/*
We are doing this as:
getExp(mulUInt(expScale, scalar), divisor.mantissa)
How it works:
Exp = a / b;
Scalar = s;
`s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale`
*/
(MathError err0, uint numerator) = mulUInt(expScale, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return getExp(numerator, divisor.mantissa);
}
/**
* @dev Divide a scalar by an Exp, then truncate to return an unsigned integer.
*/
function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (MathError, uint) {
(MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(fraction));
}
/**
* @dev Multiplies two exponentials, returning a new exponential.
*/
function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
// We add half the scale before dividing so that we get rounding instead of truncation.
// See "Listing 6" and text above it at https://accu.org/index.php/journals/1717
// Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18.
(MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
(MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale);
// The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero.
assert(err2 == MathError.NO_ERROR);
return (MathError.NO_ERROR, Exp({mantissa: product}));
}
/**
* @dev Multiplies two exponentials given their mantissas, returning a new exponential.
*/
function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) {
return mulExp(Exp({mantissa: a}), Exp({mantissa: b}));
}
/**
* @dev Multiplies three exponentials, returning a new exponential.
*/
function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) {
(MathError err, Exp memory ab) = mulExp(a, b);
if (err != MathError.NO_ERROR) {
return (err, ab);
}
return mulExp(ab, c);
}
/**
* @dev Divides two exponentials, returning a new exponential.
* (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b,
* which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa)
*/
function divExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
return getExp(a.mantissa, b.mantissa);
}
}
pragma solidity ^0.5.16;
/**
* @title ERC 20 Token Standard Interface
* https://eips.ethereum.org/EIPS/eip-20
*/
interface EIP20Interface {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
/**
* @notice Get the total number of tokens in circulation
* @return The supply of tokens
*/
function totalSupply() external view returns (uint256);
/**
* @notice Gets the balance of the specified address
* @param owner The address from which the balance will be retrieved
* @return The balance
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 amount) external returns (bool success);
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint256 amount) external returns (bool success);
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool success);
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent (-1 means infinite)
*/
function allowance(address owner, address spender) external view returns (uint256 remaining);
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
}
pragma solidity ^0.5.16;
/**
* @title EIP20NonStandardInterface
* @dev Version of ERC20 with no return values for `transfer` and `transferFrom`
* See https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
interface EIP20NonStandardInterface {
/**
* @notice Get the total number of tokens in circulation
* @return The supply of tokens
*/
function totalSupply() external view returns (uint256);
/**
* @notice Gets the balance of the specified address
* @param owner The address from which the balance will be retrieved
* @return The balance
*/
function balanceOf(address owner) external view returns (uint256 balance);
///
/// !!!!!!!!!!!!!!
/// !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification
/// !!!!!!!!!!!!!!
///
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
*/
function transfer(address dst, uint256 amount) external;
///
/// !!!!!!!!!!!!!!
/// !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification
/// !!!!!!!!!!!!!!
///
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
*/
function transferFrom(address src, address dst, uint256 amount) external;
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool success);
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent
*/
function allowance(address owner, address spender) external view returns (uint256 remaining);
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
}
pragma solidity ^0.5.16;
/**
* @title Compound's InterestRateModel Interface
* @author Compound
*/
contract InterestRateModel {
/// @notice Indicator that this is an InterestRateModel contract (for inspection)
bool public constant isInterestRateModel = true;
/**
* @notice Calculates the current borrow interest rate per block
* @param cash The total amount of cash the market has
* @param borrows The total amount of borrows the market has outstanding
* @param reserves The total amount of reserves the market has
* @return The borrow rate per block (as a percentage, and scaled by 1e18)
*/
function getBorrowRate(uint cash, uint borrows, uint reserves) external view returns (uint);
/**
* @notice Calculates the current supply interest rate per block
* @param cash The total amount of cash the market has
* @param borrows The total amount of borrows the market has outstanding
* @param reserves The total amount of reserves the market has
* @param reserveFactorMantissa The current reserve factor the market has
* @return The supply rate per block (as a percentage, and scaled by 1e18)
*/
function getSupplyRate(uint cash, uint borrows, uint reserves, uint reserveFactorMantissa) external view returns (uint);
}
pragma solidity ^0.5.16;
/**
* @title Careful Math
* @author Compound
* @notice Derived from OpenZeppelin's SafeMath library
* https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol
*/
contract CarefulMath {
/**
* @dev Possible error codes that we can return
*/
enum MathError {
NO_ERROR,
DIVISION_BY_ZERO,
INTEGER_OVERFLOW,
INTEGER_UNDERFLOW
}
/**
* @dev Multiplies two numbers, returns an error on overflow.
*/
function mulUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (a == 0) {
return (MathError.NO_ERROR, 0);
}
uint c = a * b;
if (c / a != b) {
return (MathError.INTEGER_OVERFLOW, 0);
} else {
return (MathError.NO_ERROR, c);
}
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function divUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (b == 0) {
return (MathError.DIVISION_BY_ZERO, 0);
}
return (MathError.NO_ERROR, a / b);
}
/**
* @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend).
*/
function subUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (b <= a) {
return (MathError.NO_ERROR, a - b);
} else {
return (MathError.INTEGER_UNDERFLOW, 0);
}
}
/**
* @dev Adds two numbers, returns an error on overflow.
*/
function addUInt(uint a, uint b) internal pure returns (MathError, uint) {
uint c = a + b;
if (c >= a) {
return (MathError.NO_ERROR, c);
} else {
return (MathError.INTEGER_OVERFLOW, 0);
}
}
/**
* @dev add a and b and then subtract c
*/
function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) {
(MathError err0, uint sum) = addUInt(a, b);
if (err0 != MathError.NO_ERROR) {
return (err0, 0);
}
return subUInt(sum, c);
}
}
pragma solidity ^0.5.16;
/**
* @title Exponential module for storing fixed-precision decimals
* @author Compound
* @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places.
* Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is:
* `Exp({mantissa: 5100000000000000000})`.
*/
contract ExponentialNoError {
uint constant expScale = 1e18;
uint constant doubleScale = 1e36;
uint constant halfExpScale = expScale/2;
uint constant mantissaOne = expScale;
struct Exp {
uint mantissa;
}
struct Double {
uint mantissa;
}
/**
* @dev Truncates the given exp to a whole number value.
* For example, truncate(Exp{mantissa: 15 * expScale}) = 15
*/
function truncate(Exp memory exp) pure internal returns (uint) {
// Note: We are not using careful math here as we're performing a division that cannot fail
return exp.mantissa / expScale;
}
/**
* @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer.
*/
function mul_ScalarTruncate(Exp memory a, uint scalar) pure internal returns (uint) {
Exp memory product = mul_(a, scalar);
return truncate(product);
}
/**
* @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer.
*/
function mul_ScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (uint) {
Exp memory product = mul_(a, scalar);
return add_(truncate(product), addend);
}
/**
* @dev Checks if first Exp is less than second Exp.
*/
function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa < right.mantissa;
}
/**
* @dev Checks if left Exp <= right Exp.
*/
function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa <= right.mantissa;
}
/**
* @dev Checks if left Exp > right Exp.
*/
function greaterThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa > right.mantissa;
}
/**
* @dev returns true if Exp is exactly zero
*/
function isZeroExp(Exp memory value) pure internal returns (bool) {
return value.mantissa == 0;
}
function safe224(uint n, string memory errorMessage) pure internal returns (uint224) {
require(n < 2**224, errorMessage);
return uint224(n);
}
function safe32(uint n, string memory errorMessage) pure internal returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function add_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: add_(a.mantissa, b.mantissa)});
}
function add_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: add_(a.mantissa, b.mantissa)});
}
function add_(uint a, uint b) pure internal returns (uint) {
return add_(a, b, "addition overflow");
}
function add_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
uint c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: sub_(a.mantissa, b.mantissa)});
}
function sub_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: sub_(a.mantissa, b.mantissa)});
}
function sub_(uint a, uint b) pure internal returns (uint) {
return sub_(a, b, "subtraction underflow");
}
function sub_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
require(b <= a, errorMessage);
return a - b;
}
function mul_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale});
}
function mul_(Exp memory a, uint b) pure internal returns (Exp memory) {
return Exp({mantissa: mul_(a.mantissa, b)});
}
function mul_(uint a, Exp memory b) pure internal returns (uint) {
return mul_(a, b.mantissa) / expScale;
}
function mul_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale});
}
function mul_(Double memory a, uint b) pure internal returns (Double memory) {
return Double({mantissa: mul_(a.mantissa, b)});
}
function mul_(uint a, Double memory b) pure internal returns (uint) {
return mul_(a, b.mantissa) / doubleScale;
}
function mul_(uint a, uint b) pure internal returns (uint) {
return mul_(a, b, "multiplication overflow");
}
function mul_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
if (a == 0 || b == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, errorMessage);
return c;
}
function div_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)});
}
function div_(Exp memory a, uint b) pure internal returns (Exp memory) {
return Exp({mantissa: div_(a.mantissa, b)});
}
function div_(uint a, Exp memory b) pure internal returns (uint) {
return div_(mul_(a, expScale), b.mantissa);
}
function div_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)});
}
function div_(Double memory a, uint b) pure internal returns (Double memory) {
return Double({mantissa: div_(a.mantissa, b)});
}
function div_(uint a, Double memory b) pure internal returns (uint) {
return div_(mul_(a, doubleScale), b.mantissa);
}
function div_(uint a, uint b) pure internal returns (uint) {
return div_(a, b, "divide by zero");
}
function div_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
require(b > 0, errorMessage);
return a / b;
}
function fraction(uint a, uint b) pure internal returns (Double memory) {
return Double({mantissa: div_(mul_(a, doubleScale), b)});
}
}
|
Get a snapshot of the account's balances, and the cached exchange rate This is used by comptroller to more efficiently perform liquidity checks. account Address of the account to snapshot return (possible error, token balance, borrow balance, exchange rate mantissa)/
|
function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint) {
uint cTokenBalance = accountTokens[account];
uint borrowBalance;
uint exchangeRateMantissa;
MathError mErr;
(mErr, borrowBalance) = borrowBalanceStoredInternal(account);
if (mErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0, 0, 0);
}
(mErr, exchangeRateMantissa) = exchangeRateStoredInternal();
if (mErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0, 0, 0);
}
return (uint(Error.NO_ERROR), cTokenBalance, borrowBalance, exchangeRateMantissa);
}
| 17,573 |
pragma solidity ^0.4.20;
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
// <ORACLIZE_API>
/*
Copyright (c) 2015-2016 Oraclize SRL
Copyright (c) 2016 Oraclize LTD
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
pragma solidity ^0.4.11;//please import oraclizeAPI_pre0.4.sol when solidity < 0.4.0
contract OraclizeI {
address public cbAddress;
function query(uint _timestamp, string _datasource, string _arg) payable returns (bytes32 _id);
function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) payable returns (bytes32 _id);
function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) payable returns (bytes32 _id);
function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) payable returns (bytes32 _id);
function queryN(uint _timestamp, string _datasource, bytes _argN) payable returns (bytes32 _id);
function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) payable returns (bytes32 _id);
function getPrice(string _datasource) returns (uint _dsprice);
function getPrice(string _datasource, uint gaslimit) returns (uint _dsprice);
function useCoupon(string _coupon);
function setProofType(byte _proofType);
function setConfig(bytes32 _config);
function setCustomGasPrice(uint _gasPrice);
function randomDS_getSessionPubKeyHash() returns(bytes32);
}
contract OraclizeAddrResolverI {
function getAddress() returns (address _addr);
}
contract usingOraclize {
uint constant day = 60*60*24;
uint constant week = 60*60*24*7;
uint constant month = 60*60*24*30;
byte constant proofType_NONE = 0x00;
byte constant proofType_TLSNotary = 0x10;
byte constant proofType_Android = 0x20;
byte constant proofType_Ledger = 0x30;
byte constant proofType_Native = 0xF0;
byte constant proofStorage_IPFS = 0x01;
uint8 constant networkID_auto = 0;
uint8 constant networkID_mainnet = 1;
uint8 constant networkID_testnet = 2;
uint8 constant networkID_morden = 2;
uint8 constant networkID_consensys = 161;
OraclizeAddrResolverI OAR;
OraclizeI oraclize;
modifier oraclizeAPI {
if((address(OAR)==0)||(getCodeSize(address(OAR))==0)) oraclize_setNetwork(networkID_auto);
oraclize = OraclizeI(OAR.getAddress());
_;
}
modifier coupon(string code){
oraclize = OraclizeI(OAR.getAddress());
oraclize.useCoupon(code);
_;
}
function oraclize_setNetwork(uint8 networkID) internal returns(bool){
if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){ //mainnet
OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed);
oraclize_setNetworkName("eth_mainnet");
return true;
}
if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){ //ropsten testnet
OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1);
oraclize_setNetworkName("eth_ropsten3");
return true;
}
if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){ //kovan testnet
OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e);
oraclize_setNetworkName("eth_kovan");
return true;
}
if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0){ //rinkeby testnet
OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48);
oraclize_setNetworkName("eth_rinkeby");
return true;
}
if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){ //ethereum-bridge
OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475);
return true;
}
if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){ //ether.camp ide
OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF);
return true;
}
if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){ //browser-solidity
OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA);
return true;
}
return false;
}
function __callback(bytes32 myid, string result) {
__callback(myid, result, new bytes(0));
}
function __callback(bytes32 myid, string result, bytes proof) {
}
function oraclize_useCoupon(string code) oraclizeAPI internal {
oraclize.useCoupon(code);
}
function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){
return oraclize.getPrice(datasource);
}
function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){
return oraclize.getPrice(datasource, gaslimit);
}
function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query.value(price)(0, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query.value(price)(timestamp, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit);
}
function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit);
}
function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query2.value(price)(0, datasource, arg1, arg2);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit);
}
function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit);
}
function oraclize_query(string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN.value(price)(0, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN.value(price)(timestamp, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit);
}
function oraclize_query(string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit);
}
function oraclize_query(string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN.value(price)(0, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN.value(price)(timestamp, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit);
}
function oraclize_query(string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit);
}
function oraclize_query(string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_cbAddress() oraclizeAPI internal returns (address){
return oraclize.cbAddress();
}
function oraclize_setProof(byte proofP) oraclizeAPI internal {
return oraclize.setProofType(proofP);
}
function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal {
return oraclize.setCustomGasPrice(gasPrice);
}
function oraclize_setConfig(bytes32 config) oraclizeAPI internal {
return oraclize.setConfig(config);
}
function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32){
return oraclize.randomDS_getSessionPubKeyHash();
}
function getCodeSize(address _addr) constant internal returns(uint _size) {
assembly {
_size := extcodesize(_addr)
}
}
function parseAddr(string _a) internal returns (address){
bytes memory tmp = bytes(_a);
uint160 iaddr = 0;
uint160 b1;
uint160 b2;
for (uint i=2; i<2+2*20; i+=2){
iaddr *= 256;
b1 = uint160(tmp[i]);
b2 = uint160(tmp[i+1]);
if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87;
else if ((b1 >= 65)&&(b1 <= 70)) b1 -= 55;
else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48;
if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87;
else if ((b2 >= 65)&&(b2 <= 70)) b2 -= 55;
else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48;
iaddr += (b1*16+b2);
}
return address(iaddr);
}
function strCompare(string _a, string _b) internal returns (int) {
bytes memory a = bytes(_a);
bytes memory b = bytes(_b);
uint minLength = a.length;
if (b.length < minLength) minLength = b.length;
for (uint i = 0; i < minLength; i ++)
if (a[i] < b[i])
return -1;
else if (a[i] > b[i])
return 1;
if (a.length < b.length)
return -1;
else if (a.length > b.length)
return 1;
else
return 0;
}
function indexOf(string _haystack, string _needle) internal returns (int) {
bytes memory h = bytes(_haystack);
bytes memory n = bytes(_needle);
if(h.length < 1 || n.length < 1 || (n.length > h.length))
return -1;
else if(h.length > (2**128 -1))
return -1;
else
{
uint subindex = 0;
for (uint i = 0; i < h.length; i ++)
{
if (h[i] == n[0])
{
subindex = 1;
while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex])
{
subindex++;
}
if(subindex == n.length)
return int(i);
}
}
return -1;
}
}
function strConcat(string _a, string _b, string _c, string _d, string _e) internal returns (string) {
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
bytes memory _bd = bytes(_d);
bytes memory _be = bytes(_e);
string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length);
bytes memory babcde = bytes(abcde);
uint k = 0;
for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i];
for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i];
for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i];
for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i];
for (i = 0; i < _be.length; i++) babcde[k++] = _be[i];
return string(babcde);
}
function strConcat(string _a, string _b, string _c, string _d) internal returns (string) {
return strConcat(_a, _b, _c, _d, "");
}
function strConcat(string _a, string _b, string _c) internal returns (string) {
return strConcat(_a, _b, _c, "", "");
}
function strConcat(string _a, string _b) internal returns (string) {
return strConcat(_a, _b, "", "", "");
}
// parseInt
function parseInt(string _a) internal returns (uint) {
return parseInt(_a, 0);
}
// parseInt(parseFloat*10^_b)
function parseInt(string _a, uint _b) internal returns (uint) {
bytes memory bresult = bytes(_a);
uint mint = 0;
bool decimals = false;
for (uint i=0; i<bresult.length; i++){
if ((bresult[i] >= 48)&&(bresult[i] <= 57)){
if (decimals){
if (_b == 0) break;
else _b--;
}
mint *= 10;
mint += uint(bresult[i]) - 48;
} else if (bresult[i] == 46) decimals = true;
}
if (_b > 0) mint *= 10**_b;
return mint;
}
function uint2str(uint i) internal returns (string){
if (i == 0) return "0";
uint j = i;
uint len;
while (j != 0){
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (i != 0){
bstr[k--] = byte(48 + i % 10);
i /= 10;
}
return string(bstr);
}
function stra2cbor(string[] arr) internal returns (bytes) {
uint arrlen = arr.length;
// get correct cbor output length
uint outputlen = 0;
bytes[] memory elemArray = new bytes[](arrlen);
for (uint i = 0; i < arrlen; i++) {
elemArray[i] = (bytes(arr[i]));
outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; //+3 accounts for paired identifier types
}
uint ctr = 0;
uint cborlen = arrlen + 0x80;
outputlen += byte(cborlen).length;
bytes memory res = new bytes(outputlen);
while (byte(cborlen).length > ctr) {
res[ctr] = byte(cborlen)[ctr];
ctr++;
}
for (i = 0; i < arrlen; i++) {
res[ctr] = 0x5F;
ctr++;
for (uint x = 0; x < elemArray[i].length; x++) {
// if there's a bug with larger strings, this may be the culprit
if (x % 23 == 0) {
uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x;
elemcborlen += 0x40;
uint lctr = ctr;
while (byte(elemcborlen).length > ctr - lctr) {
res[ctr] = byte(elemcborlen)[ctr - lctr];
ctr++;
}
}
res[ctr] = elemArray[i][x];
ctr++;
}
res[ctr] = 0xFF;
ctr++;
}
return res;
}
function ba2cbor(bytes[] arr) internal returns (bytes) {
uint arrlen = arr.length;
// get correct cbor output length
uint outputlen = 0;
bytes[] memory elemArray = new bytes[](arrlen);
for (uint i = 0; i < arrlen; i++) {
elemArray[i] = (bytes(arr[i]));
outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; //+3 accounts for paired identifier types
}
uint ctr = 0;
uint cborlen = arrlen + 0x80;
outputlen += byte(cborlen).length;
bytes memory res = new bytes(outputlen);
while (byte(cborlen).length > ctr) {
res[ctr] = byte(cborlen)[ctr];
ctr++;
}
for (i = 0; i < arrlen; i++) {
res[ctr] = 0x5F;
ctr++;
for (uint x = 0; x < elemArray[i].length; x++) {
// if there's a bug with larger strings, this may be the culprit
if (x % 23 == 0) {
uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x;
elemcborlen += 0x40;
uint lctr = ctr;
while (byte(elemcborlen).length > ctr - lctr) {
res[ctr] = byte(elemcborlen)[ctr - lctr];
ctr++;
}
}
res[ctr] = elemArray[i][x];
ctr++;
}
res[ctr] = 0xFF;
ctr++;
}
return res;
}
string oraclize_network_name;
function oraclize_setNetworkName(string _network_name) internal {
oraclize_network_name = _network_name;
}
function oraclize_getNetworkName() internal returns (string) {
return oraclize_network_name;
}
function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){
if ((_nbytes == 0)||(_nbytes > 32)) throw;
bytes memory nbytes = new bytes(1);
nbytes[0] = byte(_nbytes);
bytes memory unonce = new bytes(32);
bytes memory sessionKeyHash = new bytes(32);
bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash();
assembly {
mstore(unonce, 0x20)
mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp)))
mstore(sessionKeyHash, 0x20)
mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32)
}
bytes[3] memory args = [unonce, nbytes, sessionKeyHash];
bytes32 queryId = oraclize_query(_delay, "random", args, _customGasLimit);
oraclize_randomDS_setCommitment(queryId, sha3(bytes8(_delay), args[1], sha256(args[0]), args[2]));
return queryId;
}
function oraclize_randomDS_setCommitment(bytes32 queryId, bytes32 commitment) internal {
oraclize_randomDS_args[queryId] = commitment;
}
mapping(bytes32=>bytes32) oraclize_randomDS_args;
mapping(bytes32=>bool) oraclize_randomDS_sessionKeysHashVerified;
function verifySig(bytes32 tosignh, bytes dersig, bytes pubkey) internal returns (bool){
bool sigok;
address signer;
bytes32 sigr;
bytes32 sigs;
bytes memory sigr_ = new bytes(32);
uint offset = 4+(uint(dersig[3]) - 0x20);
sigr_ = copyBytes(dersig, offset, 32, sigr_, 0);
bytes memory sigs_ = new bytes(32);
offset += 32 + 2;
sigs_ = copyBytes(dersig, offset+(uint(dersig[offset-1]) - 0x20), 32, sigs_, 0);
assembly {
sigr := mload(add(sigr_, 32))
sigs := mload(add(sigs_, 32))
}
(sigok, signer) = safer_ecrecover(tosignh, 27, sigr, sigs);
if (address(sha3(pubkey)) == signer) return true;
else {
(sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs);
return (address(sha3(pubkey)) == signer);
}
}
function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes proof, uint sig2offset) internal returns (bool) {
bool sigok;
// Step 6: verify the attestation signature, APPKEY1 must sign the sessionKey from the correct ledger app (CODEHASH)
bytes memory sig2 = new bytes(uint(proof[sig2offset+1])+2);
copyBytes(proof, sig2offset, sig2.length, sig2, 0);
bytes memory appkey1_pubkey = new bytes(64);
copyBytes(proof, 3+1, 64, appkey1_pubkey, 0);
bytes memory tosign2 = new bytes(1+65+32);
tosign2[0] = 1; //role
copyBytes(proof, sig2offset-65, 65, tosign2, 1);
bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c";
copyBytes(CODEHASH, 0, 32, tosign2, 1+65);
sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey);
if (sigok == false) return false;
// Step 7: verify the APPKEY1 provenance (must be signed by Ledger)
bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4";
bytes memory tosign3 = new bytes(1+65);
tosign3[0] = 0xFE;
copyBytes(proof, 3, 65, tosign3, 1);
bytes memory sig3 = new bytes(uint(proof[3+65+1])+2);
copyBytes(proof, 3+65, sig3.length, sig3, 0);
sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY);
return sigok;
}
modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string _result, bytes _proof) {
// Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1)
if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) throw;
bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
if (proofVerified == false) throw;
_;
}
function matchBytes32Prefix(bytes32 content, bytes prefix) internal returns (bool){
bool match_ = true;
for (var i=0; i<prefix.length; i++){
if (content[i] != prefix[i]) match_ = false;
}
return match_;
}
function oraclize_randomDS_proofVerify__main(bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){
bool checkok;
// Step 2: the unique keyhash has to match with the sha256 of (context name + queryId)
uint ledgerProofLength = 3+65+(uint(proof[3+65+1])+2)+32;
bytes memory keyhash = new bytes(32);
copyBytes(proof, ledgerProofLength, 32, keyhash, 0);
checkok = (sha3(keyhash) == sha3(sha256(context_name, queryId)));
if (checkok == false) return false;
bytes memory sig1 = new bytes(uint(proof[ledgerProofLength+(32+8+1+32)+1])+2);
copyBytes(proof, ledgerProofLength+(32+8+1+32), sig1.length, sig1, 0);
// Step 3: we assume sig1 is valid (it will be verified during step 5) and we verify if 'result' is the prefix of sha256(sig1)
checkok = matchBytes32Prefix(sha256(sig1), result);
if (checkok == false) return false;
// Step 4: commitment match verification, sha3(delay, nbytes, unonce, sessionKeyHash) == commitment in storage.
// This is to verify that the computed args match with the ones specified in the query.
bytes memory commitmentSlice1 = new bytes(8+1+32);
copyBytes(proof, ledgerProofLength+32, 8+1+32, commitmentSlice1, 0);
bytes memory sessionPubkey = new bytes(64);
uint sig2offset = ledgerProofLength+32+(8+1+32)+sig1.length+65;
copyBytes(proof, sig2offset-64, 64, sessionPubkey, 0);
bytes32 sessionPubkeyHash = sha256(sessionPubkey);
if (oraclize_randomDS_args[queryId] == sha3(commitmentSlice1, sessionPubkeyHash)){ //unonce, nbytes and sessionKeyHash match
delete oraclize_randomDS_args[queryId];
} else return false;
// Step 5: validity verification for sig1 (keyhash and args signed with the sessionKey)
bytes memory tosign1 = new bytes(32+8+1+32);
copyBytes(proof, ledgerProofLength, 32+8+1+32, tosign1, 0);
checkok = verifySig(sha256(tosign1), sig1, sessionPubkey);
if (checkok == false) return false;
// verify if sessionPubkeyHash was verified already, if not.. let's do it!
if (oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] == false){
oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(proof, sig2offset);
}
return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash];
}
// the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) internal returns (bytes) {
uint minLength = length + toOffset;
if (to.length < minLength) {
// Buffer too small
throw; // Should be a better way?
}
// NOTE: the offset 32 is added to skip the `size` field of both bytes variables
uint i = 32 + fromOffset;
uint j = 32 + toOffset;
while (i < (32 + fromOffset + length)) {
assembly {
let tmp := mload(add(from, i))
mstore(add(to, j), tmp)
}
i += 32;
j += 32;
}
return to;
}
// the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
// Duplicate Solidity's ecrecover, but catching the CALL return value
function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) {
// We do our own memory management here. Solidity uses memory offset
// 0x40 to store the current end of memory. We write past it (as
// writes are memory extensions), but don't update the offset so
// Solidity will reuse it. The memory used here is only needed for
// this context.
// FIXME: inline assembly can't access return values
bool ret;
address addr;
assembly {
let size := mload(0x40)
mstore(size, hash)
mstore(add(size, 32), v)
mstore(add(size, 64), r)
mstore(add(size, 96), s)
// NOTE: we can reuse the request memory because we deal with
// the return code
ret := call(3000, 1, 0, size, 128, size, 32)
addr := mload(size)
}
return (ret, addr);
}
// the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
function ecrecovery(bytes32 hash, bytes sig) internal returns (bool, address) {
bytes32 r;
bytes32 s;
uint8 v;
if (sig.length != 65)
return (false, 0);
// The signature format is a compact form of:
// {bytes32 r}{bytes32 s}{uint8 v}
// Compact means, uint8 is not padded to 32 bytes.
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
// Here we are loading the last 32 bytes. We exploit the fact that
// 'mload' will pad with zeroes if we overread.
// There is no 'mload8' to do this, but that would be nicer.
v := byte(0, mload(add(sig, 96)))
// Alternative solution:
// 'byte' is not working due to the Solidity parser, so lets
// use the second best option, 'and'
// v := and(mload(add(sig, 65)), 255)
}
// albeit non-transactional signatures are not specified by the YP, one would expect it
// to match the YP range of [27, 28]
//
// geth uses [0, 1] and some clients have followed. This might change, see:
// https://github.com/ethereum/go-ethereum/issues/2053
if (v < 27)
v += 27;
if (v != 27 && v != 28)
return (false, 0);
return safer_ecrecover(hash, v, r, s);
}
}
// </ORACLIZE_API>
contract BettingControllerInterface {
function remoteBettingClose() external;
function depositHouseTakeout() external payable;
}
contract Betting is usingOraclize {
using SafeMath for uint256; //using safemath
uint countdown=3; // variable to check if all prices are received
address public owner; //owner address
uint public winnerPoolTotal;
string public constant version = "0.2.2";
BettingControllerInterface internal bettingControllerInstance;
struct chronus_info {
bool betting_open; // boolean: check if betting is open
bool race_start; //boolean: check if race has started
bool race_end; //boolean: check if race has ended
bool voided_bet; //boolean: check if race has been voided
uint32 starting_time; // timestamp of when the race starts
uint32 betting_duration;
uint32 race_duration; // duration of the race
uint32 voided_timestamp;
}
struct horses_info{
int32 BTC_delta; //horses.BTC delta value
int32 ETH_delta; //horses.ETH delta value
int32 LTC_delta; //horses.LTC delta value
bytes32 BTC; //32-bytes equivalent of horses.BTC
bytes32 ETH; //32-bytes equivalent of horses.ETH
bytes32 LTC; //32-bytes equivalent of horses.LTC
uint customGasLimit;
}
struct bet_info{
bytes32 horse; // coin on which amount is bet on
uint amount; // amount bet by Bettor
}
struct coin_info{
uint256 pre; // locking price
uint256 post; // ending price
uint160 total; // total coin pool
uint32 count; // number of bets
bool price_check;
bytes32 preOraclizeId;
bytes32 postOraclizeId;
}
struct voter_info {
uint160 total_bet; //total amount of bet placed
bool rewarded; // boolean: check for double spending
mapping(bytes32=>uint) bets; //array of bets
}
mapping (bytes32 => bytes32) oraclizeIndex; // mapping oraclize IDs with coins
mapping (bytes32 => coin_info) coinIndex; // mapping coins with pool information
mapping (address => voter_info) voterIndex; // mapping voter address with Bettor information
uint public total_reward; // total reward to be awarded
uint32 total_bettors;
mapping (bytes32 => bool) public winner_horse;
// tracking events
event newOraclizeQuery(string description);
event newPriceTicker(uint price);
event Deposit(address _from, uint256 _value, bytes32 _horse, uint256 _date);
event Withdraw(address _to, uint256 _value);
// constructor
function Betting() public payable {
oraclize_setProof(proofType_TLSNotary | proofStorage_IPFS);
owner = msg.sender;
// oraclize_setCustomGasPrice(10000000000 wei);
horses.BTC = bytes32("BTC");
horses.ETH = bytes32("ETH");
horses.LTC = bytes32("LTC");
horses.customGasLimit = 300000;
bettingControllerInstance = BettingControllerInterface(owner);
}
// data access structures
horses_info public horses;
chronus_info public chronus;
// modifiers for restricting access to methods
modifier onlyOwner {
require(owner == msg.sender);
_;
}
modifier duringBetting {
require(chronus.betting_open);
_;
}
modifier beforeBetting {
require(!chronus.betting_open && !chronus.race_start);
_;
}
modifier afterRace {
require(chronus.race_end);
_;
}
//function to change owner
function changeOwnership(address _newOwner) onlyOwner external {
owner = _newOwner;
}
//oraclize callback method
function __callback(bytes32 myid, string result, bytes proof) public {
require (msg.sender == oraclize_cbAddress());
require (!chronus.race_end);
bytes32 coin_pointer; // variable to differentiate different callbacks
chronus.race_start = true;
chronus.betting_open = false;
bettingControllerInstance.remoteBettingClose();
coin_pointer = oraclizeIndex[myid];
if (myid == coinIndex[coin_pointer].preOraclizeId) {
if (coinIndex[coin_pointer].pre > 0) {
} else if (now >= chronus.starting_time+chronus.betting_duration+ 15 minutes) {
forceVoidRace();
} else {
coinIndex[coin_pointer].pre = stringToUintNormalize(result);
emit newPriceTicker(coinIndex[coin_pointer].pre);
}
} else if (myid == coinIndex[coin_pointer].postOraclizeId){
if (coinIndex[coin_pointer].pre > 0 ){
if (coinIndex[coin_pointer].post > 0) {
} else if (now >= chronus.starting_time+chronus.race_duration+ 15 minutes) {
forceVoidRace();
} else {
coinIndex[coin_pointer].post = stringToUintNormalize(result);
coinIndex[coin_pointer].price_check = true;
emit newPriceTicker(coinIndex[coin_pointer].post);
if (coinIndex[horses.ETH].price_check && coinIndex[horses.BTC].price_check && coinIndex[horses.LTC].price_check) {
reward();
}
}
} else {
forceVoidRace();
}
}
}
// place a bet on a coin(horse) lockBetting
function placeBet(bytes32 horse) external duringBetting payable {
require(msg.value >= 0.01 ether);
if (voterIndex[msg.sender].total_bet==0) {
total_bettors+=1;
}
uint _newAmount = voterIndex[msg.sender].bets[horse] + msg.value;
voterIndex[msg.sender].bets[horse] = _newAmount;
voterIndex[msg.sender].total_bet += uint160(msg.value);
uint160 _newTotal = coinIndex[horse].total + uint160(msg.value);
uint32 _newCount = coinIndex[horse].count + 1;
coinIndex[horse].total = _newTotal;
coinIndex[horse].count = _newCount;
emit Deposit(msg.sender, msg.value, horse, now);
}
// fallback method for accepting payments
function () private payable {}
// method to place the oraclize queries
function setupRace(uint delay, uint locking_duration) onlyOwner beforeBetting public payable returns(bool) {
// if (oraclize_getPrice("URL") > (this.balance)/6) {
if (oraclize_getPrice("URL")*3 + oraclize_getPrice("URL", horses.customGasLimit)*3 > address(this).balance) {
emit newOraclizeQuery("Oraclize query was NOT sent, please add some ETH to cover for the query fee");
return false;
} else {
chronus.starting_time = uint32(block.timestamp);
chronus.betting_open = true;
bytes32 temp_ID; // temp variable to store oraclize IDs
emit newOraclizeQuery("Oraclize query was sent, standing by for the answer..");
// bets open price query
chronus.betting_duration = uint32(delay);
temp_ID = oraclize_query(delay, "URL", "json(https://api.coinmarketcap.com/v1/ticker/ethereum/).0.price_usd");
oraclizeIndex[temp_ID] = horses.ETH;
coinIndex[horses.ETH].preOraclizeId = temp_ID;
temp_ID = oraclize_query(delay, "URL", "json(https://api.coinmarketcap.com/v1/ticker/litecoin/).0.price_usd");
oraclizeIndex[temp_ID] = horses.LTC;
coinIndex[horses.LTC].preOraclizeId = temp_ID;
temp_ID = oraclize_query(delay, "URL", "json(https://api.coinmarketcap.com/v1/ticker/bitcoin/).0.price_usd");
oraclizeIndex[temp_ID] = horses.BTC;
coinIndex[horses.BTC].preOraclizeId = temp_ID;
//bets closing price query
delay = delay.add(locking_duration);
temp_ID = oraclize_query(delay, "URL", "json(https://api.coinmarketcap.com/v1/ticker/ethereum/).0.price_usd",horses.customGasLimit);
oraclizeIndex[temp_ID] = horses.ETH;
coinIndex[horses.ETH].postOraclizeId = temp_ID;
temp_ID = oraclize_query(delay, "URL", "json(https://api.coinmarketcap.com/v1/ticker/litecoin/).0.price_usd",horses.customGasLimit);
oraclizeIndex[temp_ID] = horses.LTC;
coinIndex[horses.LTC].postOraclizeId = temp_ID;
temp_ID = oraclize_query(delay, "URL", "json(https://api.coinmarketcap.com/v1/ticker/bitcoin/).0.price_usd",horses.customGasLimit);
oraclizeIndex[temp_ID] = horses.BTC;
coinIndex[horses.BTC].postOraclizeId = temp_ID;
chronus.race_duration = uint32(delay);
return true;
}
}
// method to calculate reward (called internally by callback)
function reward() internal {
/*
calculating the difference in price with a precision of 5 digits
not using safemath since signed integers are handled
*/
horses.BTC_delta = int32(coinIndex[horses.BTC].post - coinIndex[horses.BTC].pre)*100000/int32(coinIndex[horses.BTC].pre);
horses.ETH_delta = int32(coinIndex[horses.ETH].post - coinIndex[horses.ETH].pre)*100000/int32(coinIndex[horses.ETH].pre);
horses.LTC_delta = int32(coinIndex[horses.LTC].post - coinIndex[horses.LTC].pre)*100000/int32(coinIndex[horses.LTC].pre);
total_reward = (coinIndex[horses.BTC].total) + (coinIndex[horses.ETH].total) + (coinIndex[horses.LTC].total);
if (total_bettors <= 1) {
forceVoidRace();
} else {
uint house_fee = total_reward.mul(5).div(100);
require(house_fee < address(this).balance);
total_reward = total_reward.sub(house_fee);
bettingControllerInstance.depositHouseTakeout.value(house_fee)();
}
if (horses.BTC_delta > horses.ETH_delta) {
if (horses.BTC_delta > horses.LTC_delta) {
winner_horse[horses.BTC] = true;
winnerPoolTotal = coinIndex[horses.BTC].total;
}
else if(horses.LTC_delta > horses.BTC_delta) {
winner_horse[horses.LTC] = true;
winnerPoolTotal = coinIndex[horses.LTC].total;
} else {
winner_horse[horses.BTC] = true;
winner_horse[horses.LTC] = true;
winnerPoolTotal = coinIndex[horses.BTC].total + (coinIndex[horses.LTC].total);
}
} else if(horses.ETH_delta > horses.BTC_delta) {
if (horses.ETH_delta > horses.LTC_delta) {
winner_horse[horses.ETH] = true;
winnerPoolTotal = coinIndex[horses.ETH].total;
}
else if (horses.LTC_delta > horses.ETH_delta) {
winner_horse[horses.LTC] = true;
winnerPoolTotal = coinIndex[horses.LTC].total;
} else {
winner_horse[horses.ETH] = true;
winner_horse[horses.LTC] = true;
winnerPoolTotal = coinIndex[horses.ETH].total + (coinIndex[horses.LTC].total);
}
} else {
if (horses.LTC_delta > horses.ETH_delta) {
winner_horse[horses.LTC] = true;
winnerPoolTotal = coinIndex[horses.LTC].total;
} else if(horses.LTC_delta < horses.ETH_delta){
winner_horse[horses.ETH] = true;
winner_horse[horses.BTC] = true;
winnerPoolTotal = coinIndex[horses.ETH].total + (coinIndex[horses.BTC].total);
} else {
winner_horse[horses.LTC] = true;
winner_horse[horses.ETH] = true;
winner_horse[horses.BTC] = true;
winnerPoolTotal = coinIndex[horses.ETH].total + (coinIndex[horses.BTC].total) + (coinIndex[horses.LTC].total);
}
}
chronus.race_end = true;
}
// method to calculate an invidual's reward
function calculateReward(address candidate) internal afterRace constant returns(uint winner_reward) {
voter_info storage bettor = voterIndex[candidate];
if(chronus.voided_bet) {
winner_reward = bettor.total_bet;
} else {
uint winning_bet_total;
if(winner_horse[horses.BTC]) {
winning_bet_total += bettor.bets[horses.BTC];
} if(winner_horse[horses.ETH]) {
winning_bet_total += bettor.bets[horses.ETH];
} if(winner_horse[horses.LTC]) {
winning_bet_total += bettor.bets[horses.LTC];
}
winner_reward += (((total_reward.mul(10000000)).div(winnerPoolTotal)).mul(winning_bet_total)).div(10000000);
}
}
// method to just check the reward amount
function checkReward() afterRace external constant returns (uint) {
require(!voterIndex[msg.sender].rewarded);
return calculateReward(msg.sender);
}
// method to claim the reward amount
function claim_reward() afterRace external {
require(!voterIndex[msg.sender].rewarded);
uint transfer_amount = calculateReward(msg.sender);
require(address(this).balance >= transfer_amount);
voterIndex[msg.sender].rewarded = true;
msg.sender.transfer(transfer_amount);
emit Withdraw(msg.sender, transfer_amount);
}
function forceVoidRace() internal {
chronus.voided_bet=true;
chronus.race_end = true;
chronus.voided_timestamp=uint32(now);
}
// utility function to convert string to integer with precision consideration
function stringToUintNormalize(string s) internal pure returns (uint result) {
uint p =2;
bool precision=false;
bytes memory b = bytes(s);
uint i;
result = 0;
for (i = 0; i < b.length; i++) {
if (precision) {p = p-1;}
if (uint(b[i]) == 46){precision = true;}
uint c = uint(b[i]);
if (c >= 48 && c <= 57) {result = result * 10 + (c - 48);}
if (precision && p == 0){return result;}
}
while (p!=0) {
result = result*10;
p=p-1;
}
}
// exposing the coin pool details for DApp
function getCoinIndex(bytes32 index, address candidate) external constant returns (uint, uint, uint, bool, uint) {
return (coinIndex[index].total, coinIndex[index].pre, coinIndex[index].post, coinIndex[index].price_check, voterIndex[candidate].bets[index]);
}
// exposing the total reward amount for DApp
function reward_total() external constant returns (uint) {
return ((coinIndex[horses.BTC].total) + (coinIndex[horses.ETH].total) + (coinIndex[horses.LTC].total));
}
// in case of any errors in race, enable full refund for the Bettors to claim
function refund() external onlyOwner {
require(now > chronus.starting_time + chronus.race_duration);
require((chronus.betting_open && !chronus.race_start)
|| (chronus.race_start && !chronus.race_end));
chronus.voided_bet = true;
chronus.race_end = true;
chronus.voided_timestamp=uint32(now);
bettingControllerInstance.remoteBettingClose();
}
// method to claim unclaimed winnings after 30 day notice period
function recovery() external onlyOwner{
require((chronus.race_end && now > chronus.starting_time + chronus.race_duration + (30 days))
|| (chronus.voided_bet && now > chronus.voided_timestamp + (30 days)));
bettingControllerInstance.depositHouseTakeout.value(address(this).balance)();
}
}
|
method to claim unclaimed winnings after 30 day notice period
|
function recovery() external onlyOwner{
require((chronus.race_end && now > chronus.starting_time + chronus.race_duration + (30 days))
|| (chronus.voided_bet && now > chronus.voided_timestamp + (30 days)));
bettingControllerInstance.depositHouseTakeout.value(address(this).balance)();
}
| 1,131,265 |
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
// Global Enums and Structs
struct StrategyParams {
uint256 performanceFee;
uint256 activation;
uint256 debtRatio;
uint256 minDebtPerHarvest;
uint256 maxDebtPerHarvest;
uint256 lastReport;
uint256 totalDebt;
uint256 totalGain;
uint256 totalLoss;
}
// Part: ICurveFi
interface ICurveFi {
function get_virtual_price() external view returns (uint256);
function add_liquidity(
// EURt
uint256[2] calldata amounts,
uint256 min_mint_amount
) external payable;
function add_liquidity(
// Compound, sAave
uint256[2] calldata amounts,
uint256 min_mint_amount,
bool _use_underlying
) external payable returns (uint256);
function add_liquidity(
// Iron Bank, Aave
uint256[3] calldata amounts,
uint256 min_mint_amount,
bool _use_underlying
) external payable returns (uint256);
function add_liquidity(
// 3Crv Metapools
address pool,
uint256[4] calldata amounts,
uint256 min_mint_amount
) external;
function add_liquidity(
// Y and yBUSD
uint256[4] calldata amounts,
uint256 min_mint_amount,
bool _use_underlying
) external payable returns (uint256);
function add_liquidity(
// 3pool
uint256[3] calldata amounts,
uint256 min_mint_amount
) external payable;
function add_liquidity(
// sUSD
uint256[4] calldata amounts,
uint256 min_mint_amount
) external payable;
function remove_liquidity_imbalance(
uint256[2] calldata amounts,
uint256 max_burn_amount
) external;
function remove_liquidity(uint256 _amount, uint256[2] calldata amounts)
external;
function remove_liquidity_one_coin(
uint256 _token_amount,
int128 i,
uint256 min_amount
) external;
function exchange(
int128 from,
int128 to,
uint256 _from_amount,
uint256 _min_to_amount
) external;
function balances(uint256) external view returns (uint256);
function get_dy(
int128 from,
int128 to,
uint256 _from_amount
) external view returns (uint256);
// EURt
function calc_token_amount(uint256[2] calldata _amounts, bool _is_deposit)
external
view
returns (uint256);
// 3Crv Metapools
function calc_token_amount(
address _pool,
uint256[4] calldata _amounts,
bool _is_deposit
) external view returns (uint256);
// sUSD, Y pool, etc
function calc_token_amount(uint256[4] calldata _amounts, bool _is_deposit)
external
view
returns (uint256);
// 3pool, Iron Bank, etc
function calc_token_amount(uint256[3] calldata _amounts, bool _is_deposit)
external
view
returns (uint256);
function calc_withdraw_one_coin(uint256 amount, int128 i)
external
view
returns (uint256);
}
// Part: ICurveStrategyProxy
interface ICurveStrategyProxy {
function proxy() external returns (address);
function balanceOf(address _gauge) external view returns (uint256);
function deposit(address _gauge, address _token) external;
function withdraw(
address _gauge,
address _token,
uint256 _amount
) external returns (uint256);
function withdrawAll(address _gauge, address _token)
external
returns (uint256);
function harvest(address _gauge) external;
function lock() external;
function approveStrategy(address) external;
function revokeStrategy(address) external;
function claimRewards(address _gauge, address _token) external;
}
// Part: IUniswapV2Router01
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);
}
// Part: OpenZeppelin/[email protected]/Address
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// Part: OpenZeppelin/[email protected]/IERC20
/**
* @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);
}
// Part: OpenZeppelin/[email protected]/Math
/**
* @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);
}
}
// Part: OpenZeppelin/[email protected]/SafeMath
/**
* @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;
}
}
// Part: yearn/[email protected]/HealthCheck
interface HealthCheck {
function check(
uint256 profit,
uint256 loss,
uint256 debtPayment,
uint256 debtOutstanding,
uint256 totalDebt
) external view returns (bool);
}
// Part: IUniswapV2Router02
interface IUniswapV2Router02 is IUniswapV2Router01 {
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;
}
// Part: OpenZeppelin/[email protected]/SafeERC20
/**
* @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");
}
}
}
// Part: yearn/[email protected]/VaultAPI
interface VaultAPI is IERC20 {
function name() external view returns (string calldata);
function symbol() external view returns (string calldata);
function decimals() external view returns (uint256);
function apiVersion() external pure returns (string memory);
function permit(
address owner,
address spender,
uint256 amount,
uint256 expiry,
bytes calldata signature
) external returns (bool);
// NOTE: Vyper produces multiple signatures for a given function with "default" args
function deposit() external returns (uint256);
function deposit(uint256 amount) external returns (uint256);
function deposit(uint256 amount, address recipient) external returns (uint256);
// NOTE: Vyper produces multiple signatures for a given function with "default" args
function withdraw() external returns (uint256);
function withdraw(uint256 maxShares) external returns (uint256);
function withdraw(uint256 maxShares, address recipient) external returns (uint256);
function token() external view returns (address);
function strategies(address _strategy) external view returns (StrategyParams memory);
function pricePerShare() external view returns (uint256);
function totalAssets() external view returns (uint256);
function depositLimit() external view returns (uint256);
function maxAvailableShares() external view returns (uint256);
/**
* View how much the Vault would increase this Strategy's borrow limit,
* based on its present performance (since its last report). Can be used to
* determine expectedReturn in your Strategy.
*/
function creditAvailable() external view returns (uint256);
/**
* View how much the Vault would like to pull back from the Strategy,
* based on its present performance (since its last report). Can be used to
* determine expectedReturn in your Strategy.
*/
function debtOutstanding() external view returns (uint256);
/**
* View how much the Vault expect this Strategy to return at the current
* block, based on its present performance (since its last report). Can be
* used to determine expectedReturn in your Strategy.
*/
function expectedReturn() external view returns (uint256);
/**
* This is the main contact point where the Strategy interacts with the
* Vault. It is critical that this call is handled as intended by the
* Strategy. Therefore, this function will be called by BaseStrategy to
* make sure the integration is correct.
*/
function report(
uint256 _gain,
uint256 _loss,
uint256 _debtPayment
) external returns (uint256);
/**
* This function should only be used in the scenario where the Strategy is
* being retired but no migration of the positions are possible, or in the
* extreme scenario that the Strategy needs to be put into "Emergency Exit"
* mode in order for it to exit as quickly as possible. The latter scenario
* could be for any reason that is considered "critical" that the Strategy
* exits its position as fast as possible, such as a sudden change in
* market conditions leading to losses, or an imminent failure in an
* external dependency.
*/
function revokeStrategy() external;
/**
* View the governance address of the Vault to assert privileged functions
* can only be called by governance. The Strategy serves the Vault, so it
* is subject to governance defined by the Vault.
*/
function governance() external view returns (address);
/**
* View the management address of the Vault to assert privileged functions
* can only be called by management. The Strategy serves the Vault, so it
* is subject to management defined by the Vault.
*/
function management() external view returns (address);
/**
* View the guardian address of the Vault to assert privileged functions
* can only be called by guardian. The Strategy serves the Vault, so it
* is subject to guardian defined by the Vault.
*/
function guardian() external view returns (address);
}
// Part: yearn/[email protected]/BaseStrategy
/**
* @title Yearn Base Strategy
* @author yearn.finance
* @notice
* BaseStrategy implements all of the required functionality to interoperate
* closely with the Vault contract. This contract should be inherited and the
* abstract methods implemented to adapt the Strategy to the particular needs
* it has to create a return.
*
* Of special interest is the relationship between `harvest()` and
* `vault.report()'. `harvest()` may be called simply because enough time has
* elapsed since the last report, and not because any funds need to be moved
* or positions adjusted. This is critical so that the Vault may maintain an
* accurate picture of the Strategy's performance. See `vault.report()`,
* `harvest()`, and `harvestTrigger()` for further details.
*/
abstract contract BaseStrategy {
using SafeMath for uint256;
using SafeERC20 for IERC20;
string public metadataURI;
// health checks
bool public doHealthCheck;
address public healthCheck;
/**
* @notice
* Used to track which version of `StrategyAPI` this Strategy
* implements.
* @dev The Strategy's version must match the Vault's `API_VERSION`.
* @return A string which holds the current API version of this contract.
*/
function apiVersion() public pure returns (string memory) {
return "0.4.3";
}
/**
* @notice This Strategy's name.
* @dev
* You can use this field to manage the "version" of this Strategy, e.g.
* `StrategySomethingOrOtherV1`. However, "API Version" is managed by
* `apiVersion()` function above.
* @return This Strategy's name.
*/
function name() external view virtual returns (string memory);
/**
* @notice
* The amount (priced in want) of the total assets managed by this strategy should not count
* towards Yearn's TVL calculations.
* @dev
* You can override this field to set it to a non-zero value if some of the assets of this
* Strategy is somehow delegated inside another part of of Yearn's ecosystem e.g. another Vault.
* Note that this value must be strictly less than or equal to the amount provided by
* `estimatedTotalAssets()` below, as the TVL calc will be total assets minus delegated assets.
* Also note that this value is used to determine the total assets under management by this
* strategy, for the purposes of computing the management fee in `Vault`
* @return
* The amount of assets this strategy manages that should not be included in Yearn's Total Value
* Locked (TVL) calculation across it's ecosystem.
*/
function delegatedAssets() external view virtual returns (uint256) {
return 0;
}
VaultAPI public vault;
address public strategist;
address public rewards;
address public keeper;
IERC20 public want;
// So indexers can keep track of this
event Harvested(uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding);
event UpdatedStrategist(address newStrategist);
event UpdatedKeeper(address newKeeper);
event UpdatedRewards(address rewards);
event UpdatedMinReportDelay(uint256 delay);
event UpdatedMaxReportDelay(uint256 delay);
event UpdatedProfitFactor(uint256 profitFactor);
event UpdatedDebtThreshold(uint256 debtThreshold);
event EmergencyExitEnabled();
event UpdatedMetadataURI(string metadataURI);
// The minimum number of seconds between harvest calls. See
// `setMinReportDelay()` for more details.
uint256 public minReportDelay;
// The maximum number of seconds between harvest calls. See
// `setMaxReportDelay()` for more details.
uint256 public maxReportDelay;
// The minimum multiple that `callCost` must be above the credit/profit to
// be "justifiable". See `setProfitFactor()` for more details.
uint256 public profitFactor;
// Use this to adjust the threshold at which running a debt causes a
// harvest trigger. See `setDebtThreshold()` for more details.
uint256 public debtThreshold;
// See note on `setEmergencyExit()`.
bool public emergencyExit;
// modifiers
modifier onlyAuthorized() {
require(msg.sender == strategist || msg.sender == governance(), "!authorized");
_;
}
modifier onlyEmergencyAuthorized() {
require(
msg.sender == strategist || msg.sender == governance() || msg.sender == vault.guardian() || msg.sender == vault.management(),
"!authorized"
);
_;
}
modifier onlyStrategist() {
require(msg.sender == strategist, "!strategist");
_;
}
modifier onlyGovernance() {
require(msg.sender == governance(), "!authorized");
_;
}
modifier onlyKeepers() {
require(
msg.sender == keeper ||
msg.sender == strategist ||
msg.sender == governance() ||
msg.sender == vault.guardian() ||
msg.sender == vault.management(),
"!authorized"
);
_;
}
modifier onlyVaultManagers() {
require(msg.sender == vault.management() || msg.sender == governance(), "!authorized");
_;
}
constructor(address _vault) public {
_initialize(_vault, msg.sender, msg.sender, msg.sender);
}
/**
* @notice
* Initializes the Strategy, this is called only once, when the
* contract is deployed.
* @dev `_vault` should implement `VaultAPI`.
* @param _vault The address of the Vault responsible for this Strategy.
* @param _strategist The address to assign as `strategist`.
* The strategist is able to change the reward address
* @param _rewards The address to use for pulling rewards.
* @param _keeper The adddress of the _keeper. _keeper
* can harvest and tend a strategy.
*/
function _initialize(
address _vault,
address _strategist,
address _rewards,
address _keeper
) internal {
require(address(want) == address(0), "Strategy already initialized");
vault = VaultAPI(_vault);
want = IERC20(vault.token());
want.safeApprove(_vault, uint256(-1)); // Give Vault unlimited access (might save gas)
strategist = _strategist;
rewards = _rewards;
keeper = _keeper;
// initialize variables
minReportDelay = 0;
maxReportDelay = 86400;
profitFactor = 100;
debtThreshold = 0;
vault.approve(rewards, uint256(-1)); // Allow rewards to be pulled
}
function setHealthCheck(address _healthCheck) external onlyVaultManagers {
healthCheck = _healthCheck;
}
function setDoHealthCheck(bool _doHealthCheck) external onlyVaultManagers {
doHealthCheck = _doHealthCheck;
}
/**
* @notice
* Used to change `strategist`.
*
* This may only be called by governance or the existing strategist.
* @param _strategist The new address to assign as `strategist`.
*/
function setStrategist(address _strategist) external onlyAuthorized {
require(_strategist != address(0));
strategist = _strategist;
emit UpdatedStrategist(_strategist);
}
/**
* @notice
* Used to change `keeper`.
*
* `keeper` is the only address that may call `tend()` or `harvest()`,
* other than `governance()` or `strategist`. However, unlike
* `governance()` or `strategist`, `keeper` may *only* call `tend()`
* and `harvest()`, and no other authorized functions, following the
* principle of least privilege.
*
* This may only be called by governance or the strategist.
* @param _keeper The new address to assign as `keeper`.
*/
function setKeeper(address _keeper) external onlyAuthorized {
require(_keeper != address(0));
keeper = _keeper;
emit UpdatedKeeper(_keeper);
}
/**
* @notice
* Used to change `rewards`. EOA or smart contract which has the permission
* to pull rewards from the vault.
*
* This may only be called by the strategist.
* @param _rewards The address to use for pulling rewards.
*/
function setRewards(address _rewards) external onlyStrategist {
require(_rewards != address(0));
vault.approve(rewards, 0);
rewards = _rewards;
vault.approve(rewards, uint256(-1));
emit UpdatedRewards(_rewards);
}
/**
* @notice
* Used to change `minReportDelay`. `minReportDelay` is the minimum number
* of blocks that should pass for `harvest()` to be called.
*
* For external keepers (such as the Keep3r network), this is the minimum
* time between jobs to wait. (see `harvestTrigger()`
* for more details.)
*
* This may only be called by governance or the strategist.
* @param _delay The minimum number of seconds to wait between harvests.
*/
function setMinReportDelay(uint256 _delay) external onlyAuthorized {
minReportDelay = _delay;
emit UpdatedMinReportDelay(_delay);
}
/**
* @notice
* Used to change `maxReportDelay`. `maxReportDelay` is the maximum number
* of blocks that should pass for `harvest()` to be called.
*
* For external keepers (such as the Keep3r network), this is the maximum
* time between jobs to wait. (see `harvestTrigger()`
* for more details.)
*
* This may only be called by governance or the strategist.
* @param _delay The maximum number of seconds to wait between harvests.
*/
function setMaxReportDelay(uint256 _delay) external onlyAuthorized {
maxReportDelay = _delay;
emit UpdatedMaxReportDelay(_delay);
}
/**
* @notice
* Used to change `profitFactor`. `profitFactor` is used to determine
* if it's worthwhile to harvest, given gas costs. (See `harvestTrigger()`
* for more details.)
*
* This may only be called by governance or the strategist.
* @param _profitFactor A ratio to multiply anticipated
* `harvest()` gas cost against.
*/
function setProfitFactor(uint256 _profitFactor) external onlyAuthorized {
profitFactor = _profitFactor;
emit UpdatedProfitFactor(_profitFactor);
}
/**
* @notice
* Sets how far the Strategy can go into loss without a harvest and report
* being required.
*
* By default this is 0, meaning any losses would cause a harvest which
* will subsequently report the loss to the Vault for tracking. (See
* `harvestTrigger()` for more details.)
*
* This may only be called by governance or the strategist.
* @param _debtThreshold How big of a loss this Strategy may carry without
* being required to report to the Vault.
*/
function setDebtThreshold(uint256 _debtThreshold) external onlyAuthorized {
debtThreshold = _debtThreshold;
emit UpdatedDebtThreshold(_debtThreshold);
}
/**
* @notice
* Used to change `metadataURI`. `metadataURI` is used to store the URI
* of the file describing the strategy.
*
* This may only be called by governance or the strategist.
* @param _metadataURI The URI that describe the strategy.
*/
function setMetadataURI(string calldata _metadataURI) external onlyAuthorized {
metadataURI = _metadataURI;
emit UpdatedMetadataURI(_metadataURI);
}
/**
* Resolve governance address from Vault contract, used to make assertions
* on protected functions in the Strategy.
*/
function governance() internal view returns (address) {
return vault.governance();
}
/**
* @notice
* Provide an accurate conversion from `_amtInWei` (denominated in wei)
* to `want` (using the native decimal characteristics of `want`).
* @dev
* Care must be taken when working with decimals to assure that the conversion
* is compatible. As an example:
*
* given 1e17 wei (0.1 ETH) as input, and want is USDC (6 decimals),
* with USDC/ETH = 1800, this should give back 1800000000 (180 USDC)
*
* @param _amtInWei The amount (in wei/1e-18 ETH) to convert to `want`
* @return The amount in `want` of `_amtInEth` converted to `want`
**/
function ethToWant(uint256 _amtInWei) public view virtual returns (uint256);
/**
* @notice
* Provide an accurate estimate for the total amount of assets
* (principle + return) that this Strategy is currently managing,
* denominated in terms of `want` tokens.
*
* This total should be "realizable" e.g. the total value that could
* *actually* be obtained from this Strategy if it were to divest its
* entire position based on current on-chain conditions.
* @dev
* Care must be taken in using this function, since it relies on external
* systems, which could be manipulated by the attacker to give an inflated
* (or reduced) value produced by this function, based on current on-chain
* conditions (e.g. this function is possible to influence through
* flashloan attacks, oracle manipulations, or other DeFi attack
* mechanisms).
*
* It is up to governance to use this function to correctly order this
* Strategy relative to its peers in the withdrawal queue to minimize
* losses for the Vault based on sudden withdrawals. This value should be
* higher than the total debt of the Strategy and higher than its expected
* value to be "safe".
* @return The estimated total assets in this Strategy.
*/
function estimatedTotalAssets() public view virtual returns (uint256);
/*
* @notice
* Provide an indication of whether this strategy is currently "active"
* in that it is managing an active position, or will manage a position in
* the future. This should correlate to `harvest()` activity, so that Harvest
* events can be tracked externally by indexing agents.
* @return True if the strategy is actively managing a position.
*/
function isActive() public view returns (bool) {
return vault.strategies(address(this)).debtRatio > 0 || estimatedTotalAssets() > 0;
}
/**
* Perform any Strategy unwinding or other calls necessary to capture the
* "free return" this Strategy has generated since the last time its core
* position(s) were adjusted. Examples include unwrapping extra rewards.
* This call is only used during "normal operation" of a Strategy, and
* should be optimized to minimize losses as much as possible.
*
* This method returns any realized profits and/or realized losses
* incurred, and should return the total amounts of profits/losses/debt
* payments (in `want` tokens) for the Vault's accounting (e.g.
* `want.balanceOf(this) >= _debtPayment + _profit`).
*
* `_debtOutstanding` will be 0 if the Strategy is not past the configured
* debt limit, otherwise its value will be how far past the debt limit
* the Strategy is. The Strategy's debt limit is configured in the Vault.
*
* NOTE: `_debtPayment` should be less than or equal to `_debtOutstanding`.
* It is okay for it to be less than `_debtOutstanding`, as that
* should only used as a guide for how much is left to pay back.
* Payments should be made to minimize loss from slippage, debt,
* withdrawal fees, etc.
*
* See `vault.debtOutstanding()`.
*/
function prepareReturn(uint256 _debtOutstanding)
internal
virtual
returns (
uint256 _profit,
uint256 _loss,
uint256 _debtPayment
);
/**
* Perform any adjustments to the core position(s) of this Strategy given
* what change the Vault made in the "investable capital" available to the
* Strategy. Note that all "free capital" in the Strategy after the report
* was made is available for reinvestment. Also note that this number
* could be 0, and you should handle that scenario accordingly.
*
* See comments regarding `_debtOutstanding` on `prepareReturn()`.
*/
function adjustPosition(uint256 _debtOutstanding) internal virtual;
/**
* Liquidate up to `_amountNeeded` of `want` of this strategy's positions,
* irregardless of slippage. Any excess will be re-invested with `adjustPosition()`.
* This function should return the amount of `want` tokens made available by the
* liquidation. If there is a difference between them, `_loss` indicates whether the
* difference is due to a realized loss, or if there is some other sitution at play
* (e.g. locked funds) where the amount made available is less than what is needed.
*
* NOTE: The invariant `_liquidatedAmount + _loss <= _amountNeeded` should always be maintained
*/
function liquidatePosition(uint256 _amountNeeded) internal virtual returns (uint256 _liquidatedAmount, uint256 _loss);
/**
* Liquidate everything and returns the amount that got freed.
* This function is used during emergency exit instead of `prepareReturn()` to
* liquidate all of the Strategy's positions back to the Vault.
*/
function liquidateAllPositions() internal virtual returns (uint256 _amountFreed);
/**
* @notice
* Provide a signal to the keeper that `tend()` should be called. The
* keeper will provide the estimated gas cost that they would pay to call
* `tend()`, and this function should use that estimate to make a
* determination if calling it is "worth it" for the keeper. This is not
* the only consideration into issuing this trigger, for example if the
* position would be negatively affected if `tend()` is not called
* shortly, then this can return `true` even if the keeper might be
* "at a loss" (keepers are always reimbursed by Yearn).
* @dev
* `callCostInWei` must be priced in terms of `wei` (1e-18 ETH).
*
* This call and `harvestTrigger()` should never return `true` at the same
* time.
* @param callCostInWei The keeper's estimated gas cost to call `tend()` (in wei).
* @return `true` if `tend()` should be called, `false` otherwise.
*/
function tendTrigger(uint256 callCostInWei) public view virtual returns (bool) {
// We usually don't need tend, but if there are positions that need
// active maintainence, overriding this function is how you would
// signal for that.
// If your implementation uses the cost of the call in want, you can
// use uint256 callCost = ethToWant(callCostInWei);
return false;
}
/**
* @notice
* Adjust the Strategy's position. The purpose of tending isn't to
* realize gains, but to maximize yield by reinvesting any returns.
*
* See comments on `adjustPosition()`.
*
* This may only be called by governance, the strategist, or the keeper.
*/
function tend() external onlyKeepers {
// Don't take profits with this call, but adjust for better gains
adjustPosition(vault.debtOutstanding());
}
/**
* @notice
* Provide a signal to the keeper that `harvest()` should be called. The
* keeper will provide the estimated gas cost that they would pay to call
* `harvest()`, and this function should use that estimate to make a
* determination if calling it is "worth it" for the keeper. This is not
* the only consideration into issuing this trigger, for example if the
* position would be negatively affected if `harvest()` is not called
* shortly, then this can return `true` even if the keeper might be "at a
* loss" (keepers are always reimbursed by Yearn).
* @dev
* `callCostInWei` must be priced in terms of `wei` (1e-18 ETH).
*
* This call and `tendTrigger` should never return `true` at the
* same time.
*
* See `min/maxReportDelay`, `profitFactor`, `debtThreshold` to adjust the
* strategist-controlled parameters that will influence whether this call
* returns `true` or not. These parameters will be used in conjunction
* with the parameters reported to the Vault (see `params`) to determine
* if calling `harvest()` is merited.
*
* It is expected that an external system will check `harvestTrigger()`.
* This could be a script run off a desktop or cloud bot (e.g.
* https://github.com/iearn-finance/yearn-vaults/blob/main/scripts/keep.py),
* or via an integration with the Keep3r network (e.g.
* https://github.com/Macarse/GenericKeep3rV2/blob/master/contracts/keep3r/GenericKeep3rV2.sol).
* @param callCostInWei The keeper's estimated gas cost to call `harvest()` (in wei).
* @return `true` if `harvest()` should be called, `false` otherwise.
*/
function harvestTrigger(uint256 callCostInWei) public view virtual returns (bool) {
uint256 callCost = ethToWant(callCostInWei);
StrategyParams memory params = vault.strategies(address(this));
// Should not trigger if Strategy is not activated
if (params.activation == 0) return false;
// Should not trigger if we haven't waited long enough since previous harvest
if (block.timestamp.sub(params.lastReport) < minReportDelay) return false;
// Should trigger if hasn't been called in a while
if (block.timestamp.sub(params.lastReport) >= maxReportDelay) return true;
// If some amount is owed, pay it back
// NOTE: Since debt is based on deposits, it makes sense to guard against large
// changes to the value from triggering a harvest directly through user
// behavior. This should ensure reasonable resistance to manipulation
// from user-initiated withdrawals as the outstanding debt fluctuates.
uint256 outstanding = vault.debtOutstanding();
if (outstanding > debtThreshold) return true;
// Check for profits and losses
uint256 total = estimatedTotalAssets();
// Trigger if we have a loss to report
if (total.add(debtThreshold) < params.totalDebt) return true;
uint256 profit = 0;
if (total > params.totalDebt) profit = total.sub(params.totalDebt); // We've earned a profit!
// Otherwise, only trigger if it "makes sense" economically (gas cost
// is <N% of value moved)
uint256 credit = vault.creditAvailable();
return (profitFactor.mul(callCost) < credit.add(profit));
}
/**
* @notice
* Harvests the Strategy, recognizing any profits or losses and adjusting
* the Strategy's position.
*
* In the rare case the Strategy is in emergency shutdown, this will exit
* the Strategy's position.
*
* This may only be called by governance, the strategist, or the keeper.
* @dev
* When `harvest()` is called, the Strategy reports to the Vault (via
* `vault.report()`), so in some cases `harvest()` must be called in order
* to take in profits, to borrow newly available funds from the Vault, or
* otherwise adjust its position. In other cases `harvest()` must be
* called to report to the Vault on the Strategy's position, especially if
* any losses have occurred.
*/
function harvest() external onlyKeepers {
uint256 profit = 0;
uint256 loss = 0;
uint256 debtOutstanding = vault.debtOutstanding();
uint256 debtPayment = 0;
if (emergencyExit) {
// Free up as much capital as possible
uint256 amountFreed = liquidateAllPositions();
if (amountFreed < debtOutstanding) {
loss = debtOutstanding.sub(amountFreed);
} else if (amountFreed > debtOutstanding) {
profit = amountFreed.sub(debtOutstanding);
}
debtPayment = debtOutstanding.sub(loss);
} else {
// Free up returns for Vault to pull
(profit, loss, debtPayment) = prepareReturn(debtOutstanding);
}
// Allow Vault to take up to the "harvested" balance of this contract,
// which is the amount it has earned since the last time it reported to
// the Vault.
uint256 totalDebt = vault.strategies(address(this)).totalDebt;
debtOutstanding = vault.report(profit, loss, debtPayment);
// Check if free returns are left, and re-invest them
adjustPosition(debtOutstanding);
// call healthCheck contract
if (doHealthCheck && healthCheck != address(0)) {
require(HealthCheck(healthCheck).check(profit, loss, debtPayment, debtOutstanding, totalDebt), "!healthcheck");
} else {
doHealthCheck = true;
}
emit Harvested(profit, loss, debtPayment, debtOutstanding);
}
/**
* @notice
* Withdraws `_amountNeeded` to `vault`.
*
* This may only be called by the Vault.
* @param _amountNeeded How much `want` to withdraw.
* @return _loss Any realized losses
*/
function withdraw(uint256 _amountNeeded) external returns (uint256 _loss) {
require(msg.sender == address(vault), "!vault");
// Liquidate as much as possible to `want`, up to `_amountNeeded`
uint256 amountFreed;
(amountFreed, _loss) = liquidatePosition(_amountNeeded);
// Send it directly back (NOTE: Using `msg.sender` saves some gas here)
want.safeTransfer(msg.sender, amountFreed);
// NOTE: Reinvest anything leftover on next `tend`/`harvest`
}
/**
* Do anything necessary to prepare this Strategy for migration, such as
* transferring any reserve or LP tokens, CDPs, or other tokens or stores of
* value.
*/
function prepareMigration(address _newStrategy) internal virtual;
/**
* @notice
* Transfers all `want` from this Strategy to `_newStrategy`.
*
* This may only be called by the Vault.
* @dev
* The new Strategy's Vault must be the same as this Strategy's Vault.
* The migration process should be carefully performed to make sure all
* the assets are migrated to the new address, which should have never
* interacted with the vault before.
* @param _newStrategy The Strategy to migrate to.
*/
function migrate(address _newStrategy) external {
require(msg.sender == address(vault));
require(BaseStrategy(_newStrategy).vault() == vault);
prepareMigration(_newStrategy);
want.safeTransfer(_newStrategy, want.balanceOf(address(this)));
}
/**
* @notice
* Activates emergency exit. Once activated, the Strategy will exit its
* position upon the next harvest, depositing all funds into the Vault as
* quickly as is reasonable given on-chain conditions.
*
* This may only be called by governance or the strategist.
* @dev
* See `vault.setEmergencyShutdown()` and `harvest()` for further details.
*/
function setEmergencyExit() external onlyEmergencyAuthorized {
emergencyExit = true;
vault.revokeStrategy();
emit EmergencyExitEnabled();
}
/**
* Override this to add all tokens/tokenized positions this contract
* manages on a *persistent* basis (e.g. not just for swapping back to
* want ephemerally).
*
* NOTE: Do *not* include `want`, already included in `sweep` below.
*
* Example:
* ```
* function protectedTokens() internal override view returns (address[] memory) {
* address[] memory protected = new address[](3);
* protected[0] = tokenA;
* protected[1] = tokenB;
* protected[2] = tokenC;
* return protected;
* }
* ```
*/
function protectedTokens() internal view virtual returns (address[] memory);
/**
* @notice
* Removes tokens from this Strategy that are not the type of tokens
* managed by this Strategy. This may be used in case of accidentally
* sending the wrong kind of token to this Strategy.
*
* Tokens will be sent to `governance()`.
*
* This will fail if an attempt is made to sweep `want`, or any tokens
* that are protected by this Strategy.
*
* This may only be called by governance.
* @dev
* Implement `protectedTokens()` to specify any additional tokens that
* should be protected from sweeping in addition to `want`.
* @param _token The token to transfer out of this vault.
*/
function sweep(address _token) external onlyGovernance {
require(_token != address(want), "!want");
require(_token != address(vault), "!shares");
address[] memory _protectedTokens = protectedTokens();
for (uint256 i; i < _protectedTokens.length; i++) require(_token != _protectedTokens[i], "!protected");
IERC20(_token).safeTransfer(governance(), IERC20(_token).balanceOf(address(this)));
}
}
// Part: StrategyCurveBase
abstract contract StrategyCurveBase is BaseStrategy {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
/* ========== STATE VARIABLES ========== */
// these should stay the same across different wants.
// curve infrastructure contracts
ICurveStrategyProxy public proxy; // Below we set it to Yearn's Updated v4 StrategyProxy
ICurveFi public curve; // Curve Pool, need this for depositing into our curve pool
address public gauge; // Curve gauge contract, most are tokenized, held by Yearn's voter
// keepCRV stuff
uint256 public keepCRV; // the percentage of CRV we re-lock for boost (in basis points)
uint256 public constant FEE_DENOMINATOR = 10000; // this means all of our fee values are in bips
address public constant voter = 0xF147b8125d2ef93FB6965Db97D6746952a133934; // Yearn's veCRV voter
// swap stuff
address public constant sushiswap =
0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F; // default to sushiswap, more CRV liquidity there
address[] public crvPath;
IERC20 public constant crv =
IERC20(0xD533a949740bb3306d119CC777fa900bA034cd52);
IERC20 public constant weth =
IERC20(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
bool internal forceHarvestTriggerOnce; // only set this to true externally when we want to trigger our keepers to harvest for us
string internal stratName; // set our strategy name here
/* ========== CONSTRUCTOR ========== */
constructor(address _vault) public BaseStrategy(_vault) {}
/* ========== VIEWS ========== */
function name() external view override returns (string memory) {
return stratName;
}
function stakedBalance() public view returns (uint256) {
return proxy.balanceOf(gauge);
}
function balanceOfWant() public view returns (uint256) {
return want.balanceOf(address(this));
}
function estimatedTotalAssets() public view override returns (uint256) {
return balanceOfWant().add(stakedBalance());
}
/* ========== MUTATIVE FUNCTIONS ========== */
// these should stay the same across different wants.
function adjustPosition(uint256 _debtOutstanding) internal override {
if (emergencyExit) {
return;
}
// Send all of our LP tokens to the proxy and deposit to the gauge if we have any
uint256 _toInvest = balanceOfWant();
if (_toInvest > 0) {
want.safeTransfer(address(proxy), _toInvest);
proxy.deposit(gauge, address(want));
}
}
function liquidatePosition(uint256 _amountNeeded)
internal
override
returns (uint256 _liquidatedAmount, uint256 _loss)
{
uint256 _wantBal = balanceOfWant();
if (_amountNeeded > _wantBal) {
// check if we have enough free funds to cover the withdrawal
uint256 _stakedBal = stakedBalance();
if (_stakedBal > 0) {
proxy.withdraw(
gauge,
address(want),
Math.min(_stakedBal, _amountNeeded.sub(_wantBal))
);
}
uint256 _withdrawnBal = balanceOfWant();
_liquidatedAmount = Math.min(_amountNeeded, _withdrawnBal);
_loss = _amountNeeded.sub(_liquidatedAmount);
} else {
// we have enough balance to cover the liquidation available
return (_amountNeeded, 0);
}
}
// fire sale, get rid of it all!
function liquidateAllPositions() internal override returns (uint256) {
uint256 _stakedBal = stakedBalance();
if (_stakedBal > 0) {
// don't bother withdrawing zero
proxy.withdraw(gauge, address(want), _stakedBal);
}
return balanceOfWant();
}
function prepareMigration(address _newStrategy) internal override {
uint256 _stakedBal = stakedBalance();
if (_stakedBal > 0) {
proxy.withdraw(gauge, address(want), _stakedBal);
}
}
function protectedTokens()
internal
view
override
returns (address[] memory)
{}
/* ========== KEEP3RS ========== */
function harvestTrigger(uint256 callCostinEth)
public
view
override
returns (bool)
{
// trigger if we want to manually harvest
if (forceHarvestTriggerOnce) {
return true;
}
// Should not trigger if strategy is not active (no assets and no debtRatio). This means we don't need to adjust keeper job.
if (!isActive()) {
return false;
}
return super.harvestTrigger(callCostinEth);
}
/* ========== SETTERS ========== */
// These functions are useful for setting parameters of the strategy that may need to be adjusted.
// Use to update Yearn's StrategyProxy contract as needed in case of upgrades.
function setProxy(address _proxy) external onlyGovernance {
proxy = ICurveStrategyProxy(_proxy);
}
// Set the amount of CRV to be locked in Yearn's veCRV voter from each harvest. Default is 10%.
function setKeepCRV(uint256 _keepCRV) external onlyAuthorized {
require(_keepCRV <= 10_000);
keepCRV = _keepCRV;
}
// This allows us to manually harvest with our keeper as needed
function setForceHarvestTriggerOnce(bool _forceHarvestTriggerOnce)
external
onlyAuthorized
{
forceHarvestTriggerOnce = _forceHarvestTriggerOnce;
}
}
// File: StrategyCurveibFFClonable.sol
contract StrategyCurveibFFClonable is StrategyCurveBase {
/* ========== STATE VARIABLES ========== */
// these will likely change across different wants.
// swap stuff
IERC20 public ibToken;
// check for cloning
bool internal isOriginal = true;
/* ========== CONSTRUCTOR ========== */
constructor(
address _vault,
address _curvePool,
address _gauge,
address _ibToken,
string memory _name
) public StrategyCurveBase(_vault) {
_initializeStrat(_curvePool, _gauge, _ibToken, _name);
}
/* ========== CLONING ========== */
event Cloned(address indexed clone);
// we use this to clone our original strategy to other vaults
function cloneCurveibFF(
address _vault,
address _strategist,
address _rewards,
address _keeper,
address _curvePool,
address _gauge,
address _ibToken,
string memory _name
) external returns (address newStrategy) {
require(isOriginal);
// Copied from https://github.com/optionality/clone-factory/blob/master/contracts/CloneFactory.sol
bytes20 addressBytes = bytes20(address(this));
assembly {
// EIP-1167 bytecode
let clone_code := mload(0x40)
mstore(
clone_code,
0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000
)
mstore(add(clone_code, 0x14), addressBytes)
mstore(
add(clone_code, 0x28),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
newStrategy := create(0, clone_code, 0x37)
}
StrategyCurveibFFClonable(newStrategy).initialize(
_vault,
_strategist,
_rewards,
_keeper,
_curvePool,
_gauge,
_ibToken,
_name
);
emit Cloned(newStrategy);
}
// this will only be called by the clone function above
function initialize(
address _vault,
address _strategist,
address _rewards,
address _keeper,
address _curvePool,
address _gauge,
address _ibToken,
string memory _name
) public {
_initialize(_vault, _strategist, _rewards, _keeper);
_initializeStrat(_curvePool, _gauge, _ibToken, _name);
}
// this is called by our original strategy, as well as any clones
function _initializeStrat(
address _curvePool,
address _gauge,
address _ibToken,
string memory _name
) internal {
// You can set these parameters on deployment to whatever you want
maxReportDelay = 7 days; // 7 days in seconds
debtThreshold = 5 * 1e18; // we shouldn't ever have debt, but set a bit of a buffer
profitFactor = 10_000; // in this strategy, profitFactor is only used for telling keep3rs when to move funds from vault to strategy
healthCheck = 0xDDCea799fF1699e98EDF118e0629A974Df7DF012; // health.ychad.eth
// need to set our proxy again when cloning since it's not a constant
proxy = ICurveStrategyProxy(0xA420A63BbEFfbda3B147d0585F1852C358e2C152);
// these are our standard approvals. want = Curve LP token
want.approve(address(proxy), type(uint256).max);
crv.approve(sushiswap, type(uint256).max);
// set our keepCRV
keepCRV = 1000;
// this is the pool specific to this vault, used for depositing
curve = ICurveFi(_curvePool);
// set our curve gauge contract
gauge = address(_gauge);
// set our strategy's name
stratName = _name;
// set our token to swap for and deposit with
ibToken = IERC20(_ibToken);
// these are our approvals and path specific to this contract
ibToken.approve(address(curve), type(uint256).max);
// crv token path
crvPath = [address(crv), address(weth), address(ibToken)];
}
/* ========== MUTATIVE FUNCTIONS ========== */
// these will likely change across different wants.
function prepareReturn(uint256 _debtOutstanding)
internal
override
returns (
uint256 _profit,
uint256 _loss,
uint256 _debtPayment
)
{
// if we have anything in the gauge, then harvest CRV from the gauge
uint256 _stakedBal = stakedBalance();
if (_stakedBal > 0) {
proxy.harvest(gauge);
uint256 _crvBalance = crv.balanceOf(address(this));
// if we claimed any CRV, then sell it
if (_crvBalance > 0) {
// keep some of our CRV to increase our boost
uint256 _sendToVoter =
_crvBalance.mul(keepCRV).div(FEE_DENOMINATOR);
if (keepCRV > 0) {
crv.safeTransfer(voter, _sendToVoter);
}
uint256 _crvRemainder = _crvBalance.sub(_sendToVoter);
// sell the rest of our CRV
if (_crvRemainder > 0) {
_sell(_crvRemainder);
}
// deposit our ibEUR to Curve if we have any
uint256 _ibTokenBalance = ibToken.balanceOf(address(this));
if (_ibTokenBalance > 0) {
curve.add_liquidity([_ibTokenBalance, 0], 0);
}
}
}
// debtOustanding will only be > 0 in the event of revoking or if we need to rebalance from a withdrawal or lowering the debtRatio
if (_debtOutstanding > 0) {
if (_stakedBal > 0) {
// don't bother withdrawing if we don't have staked funds
proxy.withdraw(
gauge,
address(want),
Math.min(_stakedBal, _debtOutstanding)
);
}
uint256 _withdrawnBal = balanceOfWant();
_debtPayment = Math.min(_debtOutstanding, _withdrawnBal);
}
// serious loss should never happen, but if it does (for instance, if Curve is hacked), let's record it accurately
uint256 assets = estimatedTotalAssets();
uint256 debt = vault.strategies(address(this)).totalDebt;
// if assets are greater than debt, things are working great!
if (assets > debt) {
_profit = assets.sub(debt);
uint256 _wantBal = balanceOfWant();
if (_profit.add(_debtPayment) > _wantBal) {
// this should only be hit following donations to strategy
liquidateAllPositions();
}
}
// if assets are less than debt, we are in trouble
else {
_loss = debt.sub(assets);
}
// we're done harvesting, so reset our trigger if we used it
forceHarvestTriggerOnce = false;
}
// Sells our harvested CRV into the selected output.
function _sell(uint256 _amount) internal {
IUniswapV2Router02(sushiswap).swapExactTokensForTokens(
_amount,
uint256(0),
crvPath,
address(this),
block.timestamp
);
}
/* ========== KEEP3RS ========== */
// convert our keeper's eth cost into want
function ethToWant(uint256 _ethAmount)
public
view
override
returns (uint256)
{
uint256 callCostInWant;
if (_ethAmount > 0) {
address[] memory ethPath = new address[](2);
ethPath[0] = address(weth);
ethPath[1] = address(ibToken);
uint256[] memory _callCostInIbTokenTuple =
IUniswapV2Router02(sushiswap).getAmountsOut(
_ethAmount,
ethPath
);
uint256 _callCostInIbToken =
_callCostInIbTokenTuple[_callCostInIbTokenTuple.length - 1];
callCostInWant = curve.calc_token_amount(
[_callCostInIbToken, 0],
true
);
}
return callCostInWant;
}
}
|
this will only be called by the clone function above
|
function initialize(
address _vault,
address _strategist,
address _rewards,
address _keeper,
address _curvePool,
address _gauge,
address _ibToken,
string memory _name
) public {
_initialize(_vault, _strategist, _rewards, _keeper);
_initializeStrat(_curvePool, _gauge, _ibToken, _name);
}
| 413,619 |
//Address: 0xaa3e80a42e7bac1072bee7ee5ac72123969b8400
//Contract name: BlindCroupierTokenDistribution
//Balance: 0.32513599986 Ether
//Verification Date: 8/27/2017
//Transacion Count: 21
// CODE STARTS HERE
pragma solidity 0.4.15;
pragma solidity 0.4.15;
/**
* @title MultiOwnable
* allows creating contracts with up to 16 owners with their shares
*/
contract MultiOwnable {
/** a single owner record */
struct Owner {
address recipient;
uint share;
}
/** contract owners */
Owner[] public owners;
/**
* Returns total owners count
* @return count - owners count
*/
function ownersCount () constant returns (uint count) {
return owners.length;
}
/**
* Returns owner's info
* @param idx - index of the owner
* @return owner - owner's info
*/
function owner (uint idx) constant returns (address owner_dot_recipient, uint owner_dot_share) {
Owner memory owner;
owner = owners[idx];
owner_dot_recipient = address(owner.recipient);
owner_dot_share = uint(owner.share);}
/** reverse lookup helper */
mapping (address => bool) ownersIdx;
/**
* Creates the contract with up to 16 owners
* shares must be > 0
*/
function MultiOwnable (address[16] _owners_dot_recipient, uint[16] _owners_dot_share) {
Owner[16] memory _owners;
for(uint __recipient_iterator__ = 0; __recipient_iterator__ < _owners_dot_recipient.length;__recipient_iterator__++)
_owners[__recipient_iterator__].recipient = address(_owners_dot_recipient[__recipient_iterator__]);
for(uint __share_iterator__ = 0; __share_iterator__ < _owners_dot_share.length;__share_iterator__++)
_owners[__share_iterator__].share = uint(_owners_dot_share[__share_iterator__]);
for(var idx = 0; idx < _owners_dot_recipient.length; idx++) {
if(_owners[idx].recipient != 0) {
owners.push(_owners[idx]);
assert(owners[idx].share > 0);
ownersIdx[_owners[idx].recipient] = true;
}
}
}
/**
* Function with this modifier can be called only by one of owners
*/
modifier onlyOneOfOwners() {
require(ownersIdx[msg.sender]);
_;
}
}
pragma solidity 0.4.15;
pragma solidity 0.4.15;
/**
* Basic interface for contracts, following ERC20 standard
*/
contract ERC20Token {
/**
* Triggered when tokens are transferred.
* @param from - address tokens were transfered from
* @param to - address tokens were transfered to
* @param value - amount of tokens transfered
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* Triggered whenever allowance status changes
* @param owner - tokens owner, allowance changed for
* @param spender - tokens spender, allowance changed for
* @param value - new allowance value (overwriting the old value)
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* Returns total supply of tokens ever emitted
* @return totalSupply - total supply of tokens ever emitted
*/
function totalSupply() constant returns (uint256 totalSupply);
/**
* Returns `owner` balance of tokens
* @param owner address to request balance for
* @return balance - token balance of `owner`
*/
function balanceOf(address owner) constant returns (uint256 balance);
/**
* Transfers `amount` of tokens to `to` address
* @param to - address to transfer to
* @param value - amount of tokens to transfer
* @return success - `true` if the transfer was succesful, `false` otherwise
*/
function transfer(address to, uint256 value) returns (bool success);
/**
* Transfers `value` tokens from `from` address to `to`
* the sender needs to have allowance for this operation
* @param from - address to take tokens from
* @param to - address to send tokens to
* @param value - amount of tokens to send
* @return success - `true` if the transfer was succesful, `false` otherwise
*/
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
* @param spender - address to give allowance to
* @param value - the maximum amount of tokens allowed for spending
* @return success - `true` if the allowance was given, `false` otherwise
*/
function approve(address spender, uint256 value) returns (bool success);
/**
* Returns the amount which `spender` is still allowed to withdraw from `owner`
* @param owner - tokens owner
* @param spender - addres to request allowance for
* @return remaining - remaining allowance (token count)
*/
function allowance(address owner, address spender) constant returns (uint256 remaining);
}
/**
* @title Blind Croupier Token
* WIN fixed supply Token, used for Blind Croupier TokenDistribution
*/
contract WIN is ERC20Token {
string public constant symbol = "WIN";
string public constant name = "WIN";
uint8 public constant decimals = 7;
uint256 constant TOKEN = 10**7;
uint256 constant MILLION = 10**6;
uint256 public totalTokenSupply = 500 * MILLION * TOKEN;
/** balances of each accounts */
mapping(address => uint256) balances;
/** amount of tokens approved for transfer */
mapping(address => mapping (address => uint256)) allowed;
/** Triggered when `owner` destroys `amount` tokens */
event Destroyed(address indexed owner, uint256 amount);
/**
* Constucts the token, and supplies the creator with `totalTokenSupply` tokens
*/
function WIN () {
balances[msg.sender] = totalTokenSupply;
}
/**
* Returns total supply of tokens ever emitted
* @return result - total supply of tokens ever emitted
*/
function totalSupply () constant returns (uint256 result) {
result = totalTokenSupply;
}
/**
* Returns `owner` balance of tokens
* @param owner address to request balance for
* @return balance - token balance of `owner`
*/
function balanceOf (address owner) constant returns (uint256 balance) {
return balances[owner];
}
/**
* Transfers `amount` of tokens to `to` address
* @param to - address to transfer to
* @param amount - amount of tokens to transfer
* @return success - `true` if the transfer was succesful, `false` otherwise
*/
function transfer (address to, uint256 amount) returns (bool success) {
if(balances[msg.sender] < amount)
return false;
if(amount <= 0)
return false;
if(balances[to] + amount <= balances[to])
return false;
balances[msg.sender] -= amount;
balances[to] += amount;
Transfer(msg.sender, to, amount);
return true;
}
/**
* Transfers `amount` tokens from `from` address to `to`
* the sender needs to have allowance for this operation
* @param from - address to take tokens from
* @param to - address to send tokens to
* @param amount - amount of tokens to send
* @return success - `true` if the transfer was succesful, `false` otherwise
*/
function transferFrom (address from, address to, uint256 amount) returns (bool success) {
if (balances[from] < amount)
return false;
if(allowed[from][msg.sender] < amount)
return false;
if(amount == 0)
return false;
if(balances[to] + amount <= balances[to])
return false;
balances[from] -= amount;
allowed[from][msg.sender] -= amount;
balances[to] += amount;
Transfer(from, to, amount);
return true;
}
/**
* Allow spender to withdraw from your account, multiple times, up to the amount amount.
* If this function is called again it overwrites the current allowance with `amount`.
* this function is required for some DEX functionality
* @param spender - address to give allowance to
* @param amount - the maximum amount of tokens allowed for spending
* @return success - `true` if the allowance was given, `false` otherwise
*/
function approve (address spender, uint256 amount) returns (bool success) {
allowed[msg.sender][spender] = amount;
Approval(msg.sender, spender, amount);
return true;
}
/**
* Returns the amount which `spender` is still allowed to withdraw from `owner`
* @param owner - tokens owner
* @param spender - addres to request allowance for
* @return remaining - remaining allowance (token count)
*/
function allowance (address owner, address spender) constant returns (uint256 remaining) {
return allowed[owner][spender];
}
/**
* Destroys `amount` of tokens permanently, they cannot be restored
* @return success - `true` if `amount` of tokens were destroyed, `false` otherwise
*/
function destroy (uint256 amount) returns (bool success) {
if(amount == 0) return false;
if(balances[msg.sender] < amount) return false;
balances[msg.sender] -= amount;
totalTokenSupply -= amount;
Destroyed(msg.sender, amount);
}
}
pragma solidity 0.4.15;
/**
* @title Various Math utilities
*/
library Math {
/** 1/1000, 1000 uint = 1 */
/**
* Returns `promille` promille of `value`
* e.g. `takePromille(5000, 1) == 5`
* @param value - uint to take promille value
* @param promille - promille value
* @return result - `value * promille / 1000`
*/
function takePromille (uint value, uint promille) constant returns (uint result) {
result = value * promille / 1000;
}
/**
* Returns `value` with added `promille` promille
* @param value - uint to add promille to
* @param promille - promille value to add
* @return result - `value + value * promille / 1000`
*/
function addPromille (uint value, uint promille) constant returns (uint result) {
result = value + takePromille(value, promille);
}
}
/**
* @title Blind Croupier TokenDistribution
* It possesses some `WIN` tokens.
* The distribution is divided into many 'periods'.
* The zero one is `Presale` with `TOKENS_FOR_PRESALE` tokens
* It's ended when all tokens are sold or manually with `endPresale()` function
* The length of first period is `FIRST_PERIOD_DURATION`.
* The length of other periods is `PERIOD_DURATION`.
* During each period, `TOKENS_PER_PERIOD` are offered for sale (`TOKENS_PER_FIRST_PERIOD` for the first one)
* Investors send their money to the contract
* and call `claimAllTokens()` function to get `WIN` tokens.
* Period 0 Token price is `PRESALE_TOKEN_PRICE`
* Period 1 Token price is `SALE_INITIAL_TOKEN_PRICE`
* Period 2+ price is determined by the following rules:
* If more than `TOKENS_TO_INCREASE_NEXT_PRICE * TOKENS_PER_PERIOD / 1000`
* were sold during the period, the price of the Tokens for the next period
* is increased by `PERIOD_PRICE_INCREASE` promille,
* if ALL tokens were sold, price is increased by `FULLY_SOLD_PRICE_INCREASE` promille
* Otherwise, the price remains the same.
*/
contract BlindCroupierTokenDistribution is MultiOwnable {
uint256 constant TOKEN = 10**7;
uint256 constant MILLION = 10**6;
uint256 constant MINIMUM_DEPOSIT = 100 finney; /** minimum deposit accepted to bank */
uint256 constant PRESALE_TOKEN_PRICE = 0.00035 ether / TOKEN;
uint256 constant SALE_INITIAL_TOKEN_PRICE = 0.0005 ether / TOKEN;
uint256 constant TOKENS_FOR_PRESALE = 5 * MILLION * TOKEN; /** 5M tokens */
uint256 constant TOKENS_PER_FIRST_PERIOD = 15 * MILLION * TOKEN; /** 15M tokens */
uint256 constant TOKENS_PER_PERIOD = 1 * MILLION * TOKEN; /** 1M tokens */
uint256 constant FIRST_PERIOD_DURATION = 161 hours; /** duration of 1st sale period */
uint256 constant PERIOD_DURATION = 23 hours; /** duration of all other sale periods */
uint256 constant PERIOD_PRICE_INCREASE = 5; /** `next_token_price = old_token_price + old_token_price * PERIOD_PRICE_INCREASE / 1000` */
uint256 constant FULLY_SOLD_PRICE_INCREASE = 10; /** to increase price if ALL tokens sold */
uint256 constant TOKENS_TO_INCREASE_NEXT_PRICE = 800; /** the price is increased if `sold_tokens > period_tokens * TOKENS_TO_INCREASE_NEXT_PRICE / 1000` */
uint256 constant NEVER = 0;
uint16 constant UNKNOWN_COUNTRY = 0;
/**
* State of Blind Croupier crowdsale
*/
enum State {
NotStarted,
Presale,
Sale
}
uint256 public totalUnclaimedTokens; /** total amount of tokens, TokenDistribution owns to investors */
uint256 public totalTokensSold; /** total amount of Tokens sold during the TokenDistribution */
uint256 public totalTokensDestroyed; /** total amount of Tokens destroyed by this contract */
mapping(address => uint256) public unclaimedTokensForInvestor; /** unclaimed tokens for each investor */
/**
* One token sale period information
*/
struct Period {
uint256 startTime;
uint256 endTime;
uint256 tokenPrice;
uint256 tokensSold;
}
/**
* Emited when `investor` sends `amount` of money to the Bank
* @param investor - address, sending the money
* @param amount - Wei sent
*/
event Deposited(address indexed investor, uint256 amount, uint256 tokenCount);
/**
* Emited when a new period is opened
* @param periodIndex - index of new period
* @param tokenPrice - price of WIN Token in new period
*/
event PeriodStarted(uint periodIndex, uint256 tokenPrice, uint256 tokensToSale, uint256 startTime, uint256 endTime, uint256 now);
/**
* Emited when `investor` claims `claimed` tokens
* @param investor - address getting the Tokens
* @param claimed - amount of Tokens claimed
*/
event TokensClaimed(address indexed investor, uint256 claimed);
/** current Token sale period */
uint public currentPeriod = 0;
/** information about past and current periods, by periods index, starting from `0` */
mapping(uint => Period) periods;
/** WIN tokens contract */
WIN public win;
/** The state of the crowdsale - `NotStarted`, `Presale`, `Sale` */
State public state;
/** the counter of investment by a country code (3-digit ISO 3166 code) */
mapping(uint16 => uint256) investmentsByCountries;
/**
* Returns amount of Wei invested by the specified country
* @param country - 3-digit country code
*/
function getInvestmentsByCountry (uint16 country) constant returns (uint256 investment) {
investment = investmentsByCountries[country];
}
/**
* Returns the Token price in the current period
* @return tokenPrice - current Token price
*/
function getTokenPrice () constant returns (uint256 tokenPrice) {
tokenPrice = periods[currentPeriod].tokenPrice;
}
/**
* Returns the Token price for the period requested
* @param periodIndex - the period index
* @return tokenPrice - Token price for the period
*/
function getTokenPriceForPeriod (uint periodIndex) constant returns (uint256 tokenPrice) {
tokenPrice = periods[periodIndex].tokenPrice;
}
/**
* Returns the amount of Tokens sold
* @param period - period index to get tokens for
* @return tokensSold - amount of tokens sold
*/
function getTokensSold (uint period) constant returns (uint256 tokensSold) {
return periods[period].tokensSold;
}
/**
* Returns `true` if TokenDistribution has enough tokens for the current period
* and thus going on
* @return active - `true` if TokenDistribution is going on, `false` otherwise
*/
function isActive () constant returns (bool active) {
return win.balanceOf(this) >= totalUnclaimedTokens + tokensForPeriod(currentPeriod) - periods[currentPeriod].tokensSold;
}
/**
* Accepts money deposit and makes record
* minimum deposit is MINIMUM_DEPOSIT
* @param beneficiar - the address to receive Tokens
* @param countryCode - 3-digit country code
* @dev if `msg.value < MINIMUM_DEPOSIT` throws
*/
function deposit (address beneficiar, uint16 countryCode) payable {
require(msg.value >= MINIMUM_DEPOSIT);
require(state == State.Sale || state == State.Presale);
/* this should end any finished period before starting any operations */
tick();
/* check if have enough tokens for the current period
* if not, the call fails until tokens are deposited to the contract
*/
require(isActive());
uint256 tokensBought = msg.value / getTokenPrice();
if(periods[currentPeriod].tokensSold + tokensBought >= tokensForPeriod(currentPeriod)) {
tokensBought = tokensForPeriod(currentPeriod) - periods[currentPeriod].tokensSold;
}
uint256 moneySpent = getTokenPrice() * tokensBought;
investmentsByCountries[countryCode] += moneySpent;
if(tokensBought > 0) {
assert(moneySpent <= msg.value);
/* return the rest */
if(msg.value > moneySpent) {
msg.sender.transfer(msg.value - moneySpent);
}
periods[currentPeriod].tokensSold += tokensBought;
unclaimedTokensForInvestor[beneficiar] += tokensBought;
totalUnclaimedTokens += tokensBought;
totalTokensSold += tokensBought;
Deposited(msg.sender, moneySpent, tokensBought);
}
/* if all tokens are sold, get to the next period */
tick();
}
/**
* See `deposit` function
*/
function() payable {
deposit(msg.sender, UNKNOWN_COUNTRY);
}
/**
* Creates the contract and sets the owners
* @param owners_dot_recipient - array of 16 owner records (MultiOwnable.Owner.recipient fields)
* @param owners_dot_share - array of 16 owner records (MultiOwnable.Owner.share fields)
*/
function BlindCroupierTokenDistribution (address[16] owners_dot_recipient, uint[16] owners_dot_share) MultiOwnable(owners_dot_recipient, owners_dot_share) {
MultiOwnable.Owner[16] memory owners;
for(uint __recipient_iterator__ = 0; __recipient_iterator__ < owners_dot_recipient.length;__recipient_iterator__++)
owners[__recipient_iterator__].recipient = address(owners_dot_recipient[__recipient_iterator__]);
for(uint __share_iterator__ = 0; __share_iterator__ < owners_dot_share.length;__share_iterator__++)
owners[__share_iterator__].share = uint(owners_dot_share[__share_iterator__]);
state = State.NotStarted;
}
/**
* Begins the crowdsale (presale period)
* @param tokenContractAddress - address of the `WIN` contract (token holder)
* @dev must be called by one of owners
*/
function startPresale (address tokenContractAddress) onlyOneOfOwners {
require(state == State.NotStarted);
win = WIN(tokenContractAddress);
assert(win.balanceOf(this) >= tokensForPeriod(0));
periods[0] = Period(now, NEVER, PRESALE_TOKEN_PRICE, 0);
PeriodStarted(0,
PRESALE_TOKEN_PRICE,
tokensForPeriod(currentPeriod),
now,
NEVER,
now);
state = State.Presale;
}
/**
* Ends the presale and begins period 1 of the crowdsale
* @dev must be called by one of owners
*/
function endPresale () onlyOneOfOwners {
require(state == State.Presale);
state = State.Sale;
nextPeriod();
}
/**
* Returns a time interval for a specific `period`
* @param period - period index to count interval for
* @return startTime - timestamp of period start time (INCLUSIVE)
* @return endTime - timestamp of period end time (INCLUSIVE)
*/
function periodTimeFrame (uint period) constant returns (uint256 startTime, uint256 endTime) {
require(period <= currentPeriod);
startTime = periods[period].startTime;
endTime = periods[period].endTime;
}
/**
* Returns `true` if the time for the `period` has already passed
*/
function isPeriodTimePassed (uint period) constant returns (bool finished) {
require(periods[period].startTime > 0);
uint256 endTime = periods[period].endTime;
if(endTime == NEVER) {
return false;
}
return (endTime < now);
}
/**
* Returns `true` if `period` has already finished (time passed or tokens sold)
*/
function isPeriodClosed (uint period) constant returns (bool finished) {
return period < currentPeriod;
}
/**
* Returns `true` if all tokens for the `period` has been sold
*/
function isPeriodAllTokensSold (uint period) constant returns (bool finished) {
return periods[period].tokensSold == tokensForPeriod(period);
}
/**
* Returns unclaimed Tokens count for the caller
* @return tokens - amount of unclaimed Tokens for the caller
*/
function unclaimedTokens () constant returns (uint256 tokens) {
return unclaimedTokensForInvestor[msg.sender];
}
/**
* Transfers all the tokens stored for this `investor` to his address
* @param investor - investor to claim tokens for
*/
function claimAllTokensForInvestor (address investor) {
assert(totalUnclaimedTokens >= unclaimedTokensForInvestor[investor]);
totalUnclaimedTokens -= unclaimedTokensForInvestor[investor];
win.transfer(investor, unclaimedTokensForInvestor[investor]);
TokensClaimed(investor, unclaimedTokensForInvestor[investor]);
unclaimedTokensForInvestor[investor] = 0;
}
/**
* Claims all the tokens for the sender
* @dev efficiently calling `claimAllForInvestor(msg.sender)`
*/
function claimAllTokens () {
claimAllTokensForInvestor(msg.sender);
}
/**
* Returns the total token count for the period specified
* @param period - period number
* @return tokens - total tokens count
*/
function tokensForPeriod (uint period) constant returns (uint256 tokens) {
if(period == 0) {
return TOKENS_FOR_PRESALE;
} else if(period == 1) {
return TOKENS_PER_FIRST_PERIOD;
} else {
return TOKENS_PER_PERIOD;
}
}
/**
* Returns the duration of the sale (not presale) period
* @param period - the period number
* @return duration - duration in seconds
*/
function periodDuration (uint period) constant returns (uint256 duration) {
require(period > 0);
if(period == 1) {
return FIRST_PERIOD_DURATION;
} else {
return PERIOD_DURATION;
}
}
/**
* Finishes the current period and starts a new one
*/
function nextPeriod() internal {
uint256 oldPrice = periods[currentPeriod].tokenPrice;
uint256 newPrice;
if(currentPeriod == 0) {
newPrice = SALE_INITIAL_TOKEN_PRICE;
} else if(periods[currentPeriod].tokensSold == tokensForPeriod(currentPeriod)) {
newPrice = Math.addPromille(oldPrice, FULLY_SOLD_PRICE_INCREASE);
} else if(periods[currentPeriod].tokensSold >= Math.takePromille(tokensForPeriod(currentPeriod), TOKENS_TO_INCREASE_NEXT_PRICE)) {
newPrice = Math.addPromille(oldPrice, PERIOD_PRICE_INCREASE);
} else {
newPrice = oldPrice;
}
/* destroy unsold tokens */
if(periods[currentPeriod].tokensSold < tokensForPeriod(currentPeriod)) {
uint256 toDestroy = tokensForPeriod(currentPeriod) - periods[currentPeriod].tokensSold;
/* do not destroy if we don't have enough to pay investors */
uint256 balance = win.balanceOf(this);
if(balance < toDestroy + totalUnclaimedTokens) {
toDestroy = (balance - totalUnclaimedTokens);
}
win.destroy(toDestroy);
totalTokensDestroyed += toDestroy;
}
/* if we are force ending the period set in the future or without end time,
* set end time to now
*/
if(periods[currentPeriod].endTime > now ||
periods[currentPeriod].endTime == NEVER) {
periods[currentPeriod].endTime = now;
}
uint256 duration = periodDuration(currentPeriod + 1);
periods[currentPeriod + 1] = Period(
periods[currentPeriod].endTime,
periods[currentPeriod].endTime + duration,
newPrice,
0);
currentPeriod++;
PeriodStarted(currentPeriod,
newPrice,
tokensForPeriod(currentPeriod),
periods[currentPeriod].startTime,
periods[currentPeriod].endTime,
now);
}
/**
* To be called as frequently as required by any external party
* Will check if 1 or more periods have finished and move on to the next
*/
function tick () {
if(!isActive()) {
return;
}
while(state == State.Sale &&
(isPeriodTimePassed(currentPeriod) ||
isPeriodAllTokensSold(currentPeriod))) {
nextPeriod();
}
}
/**
* Withdraws the money to be spent to Blind Croupier Project needs
* @param amount - amount of Wei to withdraw (total)
*/
function withdraw (uint256 amount) onlyOneOfOwners {
require(this.balance >= amount);
uint totalShares = 0;
for(var idx = 0; idx < owners.length; idx++) {
totalShares += owners[idx].share;
}
for(idx = 0; idx < owners.length; idx++) {
owners[idx].recipient.transfer(amount * owners[idx].share / totalShares);
}
}
}
|
Transfers all the tokens stored for this `investor` to his address investor - investor to claim tokens for/
|
function claimAllTokensForInvestor (address investor) {
assert(totalUnclaimedTokens >= unclaimedTokensForInvestor[investor]);
totalUnclaimedTokens -= unclaimedTokensForInvestor[investor];
win.transfer(investor, unclaimedTokensForInvestor[investor]);
TokensClaimed(investor, unclaimedTokensForInvestor[investor]);
unclaimedTokensForInvestor[investor] = 0;
}
| 5,467,285 |
/**
* SPDX-License-Identifier: UNLICENSED
*/
pragma solidity 0.8.11;
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
contract HFT {
/// @notice EIP-20 token name for this token
string public constant name = 'Hashflow';
/// @notice EIP-20 token symbol for this token
string public constant symbol = 'HFT';
/// @notice EIP-20 token decimals for this token
uint8 public constant decimals = 18;
/// @notice Total number of tokens in circulation
uint256 public totalSupply = 1_000_000_000e18; // 1 billion HFT
/// @notice Address which may mint new tokens
address public minter;
/// @notice The timestamp after which minting may occur (must be set to 4 years)
uint256 public mintingAllowedAfter;
/// @notice Minimum time between mints
uint32 public constant minimumTimeBetweenMints = 1 days * 365;
/// @notice Cap on the percentage of totalSupply that can be minted at each mint (set to 5% inflation currently)
uint8 public mintCap = 5;
/// @notice Allowance amounts on behalf of others
mapping(address => mapping(address => uint96)) internal allowances;
/// @notice Official record of token balances for each account
mapping(address => uint96) internal balances;
/// @notice A record of each accounts delegate
mapping(address => address) public delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint96 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping(address => mapping(uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping(address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH =
keccak256(
'EIP712Domain(string name,uint256 chainId,address verifyingContract)'
);
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH =
keccak256('Delegation(address delegatee,uint256 nonce,uint256 expiry)');
/// @notice The EIP-712 typehash for the permit struct used by the contract
bytes32 public constant PERMIT_TYPEHASH =
keccak256(
'Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)'
);
/// @notice A record of states for signing / validating signatures
mapping(address => uint256) public nonces;
/// @notice An event that is emitted when the minter address is changed
event MinterChanged(address minter, address newMinter);
/// @notice An event that is emitted when the mint percentage is changed
event MintCapChanged(uint256 newMintCap);
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(
address indexed delegator,
address indexed fromDelegate,
address indexed toDelegate
);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(
address indexed delegate,
uint256 previousBalance,
uint256 newBalance
);
/// @notice The standard EIP-20 transfer event
event Transfer(address indexed from, address indexed to, uint256 amount);
/// @notice The standard EIP-20 approval event
event Approval(
address indexed owner,
address indexed spender,
uint256 amount
);
/**
* @notice Construct a new Hashflow token
* @param account The initial account to grant all the tokens
* @param minter_ The account with minting ability
* @param mintingAllowedAfter_ The timestamp after which minting may occur
*/
constructor(
address account,
address minter_,
uint256 mintingAllowedAfter_
) {
require(
mintingAllowedAfter_ >= block.timestamp + 1460 days,
'HFT::constructor: minting can only begin after 4 years'
);
require(
minter_ != address(0),
'HFT::constructor: minter_ cannot be zero address'
);
require(
account != address(0),
'HFT::constructor: account cannot be zero address'
);
balances[account] = uint96(totalSupply);
emit Transfer(address(0), account, totalSupply);
minter = minter_;
emit MinterChanged(address(0), minter);
mintingAllowedAfter = mintingAllowedAfter_;
}
/**
* @notice Change the minter address
* @param minter_ The address of the new minter
*/
function setMinter(address minter_) external {
require(
minter_ != address(0),
'HFT::setMinter: minter_ cannot be zero address'
);
require(
msg.sender == minter,
'HFT::setMinter: only the minter can change the minter address'
);
minter = minter_;
emit MinterChanged(minter, minter_);
}
function setMintCap(uint256 mintCap_) external {
require(
msg.sender == minter,
'HFT::setMintCap: only the minter can change the mint cap'
);
require(
mintCap_ <= 100,
'HFT::setMintCap: mint cap should be between 0 and 100'
);
mintCap = uint8(mintCap_);
emit MintCapChanged(uint256(mintCap));
}
/**
* @notice Mint new tokens
* @param dst The address of the destination account
*/
function mint(address dst) external {
require(msg.sender == minter, 'HFT::mint: only the minter can mint');
require(
block.timestamp >= mintingAllowedAfter,
'HFT::mint: minting not allowed yet or exceeds mint cap'
);
require(
dst != address(0),
'HFT::mint: cannot transfer to the zero address'
);
// record the mint
mintingAllowedAfter = SafeMath.add(
block.timestamp,
minimumTimeBetweenMints
);
uint96 amount = safe96(
SafeMath.div(SafeMath.mul(totalSupply, uint256(mintCap)), 100),
'HFT::mint: amount exceeds 96 bits'
);
totalSupply = safe96(
SafeMath.add(totalSupply, amount),
'HFT::mint: totalSupply exceeds 96 bits'
);
// transfer the amount to the recipient
balances[dst] = add96(
balances[dst],
amount,
'HFT::mint: transfer amount overflows'
);
emit Transfer(address(0), dst, amount);
// move delegates
_moveDelegates(address(0), delegates[dst], amount);
}
/**
* @notice Get the number of tokens `spender` is approved to spend on behalf of `account`
* @param account The address of the account holding the funds
* @param spender The address of the account spending the funds
* @return The number of tokens approved
*/
function allowance(address account, address spender)
external
view
returns (uint256)
{
return allowances[account][spender];
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param rawAmount The number of tokens that are approved (2^256-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 rawAmount)
external
returns (bool)
{
_approve(msg.sender, spender, rawAmount);
return true;
}
/**
* @notice Atomically increases the allowance granted to `spender` by the caller.
* @dev This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
* @param spender The address of the account which may transfer tokens
* @param rawAmount The number of tokens that are approved (2^256-1 means infinite)
* @return Whether or not the approval succeeded
*/
function increaseAllowance(address spender, uint256 rawAmount)
external
returns (bool)
{
_approve(
msg.sender,
spender,
allowances[msg.sender][spender] + rawAmount
);
return true;
}
/**
* @notice Atomically increases the allowance granted to `spender` by the caller.
* @dev This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
* @param spender The address of the account which may transfer tokens
* @param rawAmount The number of tokens that are approved (2^256-1 means infinite)
* @return Whether or not the approval succeeded
*/
function decreaseAllowance(address spender, uint256 rawAmount)
external
returns (bool)
{
_approve(
msg.sender,
spender,
allowances[msg.sender][spender] - rawAmount
);
return true;
}
/**
* @notice Triggers an approval from owner to spends
* @param owner The address to approve from
* @param spender The address to be approved
* @param rawAmount The number of tokens that are approved (2^256-1 means infinite)
* @param deadline The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function permit(
address owner,
address spender,
uint256 rawAmount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external {
uint96 amount;
if (rawAmount == type(uint256).max) {
amount = type(uint96).max;
} else {
amount = safe96(rawAmount, 'HFT::permit: amount exceeds 96 bits');
}
bytes32 domainSeparator = keccak256(
abi.encode(
DOMAIN_TYPEHASH,
keccak256(bytes(name)),
getChainId(),
address(this)
)
);
bytes32 structHash = keccak256(
abi.encode(
PERMIT_TYPEHASH,
owner,
spender,
rawAmount,
nonces[owner]++,
deadline
)
);
bytes32 digest = keccak256(
abi.encodePacked('\x19\x01', domainSeparator, structHash)
);
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), 'HFT::permit: invalid signature');
require(signatory == owner, 'HFT::permit: unauthorized');
require(block.timestamp <= deadline, 'HFT::permit: signature expired');
allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @notice Get the number of tokens held by the `account`
* @param account The address of the account to get the balance of
* @return The number of tokens held
*/
function balanceOf(address account) external view returns (uint256) {
return balances[account];
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 rawAmount) external returns (bool) {
uint96 amount = safe96(
rawAmount,
'HFT::transfer: amount exceeds 96 bits'
);
_transferTokens(msg.sender, dst, amount);
return true;
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(
address src,
address dst,
uint256 rawAmount
) external returns (bool) {
address spender = msg.sender;
uint96 spenderAllowance = allowances[src][spender];
uint96 amount = safe96(
rawAmount,
'HFT::approve: amount exceeds 96 bits'
);
if (spender != src && spenderAllowance != type(uint96).max) {
uint96 newAllowance = sub96(
spenderAllowance,
amount,
'HFT::transferFrom: transfer amount exceeds spender allowance'
);
allowances[src][spender] = newAllowance;
emit Approval(src, spender, newAllowance);
}
_transferTokens(src, dst, amount);
return true;
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) public {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(
address delegatee,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) public {
bytes32 domainSeparator = keccak256(
abi.encode(
DOMAIN_TYPEHASH,
keccak256(bytes(name)),
getChainId(),
address(this)
)
);
bytes32 structHash = keccak256(
abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry)
);
bytes32 digest = keccak256(
abi.encodePacked('\x19\x01', domainSeparator, structHash)
);
address signatory = ecrecover(digest, v, r, s);
require(
signatory != address(0),
'HFT::delegateBySig: invalid signature'
);
require(
nonce == nonces[signatory]++,
'HFT::delegateBySig: invalid nonce'
);
require(
block.timestamp <= expiry,
'HFT::delegateBySig: signature expired'
);
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account) external view returns (uint96) {
uint32 nCheckpoints = numCheckpoints[account];
return
nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint256 blockNumber)
public
view
returns (uint96)
{
require(
blockNumber < block.number,
'HFT::getPriorVotes: not yet determined'
);
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee) internal {
address currentDelegate = delegates[delegator];
uint96 delegatorBalance = balances[delegator];
delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _approve(
address caller,
address spender,
uint256 rawAmount
) internal {
uint96 amount;
if (rawAmount == type(uint256).max) {
amount = type(uint96).max;
} else {
amount = safe96(rawAmount, 'HFT::approve: amount exceeds 96 bits');
}
allowances[caller][spender] = amount;
emit Approval(caller, spender, amount);
}
function _transferTokens(
address src,
address dst,
uint96 amount
) internal {
require(
src != address(0),
'HFT::_transferTokens: cannot transfer from the zero address'
);
require(
dst != address(0),
'HFT::_transferTokens: cannot transfer to the zero address'
);
balances[src] = sub96(
balances[src],
amount,
'HFT::_transferTokens: transfer amount exceeds balance'
);
balances[dst] = add96(
balances[dst],
amount,
'HFT::_transferTokens: transfer amount overflows'
);
emit Transfer(src, dst, amount);
_moveDelegates(delegates[src], delegates[dst], amount);
}
function _moveDelegates(
address srcRep,
address dstRep,
uint96 amount
) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
uint32 srcRepNum = numCheckpoints[srcRep];
uint96 srcRepOld = srcRepNum > 0
? checkpoints[srcRep][srcRepNum - 1].votes
: 0;
uint96 srcRepNew = sub96(
srcRepOld,
amount,
'HFT::_moveDelegates: vote amount underflows'
);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
uint32 dstRepNum = numCheckpoints[dstRep];
uint96 dstRepOld = dstRepNum > 0
? checkpoints[dstRep][dstRepNum - 1].votes
: 0;
uint96 dstRepNew = add96(
dstRepOld,
amount,
'HFT::_moveDelegates: vote amount overflows'
);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint96 oldVotes,
uint96 newVotes
) internal {
uint32 blockNumber = safe32(
block.number,
'HFT::_writeCheckpoint: block number exceeds 32 bits'
);
if (
nCheckpoints > 0 &&
checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber
) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(
blockNumber,
newVotes
);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint256 n, string memory errorMessage)
internal
pure
returns (uint32)
{
require(n < 2**32, errorMessage);
return uint32(n);
}
function safe96(uint256 n, string memory errorMessage)
internal
pure
returns (uint96)
{
require(n < 2**96, errorMessage);
return uint96(n);
}
function add96(
uint96 a,
uint96 b,
string memory errorMessage
) internal pure returns (uint96) {
uint96 c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub96(
uint96 a,
uint96 b,
string memory errorMessage
) internal pure returns (uint96) {
require(b <= a, errorMessage);
return a - b;
}
function getChainId() internal view returns (uint256) {
uint256 chainId;
assembly {
chainId := chainid()
}
return chainId;
}
}
|
Change the minter address minter_ The address of the new minter/
|
function setMinter(address minter_) external {
require(
minter_ != address(0),
'HFT::setMinter: minter_ cannot be zero address'
);
require(
msg.sender == minter,
'HFT::setMinter: only the minter can change the minter address'
);
minter = minter_;
emit MinterChanged(minter, minter_);
}
| 393,948 |
pragma solidity ^0.4.16;
// SafeMath Taken From FirstBlood
contract SafeMath {
function safeMul(uint a, uint b) internal returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function safeDiv(uint a, uint b) internal returns (uint) {
assert(b > 0);
uint c = a / b;
assert(a == b * c + a % b);
return c;
}
function safeSub(uint a, uint b) internal returns (uint) {
assert(b <= a);
return a - b;
}
function safeAdd(uint a, uint b) internal returns (uint) {
uint c = a + b;
assert(c>=a && c>=b);
return c;
}
}
// Ownership
contract Owned {
address public owner;
address public newOwner;
modifier onlyOwner { assert(msg.sender == owner); _; }
event OwnerUpdate(address _prevOwner, address _newOwner);
function Owned() {
owner = msg.sender;
}
function transferOwnership(address _newOwner) public onlyOwner {
require(_newOwner != owner);
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner);
OwnerUpdate(owner, newOwner);
owner = newOwner;
newOwner = 0x0;
}
}
// ERC20 Interface
contract ERC20 {
function totalSupply() constant returns (uint _totalSupply);
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);
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
}
// ERC20Token
contract ERC20Token is ERC20, SafeMath {
mapping(address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
uint256 public totalTokens;
function transfer(address _to, uint256 _value) returns (bool success) {
if (balances[msg.sender] >= _value && _value > 0) {
balances[msg.sender] = safeSub(balances[msg.sender], _value);
balances[_to] = safeAdd(balances[_to], _value);
Transfer(msg.sender, _to, _value);
return true;
} else {
return false;
}
}
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
var _allowance = allowed[_from][msg.sender];
if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) {
balances[_to] = safeAdd(balances[_to], _value);
balances[_from] = safeSub(balances[_from], _value);
allowed[_from][msg.sender] = safeSub(_allowance, _value);
Transfer(_from, _to, _value);
return true;
} else {
return false;
}
}
function totalSupply() constant returns (uint256) {
return totalTokens;
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) returns (bool success) {
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
contract Wolk is ERC20Token, Owned {
// TOKEN INFO
string public constant name = "Wolk Protocol Token";
string public constant symbol = "WOLK";
uint256 public constant decimals = 18;
// RESERVE
uint256 public reserveBalance = 0;
uint8 public constant percentageETHReserve = 15;
// CONTRACT OWNER
address public multisigWallet;
// WOLK SETTLERS
mapping (address => bool) settlers;
modifier onlySettler { assert(settlers[msg.sender] == true); _; }
// TOKEN GENERATION CONTROL
address public wolkSale;
bool public allSaleCompleted = false;
bool public openSaleCompleted = false;
modifier isTransferable { require(allSaleCompleted); _; }
modifier onlyWolk { assert(msg.sender == wolkSale); _; }
// TOKEN GENERATION EVENTLOG
event WolkCreated(address indexed _to, uint256 _tokenCreated);
event WolkDestroyed(address indexed _from, uint256 _tokenDestroyed);
event LogRefund(address indexed _to, uint256 _value);
}
contract WolkTGE is Wolk {
// TOKEN GENERATION EVENT
mapping (address => uint256) contribution;
mapping (address => uint256) presaleLimit;
mapping (address => bool) presaleContributor;
uint256 public constant tokenGenerationMin = 50 * 10**6 * 10**decimals;
uint256 public constant tokenGenerationMax = 150 * 10**6 * 10**decimals;
uint256 public presale_start_block;
uint256 public start_block;
uint256 public end_block;
// @param _presaleStartBlock
// @param _startBlock
// @param _endBlock
// @param _wolkWallet
// @param _wolkSale
// @return success
// @dev Wolk Genesis Event [only accessible by Contract Owner]
function wolkGenesis(uint256 _presaleStartBlock, uint256 _startBlock, uint256 _endBlock, address _wolkWallet, address _wolkSale) onlyOwner returns (bool success){
require((totalTokens < 1) && (block.number <= _startBlock) && (_endBlock > _startBlock) && (_startBlock > _presaleStartBlock));
presale_start_block = _presaleStartBlock;
start_block = _startBlock;
end_block = _endBlock;
multisigWallet = _wolkWallet;
wolkSale = _wolkSale;
settlers[msg.sender] = true;
return true;
}
// @param _presaleParticipants
// @return success
// @dev Adds addresses that are allowed to take part in presale [only accessible by current Contract Owner]
function addParticipant(address[] _presaleParticipants, uint256[] _contributionLimits) onlyOwner returns (bool success) {
require(_presaleParticipants.length == _contributionLimits.length);
for (uint cnt = 0; cnt < _presaleParticipants.length; cnt++){
presaleContributor[_presaleParticipants[cnt]] = true;
presaleLimit[_presaleParticipants[cnt]] = safeMul(_contributionLimits[cnt], 10**decimals);
}
return true;
}
// @param _presaleParticipants
// @return success
// @dev Revoke designated presale contributors [only accessible by current Contract Owner]
function removeParticipant(address[] _presaleParticipants) onlyOwner returns (bool success){
for (uint cnt = 0; cnt < _presaleParticipants.length; cnt++){
presaleContributor[_presaleParticipants[cnt]] = false;
presaleLimit[_presaleParticipants[cnt]] = 0;
}
return true;
}
// @param _participant
// @return remainingAllocation
// @dev return PresaleLimit allocated to given address
function participantBalance(address _participant) constant returns (uint256 remainingAllocation) {
return presaleLimit[_participant];
}
// @param _participant
// @dev use tokenGenerationEvent to handle Pre-sale and Open-sale
function tokenGenerationEvent(address _participant) payable external {
require( presaleContributor[_participant] && !openSaleCompleted && !allSaleCompleted && (block.number <= end_block) && msg.value > 0);
/* Early Participation Discount (rounded to the nearest integer)
---------------------------------
| Token Issued | Rate | Discount|
---------------------------------
| 0 - 50MM | 1177 | 15.0% |
| 50MM - 60MM | 1143 | 12.5% |
| 60MM - 70MM | 1111 | 10.0% |
| 70MM - 80MM | 1081 | 7.5% |
| 80MM - 90MM | 1053 | 5.0% |
| 90MM - 100MM | 1026 | 2.5% |
| 100MM+ | 1000 | 0.0% |
---------------------------------
*/
uint256 rate = 1000; // Default Rate
if ( totalTokens < (50 * 10**6 * 10**decimals) ) {
rate = 1177;
} else if ( totalTokens < (60 * 10**6 * 10**decimals) ) {
rate = 1143;
} else if ( totalTokens < (70 * 10**6 * 10**decimals) ) {
rate = 1111;
} else if ( totalTokens < (80 * 10**6 * 10**decimals) ) {
rate = 1081;
} else if ( totalTokens < (90 * 10**6 * 10**decimals) ) {
rate = 1053;
} else if ( totalTokens < (100 * 10**6 * 10**decimals) ) {
rate = 1026;
}else{
rate = 1000;
}
if ((block.number < start_block) && (block.number >= presale_start_block)) {
require(presaleLimit[_participant] >= msg.value);
presaleLimit[_participant] = safeSub(presaleLimit[_participant], msg.value);
} else {
require(block.number >= start_block) ;
}
uint256 tokens = safeMul(msg.value, rate);
uint256 checkedSupply = safeAdd(totalTokens, tokens);
require(checkedSupply <= tokenGenerationMax);
totalTokens = checkedSupply;
Transfer(address(this), _participant, tokens);
balances[_participant] = safeAdd(balances[_participant], tokens);
contribution[_participant] = safeAdd(contribution[_participant], msg.value);
WolkCreated(_participant, tokens); // logs token creation
}
// @dev If Token Generation Minimum is Not Met, TGE Participants can call this func and request for refund
function refund() external {
require((contribution[msg.sender] > 0) && (!allSaleCompleted) && (totalTokens < tokenGenerationMin) && (block.number > end_block));
uint256 tokenBalance = balances[msg.sender];
uint256 refundBalance = contribution[msg.sender];
balances[msg.sender] = 0;
contribution[msg.sender] = 0;
totalTokens = safeSub(totalTokens, tokenBalance);
WolkDestroyed(msg.sender, tokenBalance);
LogRefund(msg.sender, refundBalance);
msg.sender.transfer(refundBalance);
}
// @dev Finalizing the Open-Sale for Token Generation Event. 15% of Eth will be kept in contract to provide liquidity
function finalizeOpenSale() onlyOwner {
require((!openSaleCompleted) && (totalTokens >= tokenGenerationMin));
openSaleCompleted = true;
end_block = block.number;
reserveBalance = safeDiv(safeMul(totalTokens, percentageETHReserve), 100000);
var withdrawalBalance = safeSub(this.balance, reserveBalance);
msg.sender.transfer(withdrawalBalance);
}
// @dev Finalizing the Private-Sale. Entire Eth will be kept in contract to provide liquidity. This func will conclude the entire sale.
function finalize() onlyWolk payable external {
require((openSaleCompleted) && (!allSaleCompleted));
uint256 privateSaleTokens = safeDiv(safeMul(msg.value, 100000), percentageETHReserve);
uint256 checkedSupply = safeAdd(totalTokens, privateSaleTokens);
totalTokens = checkedSupply;
reserveBalance = safeAdd(reserveBalance, msg.value);
Transfer(address(this), wolkSale, privateSaleTokens);
balances[wolkSale] = safeAdd(balances[wolkSale], privateSaleTokens);
WolkCreated(wolkSale, privateSaleTokens); // logs token creation for Presale events
allSaleCompleted = true;
}
}
contract IBurnFormula {
function calculateWolkToBurn(uint256 _value) public constant returns (uint256);
}
contract IFeeFormula {
function calculateProviderFee(uint256 _value) public constant returns (uint256);
}
contract WolkProtocol is Wolk {
// WOLK NETWORK PROTOCOL
address public burnFormula;
bool public settlementIsRunning = true;
uint256 public burnBasisPoints = 500; // Burn rate (in BP) when Service Provider withdraws from data buyers' accounts
mapping (address => mapping (address => bool)) authorized; // holds which accounts have approved which Service Providers
mapping (address => uint256) feeBasisPoints; // Fee (in BP) earned by Service Provider when depositing to data seller
mapping (address => address) feeFormulas; // Provider's customizable Fee mormula
modifier isSettleable { require(settlementIsRunning); _; }
// WOLK PROTOCOL Events:
event AuthorizeServiceProvider(address indexed _owner, address _serviceProvider);
event DeauthorizeServiceProvider(address indexed _owner, address _serviceProvider);
event SetServiceProviderFee(address indexed _serviceProvider, uint256 _feeBasisPoints);
event BurnTokens(address indexed _from, address indexed _serviceProvider, uint256 _value);
// @param _burnBasisPoints
// @return success
// @dev Set BurnRate on Wolk Protocol -- only Wolk can set this, affects Service Provider settleBuyer
function setBurnRate(uint256 _burnBasisPoints) onlyOwner returns (bool success) {
require((_burnBasisPoints > 0) && (_burnBasisPoints <= 1000));
burnBasisPoints = _burnBasisPoints;
return true;
}
// @param _newBurnFormula
// @return success
// @dev Set the formula to use for burning -- only Wolk can set this
function setBurnFormula(address _newBurnFormula) onlyOwner returns (bool success){
uint256 testBurning = estWolkToBurn(_newBurnFormula, 10 ** 18);
require(testBurning > (5 * 10 ** 13));
burnFormula = _newBurnFormula;
return true;
}
// @param _newFeeFormula
// @return success
// @dev Set the formula to use for settlement -- settler can customize its fee
function setFeeFormula(address _newFeeFormula) onlySettler returns (bool success){
uint256 testSettling = estProviderFee(_newFeeFormula, 10 ** 18);
require(testSettling > (5 * 10 ** 13));
feeFormulas[msg.sender] = _newFeeFormula;
return true;
}
// @param _isRunning
// @return success
// @dev upating settlement status -- only Wolk can set this
function updateSettlementStatus(bool _isRunning) onlyOwner returns (bool success){
settlementIsRunning = _isRunning;
return true;
}
// @param _serviceProvider
// @param _feeBasisPoints
// @return success
// @dev Set Service Provider fee -- only Contract Owner can do this, affects Service Provider settleSeller
function setServiceFee(address _serviceProvider, uint256 _feeBasisPoints) onlyOwner returns (bool success) {
if (_feeBasisPoints <= 0 || _feeBasisPoints > 4000){
// revoke Settler privilege
settlers[_serviceProvider] = false;
feeBasisPoints[_serviceProvider] = 0;
return false;
}else{
feeBasisPoints[_serviceProvider] = _feeBasisPoints;
settlers[_serviceProvider] = true;
SetServiceProviderFee(_serviceProvider, _feeBasisPoints);
return true;
}
}
// @param _serviceProvider
// @return _feeBasisPoints
// @dev Check service Fee (in BP) for a given provider
function checkServiceFee(address _serviceProvider) constant returns (uint256 _feeBasisPoints) {
return feeBasisPoints[_serviceProvider];
}
// @param _serviceProvider
// @return _formulaAddress
// @dev Returns the contract address of the Service Provider's fee formula
function checkFeeSchedule(address _serviceProvider) constant returns (address _formulaAddress) {
return feeFormulas[_serviceProvider];
}
// @param _value
// @return wolkBurnt
// @dev Returns estimate of Wolk to burn
function estWolkToBurn(address _burnFormula, uint256 _value) constant internal returns (uint256){
if(_burnFormula != 0x0){
uint256 wolkBurnt = IBurnFormula(_burnFormula).calculateWolkToBurn(_value);
return wolkBurnt;
}else{
return 0;
}
}
// @param _value
// @param _serviceProvider
// @return estFee
// @dev Returns estimate of Service Provider's fee
function estProviderFee(address _serviceProvider, uint256 _value) constant internal returns (uint256){
address ProviderFeeFormula = feeFormulas[_serviceProvider];
if (ProviderFeeFormula != 0x0){
uint256 estFee = IFeeFormula(ProviderFeeFormula).calculateProviderFee(_value);
return estFee;
}else{
return 0;
}
}
// @param _buyer
// @param _value
// @return success
// @dev Service Provider Settlement with Buyer: a small percent is burnt (set in setBurnRate, stored in burnBasisPoints) when funds are transferred from buyer to Service Provider [only accessible by settlers]
function settleBuyer(address _buyer, uint256 _value) onlySettler isSettleable returns (bool success) {
require((burnBasisPoints > 0) && (burnBasisPoints <= 1000) && authorized[_buyer][msg.sender]); // Buyer must authorize Service Provider
require(balances[_buyer] >= _value && _value > 0);
var WolkToBurn = estWolkToBurn(burnFormula, _value);
var burnCap = safeDiv(safeMul(_value, burnBasisPoints), 10000); //can not burn more than this
// If burn formula not found, use default burn rate. If Est to burn exceeds BurnCap, cut back to the cap
if (WolkToBurn < 1) WolkToBurn = burnCap;
if (WolkToBurn > burnCap) WolkToBurn = burnCap;
var transferredToServiceProvider = safeSub(_value, WolkToBurn);
balances[_buyer] = safeSub(balances[_buyer], _value);
balances[msg.sender] = safeAdd(balances[msg.sender], transferredToServiceProvider);
totalTokens = safeSub(totalTokens, WolkToBurn);
Transfer(_buyer, msg.sender, transferredToServiceProvider);
Transfer(_buyer, 0x00000000000000000000, WolkToBurn);
BurnTokens(_buyer, msg.sender, WolkToBurn);
return true;
}
// @param _seller
// @param _value
// @return success
// @dev Service Provider Settlement with Seller: a small percent is kept by Service Provider (set in setServiceFee, stored in feeBasisPoints) when funds are transferred from Service Provider to seller [only accessible by settlers]
function settleSeller(address _seller, uint256 _value) onlySettler isSettleable returns (bool success) {
// Service Providers have a % max fee (e.g. 20%)
var serviceProviderBP = feeBasisPoints[msg.sender];
require((serviceProviderBP > 0) && (serviceProviderBP <= 4000) && (_value > 0));
var seviceFee = estProviderFee(msg.sender, _value);
var Maximumfee = safeDiv(safeMul(_value, serviceProviderBP), 10000);
// If provider's fee formula not set, use default burn rate. If Est fee exceeds Maximumfee, cut back to the fee
if (seviceFee < 1) seviceFee = Maximumfee;
if (seviceFee > Maximumfee) seviceFee = Maximumfee;
var transferredToSeller = safeSub(_value, seviceFee);
require(balances[msg.sender] >= transferredToSeller );
balances[_seller] = safeAdd(balances[_seller], transferredToSeller);
Transfer(msg.sender, _seller, transferredToSeller);
return true;
}
// @param _providerToAdd
// @return success
// @dev Buyer authorizes the Service Provider (to call settleBuyer). For security reason, _providerToAdd needs to be whitelisted by Wolk Inc first
function authorizeProvider(address _providerToAdd) returns (bool success) {
require(settlers[_providerToAdd]);
authorized[msg.sender][_providerToAdd] = true;
AuthorizeServiceProvider(msg.sender, _providerToAdd);
return true;
}
// @param _providerToRemove
// @return success
// @dev Buyer deauthorizes the Service Provider (from calling settleBuyer)
function deauthorizeProvider(address _providerToRemove) returns (bool success) {
authorized[msg.sender][_providerToRemove] = false;
DeauthorizeServiceProvider(msg.sender, _providerToRemove);
return true;
}
// @param _owner
// @param _serviceProvider
// @return authorizationStatus
// @dev Check authorization between account and Service Provider
function checkAuthorization(address _owner, address _serviceProvider) constant returns (bool authorizationStatus) {
return authorized[_owner][_serviceProvider];
}
// @param _owner
// @param _providerToAdd
// @return authorizationStatus
// @dev Grant authorization between account and Service Provider on buyers' behalf [only accessible by Contract Owner]
// @note Explicit permission from balance owner MUST be obtained beforehand
function grantService(address _owner, address _providerToAdd) onlyOwner returns (bool authorizationStatus) {
var isPreauthorized = authorized[_owner][msg.sender];
if (isPreauthorized && settlers[_providerToAdd]) {
authorized[_owner][_providerToAdd] = true;
AuthorizeServiceProvider(msg.sender, _providerToAdd);
return true;
}else{
return false;
}
}
// @param _owner
// @param _providerToRemove
// @return authorization_status
// @dev Revoke authorization between account and Service Provider on buyers' behalf [only accessible by Contract Owner]
// @note Explicit permission from balance owner are NOT required for disabling ill-intent Service Provider
function removeService(address _owner, address _providerToRemove) onlyOwner returns (bool authorizationStatus) {
authorized[_owner][_providerToRemove] = false;
DeauthorizeServiceProvider(_owner, _providerToRemove);
return true;
}
}
// Taken from https://github.com/bancorprotocol/contracts/blob/master/solidity/contracts/BancorFormula.sol
contract IBancorFormula {
function calculatePurchaseReturn(uint256 _supply, uint256 _reserveBalance, uint8 _reserveRatio, uint256 _depositAmount) public constant returns (uint256);
function calculateSaleReturn(uint256 _supply, uint256 _reserveBalance, uint8 _reserveRatio, uint256 _sellAmount) public constant returns (uint256);
}
contract WolkExchange is WolkProtocol, WolkTGE {
uint256 public maxPerExchangeBP = 50;
address public exchangeFormula;
bool public exchangeIsRunning = false;
modifier isExchangable { require(exchangeIsRunning && allSaleCompleted); _; }
// @param _newExchangeformula
// @return success
// @dev Set the bancor formula to use -- only Wolk Inc can set this
function setExchangeFormula(address _newExchangeformula) onlyOwner returns (bool success){
require(sellWolkEstimate(10**decimals, _newExchangeformula) > 0);
require(purchaseWolkEstimate(10**decimals, _newExchangeformula) > 0);
exchangeIsRunning = false;
exchangeFormula = _newExchangeformula;
return true;
}
// @param _isRunning
// @return success
// @dev upating exchange status -- only Wolk Inc can set this
function updateExchangeStatus(bool _isRunning) onlyOwner returns (bool success){
if (_isRunning){
require(sellWolkEstimate(10**decimals, exchangeFormula) > 0);
require(purchaseWolkEstimate(10**decimals, exchangeFormula) > 0);
}
exchangeIsRunning = _isRunning;
return true;
}
// @param _maxPerExchange
// @return success
// @dev Set max sell token amount per transaction -- only Wolk Inc can set this
function setMaxPerExchange(uint256 _maxPerExchange) onlyOwner returns (bool success) {
require((_maxPerExchange >= 10) && (_maxPerExchange <= 100));
maxPerExchangeBP = _maxPerExchange;
return true;
}
// @return Estimated Liquidation Cap
// @dev Liquidation Cap per transaction is used to ensure proper price discovery for Wolk Exchange
function estLiquidationCap() public constant returns (uint256) {
if (openSaleCompleted){
var liquidationMax = safeDiv(safeMul(totalTokens, maxPerExchangeBP), 10000);
if (liquidationMax < 100 * 10**decimals){
liquidationMax = 100 * 10**decimals;
}
return liquidationMax;
}else{
return 0;
}
}
function sellWolkEstimate(uint256 _wolkAmountest, address _formula) internal returns(uint256) {
uint256 ethReceivable = IBancorFormula(_formula).calculateSaleReturn(totalTokens, reserveBalance, percentageETHReserve, _wolkAmountest);
return ethReceivable;
}
function purchaseWolkEstimate(uint256 _ethAmountest, address _formula) internal returns(uint256) {
uint256 wolkReceivable = IBancorFormula(_formula).calculatePurchaseReturn(totalTokens, reserveBalance, percentageETHReserve, _ethAmountest);
return wolkReceivable;
}
// @param _wolkAmount
// @return ethReceivable
// @dev send Wolk into contract in exchange for eth, at an exchange rate based on the Bancor Protocol derivation and decrease totalSupply accordingly
function sellWolk(uint256 _wolkAmount) isExchangable() returns(uint256) {
uint256 sellCap = estLiquidationCap();
require((balances[msg.sender] >= _wolkAmount));
require(sellCap >= _wolkAmount);
uint256 ethReceivable = sellWolkEstimate(_wolkAmount,exchangeFormula);
require(this.balance > ethReceivable);
balances[msg.sender] = safeSub(balances[msg.sender], _wolkAmount);
totalTokens = safeSub(totalTokens, _wolkAmount);
reserveBalance = safeSub(this.balance, ethReceivable);
WolkDestroyed(msg.sender, _wolkAmount);
Transfer(msg.sender, 0x00000000000000000000, _wolkAmount);
msg.sender.transfer(ethReceivable);
return ethReceivable;
}
// @return wolkReceivable
// @dev send eth into contract in exchange for Wolk tokens, at an exchange rate based on the Bancor Protocol derivation and increase totalSupply accordingly
function purchaseWolk(address _buyer) isExchangable() payable returns(uint256){
require(msg.value > 0);
uint256 wolkReceivable = purchaseWolkEstimate(msg.value, exchangeFormula);
require(wolkReceivable > 0);
totalTokens = safeAdd(totalTokens, wolkReceivable);
balances[_buyer] = safeAdd(balances[_buyer], wolkReceivable);
reserveBalance = safeAdd(reserveBalance, msg.value);
WolkCreated(_buyer, wolkReceivable);
Transfer(address(this),_buyer,wolkReceivable);
return wolkReceivable;
}
// @dev fallback function for purchase
// @note Automatically fallback to tokenGenerationEvent before sale is completed. After the token generation event, fallback to purchaseWolk. Liquidity exchange will be enabled through updateExchangeStatus
function () payable {
require(msg.value > 0);
if(!openSaleCompleted){
this.tokenGenerationEvent.value(msg.value)(msg.sender);
}else if (block.number >= end_block){
this.purchaseWolk.value(msg.value)(msg.sender);
}else{
revert();
}
}
}
|
_maxPerExchange return success Set max sell token amount per transaction -- only Wolk Inc can set this
|
function setMaxPerExchange(uint256 _maxPerExchange) onlyOwner returns (bool success) {
require((_maxPerExchange >= 10) && (_maxPerExchange <= 100));
maxPerExchangeBP = _maxPerExchange;
return true;
}
| 6,571,434 |
./partial_match/1/0xaeF2332872095dF32f52Ee5182e074e6551209b1/sources/Zeeland.sol
|
Airdrop NFTs to list of address (call by owner only). This function mints the provided _quantity of NFTs to address list. _addressList is the list of address and _amountList contains number of nfts to mint.
|
function airdropMint(address[] memory _addressList , uint256[] memory _amountList) external onlyOwner {
for(uint256 i = 0; i < _addressList.length; i++) {
require(
_totalMinted() + _amountList[i] <= _totalSupply,
"Exceeds the total supply"
);
_mint(_addressList[i], _amountList[i]);
}
}
| 2,742,654 |
pragma solidity >=0.5.0 <0.6.0;
contract Proxiable {
// Code position in storage is keccak256("PROXIABLE") = "0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7"
event Upgraded(address indexed implementation);
function updateCodeAddress(address newAddress) internal {
require(
bytes32(0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7) == Proxiable(newAddress).proxiableUUID(),
"Not compatible"
);
assembly { // solium-disable-line
sstore(0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7, newAddress)
}
emit Upgraded(newAddress);
}
function proxiableUUID() public pure returns (bytes32) {
return 0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7;
}
}
// Abstract contract for the full ERC 20 Token standard
// https://github.com/ethereum/EIPs/issues/20
interface ERC20Token {
/**
* @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, uint256 _value) external returns (bool success);
/**
* @notice `msg.sender` approves `_spender` to spend `_value` tokens
* @param _spender The address of the account able to transfer the tokens
* @param _value The amount of tokens to be approved for transfer
* @return Whether the approval was successful or not
*/
function approve(address _spender, uint256 _value) external 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, uint256 _value) external returns (bool success);
/**
* @param _owner The address from which the balance will be retrieved
* @return The balance
*/
function balanceOf(address _owner) external view returns (uint256 balance);
/**
* @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) external view returns (uint256 remaining);
/**
* @notice return total supply of tokens
*/
function totalSupply() external view returns (uint256 supply);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @dev Get the contract's owner
* @return the address of the owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Only the contract's owner can invoke this function");
_;
}
/**
* @dev Sets an owner address
* @param _newOwner new owner address
*/
function _setOwner(address _newOwner) internal {
_owner = _newOwner;
}
/**
* @dev is sender the owner of the contract?
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* 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() external onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) external 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), "New owner cannot be address(0)");
emit OwnershipTransferred(_owner, _newOwner);
_owner = _newOwner;
}
}
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 _amount, address _token, bytes memory _data) public;
}
contract SafeTransfer {
function _safeTransfer(ERC20Token _token, address _to, uint256 _value) internal returns (bool result) {
_token.transfer(_to, _value);
assembly {
switch returndatasize()
case 0 {
result := not(0)
}
case 32 {
returndatacopy(0, 0, 32)
result := mload(0)
}
default {
revert(0, 0)
}
}
require(result, "Unsuccessful token transfer");
}
function _safeTransferFrom(
ERC20Token _token,
address _from,
address _to,
uint256 _value
) internal returns (bool result)
{
_token.transferFrom(_from, _to, _value);
assembly {
switch returndatasize()
case 0 {
result := not(0)
}
case 32 {
returndatacopy(0, 0, 32)
result := mload(0)
}
default {
revert(0, 0)
}
}
require(result, "Unsuccessful token transfer");
}
}
contract IEscrow {
enum EscrowStatus {CREATED, FUNDED, PAID, RELEASED, CANCELED}
struct EscrowTransaction {
uint256 offerId;
address token;
uint256 tokenAmount;
uint256 expirationTime;
uint256 sellerRating;
uint256 buyerRating;
uint256 fiatAmount;
address payable buyer;
address payable seller;
address payable arbitrator;
EscrowStatus status;
}
function createEscrow_relayed(
address payable _sender,
uint _offerId,
uint _tokenAmount,
uint _fiatAmount,
string calldata _contactData,
string calldata _location,
string calldata _username
) external returns(uint escrowId);
function pay(uint _escrowId) external;
function pay_relayed(address _sender, uint _escrowId) external;
function cancel(uint _escrowId) external;
function cancel_relayed(address _sender, uint _escrowId) external;
function openCase(uint _escrowId, uint8 _motive) external;
function openCase_relayed(address _sender, uint256 _escrowId, uint8 _motive) external;
function rateTransaction(uint _escrowId, uint _rate) external;
function rateTransaction_relayed(address _sender, uint _escrowId, uint _rate) external;
function getBasicTradeData(uint _escrowId) external view returns(address payable buyer, address payable seller, address token, uint tokenAmount);
}
/* solium-disable security/no-block-members */
/* solium-disable security/no-inline-assembly */
/* solium-disable no-empty-blocks */
/* solium-disable security/no-block-members */
/* solium-disable security/no-inline-assembly */
/**
* @title License
* @dev Contract for buying a license
*/
contract License is Ownable, ApproveAndCallFallBack, SafeTransfer, Proxiable {
uint256 public price;
ERC20Token token;
address burnAddress;
struct LicenseDetails {
uint price;
uint creationTime;
}
address[] public licenseOwners;
mapping(address => uint) public idxLicenseOwners;
mapping(address => LicenseDetails) public licenseDetails;
event Bought(address buyer, uint256 price);
event PriceChanged(uint256 _price);
bool internal _initialized;
/**
* @param _tokenAddress Address of token used to pay for licenses (SNT)
* @param _price Price of the licenses
* @param _burnAddress Address where the license fee is going to be sent
*/
constructor(address _tokenAddress, uint256 _price, address _burnAddress) public {
init(_tokenAddress, _price, _burnAddress);
}
/**
* @dev Initialize contract (used with proxy). Can only be called once
* @param _tokenAddress Address of token used to pay for licenses (SNT)
* @param _price Price of the licenses
* @param _burnAddress Address where the license fee is going to be sent
*/
function init(
address _tokenAddress,
uint256 _price,
address _burnAddress
) public {
assert(_initialized == false);
_initialized = true;
price = _price;
token = ERC20Token(_tokenAddress);
burnAddress = _burnAddress;
_setOwner(msg.sender);
}
function updateCode(address newCode) public onlyOwner {
updateCodeAddress(newCode);
}
/**
* @notice Check if the address already owns a license
* @param _address The address to check
* @return bool
*/
function isLicenseOwner(address _address) public view returns (bool) {
return licenseDetails[_address].price != 0 && licenseDetails[_address].creationTime != 0;
}
/**
* @notice Buy a license
* @dev Requires value to be equal to the price of the license.
* The msg.sender must not already own a license.
*/
function buy() external returns(uint) {
uint id = _buyFrom(msg.sender);
return id;
}
/**
* @notice Buy a license
* @dev Requires value to be equal to the price of the license.
* The _owner must not already own a license.
*/
function _buyFrom(address _licenseOwner) internal returns(uint) {
require(licenseDetails[_licenseOwner].creationTime == 0, "License already bought");
licenseDetails[_licenseOwner] = LicenseDetails({
price: price,
creationTime: block.timestamp
});
uint idx = licenseOwners.push(_licenseOwner);
idxLicenseOwners[_licenseOwner] = idx;
emit Bought(_licenseOwner, price);
require(_safeTransferFrom(token, _licenseOwner, burnAddress, price), "Unsuccessful token transfer");
return idx;
}
/**
* @notice Set the license price
* @param _price The new price of the license
* @dev Only the owner of the contract can perform this action
*/
function setPrice(uint256 _price) external onlyOwner {
price = _price;
emit PriceChanged(_price);
}
/**
* @dev Get number of license owners
* @return uint
*/
function getNumLicenseOwners() external view returns (uint256) {
return licenseOwners.length;
}
/**
* @notice Support for "approveAndCall". Callable only by `token()`.
* @param _from Who approved.
* @param _amount Amount being approved, need to be equal `price()`.
* @param _token Token being approved, need to be equal `token()`.
* @param _data Abi encoded data with selector of `buy(and)`.
*/
function receiveApproval(address _from, uint256 _amount, address _token, bytes memory _data) public {
require(_amount == price, "Wrong value");
require(_token == address(token), "Wrong token");
require(_token == address(msg.sender), "Wrong call");
require(_data.length == 4, "Wrong data length");
require(_abiDecodeBuy(_data) == bytes4(0xa6f2ae3a), "Wrong method selector"); //bytes4(keccak256("buy()"))
_buyFrom(_from);
}
/**
* @dev Decodes abi encoded data with selector for "buy()".
* @param _data Abi encoded data.
* @return Decoded registry call.
*/
function _abiDecodeBuy(bytes memory _data) internal pure returns(bytes4 sig) {
assembly {
sig := mload(add(_data, add(0x20, 0)))
}
}
}
/* solium-disable security/no-block-members */
/**
* @title ArbitratorLicense
* @dev Contract for management of an arbitrator license
*/
contract ArbitrationLicense is License {
enum RequestStatus {NONE,AWAIT,ACCEPTED,REJECTED,CLOSED}
struct Request{
address seller;
address arbitrator;
RequestStatus status;
uint date;
}
struct ArbitratorLicenseDetails {
uint id;
bool acceptAny;// accept any seller
}
mapping(address => ArbitratorLicenseDetails) public arbitratorlicenseDetails;
mapping(address => mapping(address => bool)) public permissions;
mapping(address => mapping(address => bool)) public blacklist;
mapping(bytes32 => Request) public requests;
event ArbitratorRequested(bytes32 id, address indexed seller, address indexed arbitrator);
event RequestAccepted(bytes32 id, address indexed arbitrator, address indexed seller);
event RequestRejected(bytes32 id, address indexed arbitrator, address indexed seller);
event RequestCanceled(bytes32 id, address indexed arbitrator, address indexed seller);
event BlacklistSeller(address indexed arbitrator, address indexed seller);
event UnBlacklistSeller(address indexed arbitrator, address indexed seller);
/**
* @param _tokenAddress Address of token used to pay for licenses (SNT)
* @param _price Amount of token needed to buy a license
* @param _burnAddress Burn address where the price of the license is sent
*/
constructor(address _tokenAddress, uint256 _price, address _burnAddress)
License(_tokenAddress, _price, _burnAddress)
public {}
/**
* @notice Buy an arbitrator license
*/
function buy() external returns(uint) {
return _buy(msg.sender, false);
}
/**
* @notice Buy an arbitrator license and set if the arbitrator accepts any seller
* @param _acceptAny When set to true, all sellers are accepted by the arbitrator
*/
function buy(bool _acceptAny) external returns(uint) {
return _buy(msg.sender, _acceptAny);
}
/**
* @notice Buy an arbitrator license and set if the arbitrator accepts any seller. Sets the arbitrator as the address in params instead of the sender
* @param _sender Address of the arbitrator
* @param _acceptAny When set to true, all sellers are accepted by the arbitrator
*/
function _buy(address _sender, bool _acceptAny) internal returns (uint id) {
id = _buyFrom(_sender);
arbitratorlicenseDetails[_sender].id = id;
arbitratorlicenseDetails[_sender].acceptAny = _acceptAny;
}
/**
* @notice Change acceptAny parameter for arbitrator
* @param _acceptAny indicates does arbitrator allow to accept any seller/choose sellers
*/
function changeAcceptAny(bool _acceptAny) public {
require(isLicenseOwner(msg.sender), "Message sender should have a valid arbitrator license");
require(arbitratorlicenseDetails[msg.sender].acceptAny != _acceptAny,
"Message sender should pass parameter different from the current one");
arbitratorlicenseDetails[msg.sender].acceptAny = _acceptAny;
}
/**
* @notice Allows arbitrator to accept a seller
* @param _arbitrator address of a licensed arbitrator
*/
function requestArbitrator(address _arbitrator) public {
require(isLicenseOwner(_arbitrator), "Arbitrator should have a valid license");
require(!arbitratorlicenseDetails[_arbitrator].acceptAny, "Arbitrator already accepts all cases");
bytes32 _id = keccak256(abi.encodePacked(_arbitrator, msg.sender));
RequestStatus _status = requests[_id].status;
require(_status != RequestStatus.AWAIT && _status != RequestStatus.ACCEPTED, "Invalid request status");
if(_status == RequestStatus.REJECTED || _status == RequestStatus.CLOSED){
require(requests[_id].date + 3 days < block.timestamp,
"Must wait 3 days before requesting the arbitrator again");
}
requests[_id] = Request({
seller: msg.sender,
arbitrator: _arbitrator,
status: RequestStatus.AWAIT,
date: block.timestamp
});
emit ArbitratorRequested(_id, msg.sender, _arbitrator);
}
/**
* @dev Get Request Id
* @param _arbitrator Arbitrator address
* @param _account Seller account
* @return Request Id
*/
function getId(address _arbitrator, address _account) external pure returns(bytes32){
return keccak256(abi.encodePacked(_arbitrator,_account));
}
/**
* @notice Allows arbitrator to accept a seller's request
* @param _id request id
*/
function acceptRequest(bytes32 _id) public {
require(isLicenseOwner(msg.sender), "Arbitrator should have a valid license");
require(requests[_id].status == RequestStatus.AWAIT, "This request is not pending");
require(!arbitratorlicenseDetails[msg.sender].acceptAny, "Arbitrator already accepts all cases");
require(requests[_id].arbitrator == msg.sender, "Invalid arbitrator");
requests[_id].status = RequestStatus.ACCEPTED;
address _seller = requests[_id].seller;
permissions[msg.sender][_seller] = true;
emit RequestAccepted(_id, msg.sender, requests[_id].seller);
}
/**
* @notice Allows arbitrator to reject a request
* @param _id request id
*/
function rejectRequest(bytes32 _id) public {
require(isLicenseOwner(msg.sender), "Arbitrator should have a valid license");
require(requests[_id].status == RequestStatus.AWAIT || requests[_id].status == RequestStatus.ACCEPTED,
"Invalid request status");
require(!arbitratorlicenseDetails[msg.sender].acceptAny, "Arbitrator accepts all cases");
require(requests[_id].arbitrator == msg.sender, "Invalid arbitrator");
requests[_id].status = RequestStatus.REJECTED;
requests[_id].date = block.timestamp;
address _seller = requests[_id].seller;
permissions[msg.sender][_seller] = false;
emit RequestRejected(_id, msg.sender, requests[_id].seller);
}
/**
* @notice Allows seller to cancel a request
* @param _id request id
*/
function cancelRequest(bytes32 _id) public {
require(requests[_id].seller == msg.sender, "This request id does not belong to the message sender");
require(requests[_id].status == RequestStatus.AWAIT || requests[_id].status == RequestStatus.ACCEPTED, "Invalid request status");
address arbitrator = requests[_id].arbitrator;
requests[_id].status = RequestStatus.CLOSED;
requests[_id].date = block.timestamp;
address _arbitrator = requests[_id].arbitrator;
permissions[_arbitrator][msg.sender] = false;
emit RequestCanceled(_id, arbitrator, requests[_id].seller);
}
/**
* @notice Allows arbitrator to blacklist a seller
* @param _seller Seller address
*/
function blacklistSeller(address _seller) public {
require(isLicenseOwner(msg.sender), "Arbitrator should have a valid license");
blacklist[msg.sender][_seller] = true;
emit BlacklistSeller(msg.sender, _seller);
}
/**
* @notice Allows arbitrator to remove a seller from the blacklist
* @param _seller Seller address
*/
function unBlacklistSeller(address _seller) public {
require(isLicenseOwner(msg.sender), "Arbitrator should have a valid license");
blacklist[msg.sender][_seller] = false;
emit UnBlacklistSeller(msg.sender, _seller);
}
/**
* @notice Checks if Arbitrator permits to use his/her services
* @param _seller sellers's address
* @param _arbitrator arbitrator's address
*/
function isAllowed(address _seller, address _arbitrator) public view returns(bool) {
return (arbitratorlicenseDetails[_arbitrator].acceptAny && !blacklist[_arbitrator][_seller]) || permissions[_arbitrator][_seller];
}
/**
* @notice Support for "approveAndCall". Callable only by `token()`.
* @param _from Who approved.
* @param _amount Amount being approved, need to be equal `price()`.
* @param _token Token being approved, need to be equal `token()`.
* @param _data Abi encoded data with selector of `buy(and)`.
*/
function receiveApproval(address _from, uint256 _amount, address _token, bytes memory _data) public {
require(_amount == price, "Wrong value");
require(_token == address(token), "Wrong token");
require(_token == address(msg.sender), "Wrong call");
require(_data.length == 4, "Wrong data length");
require(_abiDecodeBuy(_data) == bytes4(0xa6f2ae3a), "Wrong method selector"); //bytes4(keccak256("buy()"))
_buy(_from, false);
}
}
/* solium-disable no-empty-blocks */
/* solium-disable security/no-inline-assembly */
/**
* @dev Uses ethereum signed messages
*/
contract MessageSigned {
constructor() internal {}
/**
* @dev recovers address who signed the message
* @param _signHash operation ethereum signed message hash
* @param _messageSignature message `_signHash` signature
*/
function _recoverAddress(bytes32 _signHash, bytes memory _messageSignature)
internal
pure
returns(address)
{
uint8 v;
bytes32 r;
bytes32 s;
(v,r,s) = signatureSplit(_messageSignature);
return ecrecover(_signHash, v, r, s);
}
/**
* @dev Hash a hash with `"\x19Ethereum Signed Message:\n32"`
* @param _hash Sign to hash.
* @return Hash to be signed.
*/
function _getSignHash(bytes32 _hash) internal pure returns (bytes32 signHash) {
signHash = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", _hash));
}
/**
* @dev divides bytes signature into `uint8 v, bytes32 r, bytes32 s`
* @param _signature Signature string
*/
function signatureSplit(bytes memory _signature)
internal
pure
returns (uint8 v, bytes32 r, bytes32 s)
{
require(_signature.length == 65, "Bad signature length");
// The signature format is a compact form of:
// {bytes32 r}{bytes32 s}{uint8 v}
// Compact means, uint8 is not padded to 32 bytes.
assembly {
r := mload(add(_signature, 32))
s := mload(add(_signature, 64))
// Here we are loading the last 32 bytes, including 31 bytes
// of 's'. There is no 'mload8' to do this.
//
// 'byte' is not working due to the Solidity parser, so lets
// use the second best option, 'and'
v := and(mload(add(_signature, 65)), 0xff)
}
if (v < 27) {
v += 27;
}
require(v == 27 || v == 28, "Bad signature version");
}
}
contract SecuredFunctions is Ownable {
mapping(address => bool) public allowedContracts;
/// @notice Only allowed addresses and the same contract can invoke this function
modifier onlyAllowedContracts {
require(allowedContracts[msg.sender] || msg.sender == address(this), "Only allowed contracts can invoke this function");
_;
}
/**
* @dev Set contract addresses with special privileges to execute special functions
* @param _contract Contract address
* @param _allowed Is contract allowed?
*/
function setAllowedContract (
address _contract,
bool _allowed
) public onlyOwner {
allowedContracts[_contract] = _allowed;
}
}
contract Stakable is Ownable, SafeTransfer {
uint public basePrice = 0.01 ether;
address payable public burnAddress;
struct Stake {
uint amount;
address payable owner;
address token;
}
mapping(uint => Stake) public stakes;
mapping(address => uint) public stakeCounter;
event BurnAddressChanged(address sender, address prevBurnAddress, address newBurnAddress);
event BasePriceChanged(address sender, uint prevPrice, uint newPrice);
event Staked(uint indexed itemId, address indexed owner, uint amount);
event Unstaked(uint indexed itemId, address indexed owner, uint amount);
event Slashed(uint indexed itemId, address indexed owner, address indexed slasher, uint amount);
constructor(address payable _burnAddress) public {
burnAddress = _burnAddress;
}
/**
* @dev Changes the burn address
* @param _burnAddress New burn address
*/
function setBurnAddress(address payable _burnAddress) external onlyOwner {
emit BurnAddressChanged(msg.sender, burnAddress, _burnAddress);
burnAddress = _burnAddress;
}
/**
* @dev Changes the base price
* @param _basePrice New burn address
*/
function setBasePrice(uint _basePrice) external onlyOwner {
emit BasePriceChanged(msg.sender, basePrice, _basePrice);
basePrice = _basePrice;
}
function _stake(uint _itemId, address payable _owner, address _tokenAddress) internal {
require(stakes[_itemId].owner == address(0), "Already has/had a stake");
stakeCounter[_owner]++;
uint stakeAmount = basePrice * stakeCounter[_owner] * stakeCounter[_owner]; // y = basePrice * x^2
// Using only ETH as stake for phase 0
_tokenAddress = address(0);
require(msg.value == stakeAmount, "ETH amount is required");
// Uncomment to support tokens
/*
if (_tokenAddress != address(0)) {
require(msg.value == 0, "Cannot send ETH with token address different from 0");
ERC20Token tokenToPay = ERC20Token(_tokenAddress);
require(_safeTransferFrom(tokenToPay, _owner, address(this), stakeAmount), "Unsuccessful token transfer");
} else {
require(msg.value == stakeAmount, "ETH amount is required");
}
*/
stakes[_itemId].amount = stakeAmount;
stakes[_itemId].owner = _owner;
stakes[_itemId].token = _tokenAddress;
emit Staked(_itemId, _owner, stakeAmount);
}
function getAmountToStake(address _owner) public view returns(uint){
uint stakeCnt = stakeCounter[_owner] + 1;
return basePrice * stakeCnt * stakeCnt; // y = basePrice * x^2
}
function _unstake(uint _itemId) internal {
Stake storage s = stakes[_itemId];
if (s.amount == 0) return; // No stake for item
uint amount = s.amount;
s.amount = 0;
assert(stakeCounter[s.owner] > 0);
stakeCounter[s.owner]--;
if (s.token == address(0)) {
(bool success, ) = s.owner.call.value(amount)("");
require(success, "Transfer failed.");
} else {
require(_safeTransfer(ERC20Token(s.token), s.owner, amount), "Couldn't transfer funds");
}
emit Unstaked(_itemId, s.owner, amount);
}
function _slash(uint _itemId) internal {
Stake storage s = stakes[_itemId];
// TODO: what happens if offer was previosly validated and the user removed the stake?
if (s.amount == 0) return;
uint amount = s.amount;
s.amount = 0;
if (s.token == address(0)) {
(bool success, ) = burnAddress.call.value(amount)("");
require(success, "Transfer failed.");
} else {
require(_safeTransfer(ERC20Token(s.token), burnAddress, amount), "Couldn't transfer funds");
}
emit Slashed(_itemId, s.owner, msg.sender, amount);
}
function _refundStake(uint _itemId) internal {
Stake storage s = stakes[_itemId];
if (s.amount == 0) return;
uint amount = s.amount;
s.amount = 0;
stakeCounter[s.owner]--;
if (amount != 0) {
if (s.token == address(0)) {
(bool success, ) = s.owner.call.value(amount)("");
require(success, "Transfer failed.");
} else {
require(_safeTransfer(ERC20Token(s.token), s.owner, amount), "Couldn't transfer funds");
}
}
}
}
/**
* @title MetadataStore
* @dev User and offers registry
*/
contract MetadataStore is Stakable, MessageSigned, SecuredFunctions, Proxiable {
struct User {
string contactData;
string location;
string username;
}
struct Offer {
int16 margin;
uint[] paymentMethods;
uint limitL;
uint limitU;
address asset;
string currency;
address payable owner;
address payable arbitrator;
bool deleted;
}
License public sellingLicenses;
ArbitrationLicense public arbitrationLicenses;
mapping(address => User) public users;
mapping(address => uint) public user_nonce;
Offer[] public offers;
mapping(address => uint256[]) public addressToOffers;
mapping(address => mapping (uint256 => bool)) public offerWhitelist;
bool internal _initialized;
event OfferAdded(
address owner,
uint256 offerId,
address asset,
string location,
string currency,
string username,
uint[] paymentMethods,
uint limitL,
uint limitU,
int16 margin
);
event OfferRemoved(address owner, uint256 offerId);
/**
* @param _sellingLicenses Sellers licenses contract address
* @param _arbitrationLicenses Arbitrators licenses contract address
* @param _burnAddress Address to send slashed offer funds
*/
constructor(address _sellingLicenses, address _arbitrationLicenses, address payable _burnAddress) public
Stakable(_burnAddress)
{
init(_sellingLicenses, _arbitrationLicenses);
}
/**
* @dev Initialize contract (used with proxy). Can only be called once
* @param _sellingLicenses Sellers licenses contract address
* @param _arbitrationLicenses Arbitrators licenses contract address
*/
function init(
address _sellingLicenses,
address _arbitrationLicenses
) public {
assert(_initialized == false);
_initialized = true;
sellingLicenses = License(_sellingLicenses);
arbitrationLicenses = ArbitrationLicense(_arbitrationLicenses);
basePrice = 0.01 ether;
_setOwner(msg.sender);
}
function updateCode(address newCode) public onlyOwner {
updateCodeAddress(newCode);
}
event LicensesChanged(address sender, address oldSellingLicenses, address newSellingLicenses, address oldArbitrationLicenses, address newArbitrationLicenses);
/**
* @dev Initialize contract (used with proxy). Can only be called once
* @param _sellingLicenses Sellers licenses contract address
* @param _arbitrationLicenses Arbitrators licenses contract address
*/
function setLicenses(
address _sellingLicenses,
address _arbitrationLicenses
) public onlyOwner {
emit LicensesChanged(msg.sender, address(sellingLicenses), address(_sellingLicenses), address(arbitrationLicenses), (_arbitrationLicenses));
sellingLicenses = License(_sellingLicenses);
arbitrationLicenses = ArbitrationLicense(_arbitrationLicenses);
}
/**
* @dev Get datahash to be signed
* @param _username Username
* @param _contactData Contact Data ContactType:UserId
* @param _nonce Nonce value (obtained from user_nonce)
* @return bytes32 to sign
*/
function _dataHash(string memory _username, string memory _contactData, uint _nonce) internal view returns (bytes32) {
return keccak256(abi.encodePacked(address(this), _username, _contactData, _nonce));
}
/**
* @notice Get datahash to be signed
* @param _username Username
* @param _contactData Contact Data ContactType:UserId
* @return bytes32 to sign
*/
function getDataHash(string calldata _username, string calldata _contactData) external view returns (bytes32) {
return _dataHash(_username, _contactData, user_nonce[msg.sender]);
}
/**
* @dev Get signer address from signature. This uses the signature parameters to validate the signature
* @param _username Status username
* @param _contactData Contact Data ContactType:UserId
* @param _nonce User nonce
* @param _signature Signature obtained from the previous parameters
* @return Signing user address
*/
function _getSigner(
string memory _username,
string memory _contactData,
uint _nonce,
bytes memory _signature
) internal view returns(address) {
bytes32 signHash = _getSignHash(_dataHash(_username, _contactData, _nonce));
return _recoverAddress(signHash, _signature);
}
/**
* @notice Get signer address from signature
* @param _username Status username
* @param _contactData Contact Data ContactType:UserId
* @param _nonce User nonce
* @param _signature Signature obtained from the previous parameters
* @return Signing user address
*/
function getMessageSigner(
string calldata _username,
string calldata _contactData,
uint _nonce,
bytes calldata _signature
) external view returns(address) {
return _getSigner(_username, _contactData, _nonce, _signature);
}
/**
* @dev Adds or updates user information
* @param _user User address to update
* @param _contactData Contact Data ContactType:UserId
* @param _location New location
* @param _username New status username
*/
function _addOrUpdateUser(
address _user,
string memory _contactData,
string memory _location,
string memory _username
) internal {
User storage u = users[_user];
u.contactData = _contactData;
u.location = _location;
u.username = _username;
}
/**
* @notice Adds or updates user information via signature
* @param _signature Signature
* @param _contactData Contact Data ContactType:UserId
* @param _location New location
* @param _username New status username
* @return Signing user address
*/
function addOrUpdateUser(
bytes calldata _signature,
string calldata _contactData,
string calldata _location,
string calldata _username,
uint _nonce
) external returns(address payable _user) {
_user = address(uint160(_getSigner(_username, _contactData, _nonce, _signature)));
require(_nonce == user_nonce[_user], "Invalid nonce");
user_nonce[_user]++;
_addOrUpdateUser(_user, _contactData, _location, _username);
return _user;
}
/**
* @notice Adds or updates user information
* @param _contactData Contact Data ContactType:UserId
* @param _location New location
* @param _username New status username
* @return Signing user address
*/
function addOrUpdateUser(
string calldata _contactData,
string calldata _location,
string calldata _username
) external {
_addOrUpdateUser(msg.sender, _contactData, _location, _username);
}
/**
* @notice Adds or updates user information
* @dev can only be called by the escrow contract
* @param _sender Address that sets the user info
* @param _contactData Contact Data ContactType:UserId
* @param _location New location
* @param _username New status username
* @return Signing user address
*/
function addOrUpdateUser(
address _sender,
string calldata _contactData,
string calldata _location,
string calldata _username
) external onlyAllowedContracts {
_addOrUpdateUser(_sender, _contactData, _location, _username);
}
/**
* @dev Add a new offer with a new user if needed to the list
* @param _asset The address of the erc20 to exchange, pass 0x0 for Eth
* @param _contactData Contact Data ContactType:UserId
* @param _location The location on earth
* @param _currency The currency the user want to receive (USD, EUR...)
* @param _username The username of the user
* @param _paymentMethods The list of the payment methods the user accept
* @param _limitL Lower limit accepted
* @param _limitU Upper limit accepted
* @param _margin The margin for the user
* @param _arbitrator The arbitrator used by the offer
*/
function addOffer(
address _asset,
string memory _contactData,
string memory _location,
string memory _currency,
string memory _username,
uint[] memory _paymentMethods,
uint _limitL,
uint _limitU,
int16 _margin,
address payable _arbitrator
) public payable {
//require(sellingLicenses.isLicenseOwner(msg.sender), "Not a license owner");
// @TODO: limit number of offers if the sender is unlicensed?
require(arbitrationLicenses.isAllowed(msg.sender, _arbitrator), "Arbitrator does not allow this transaction");
require(_limitL <= _limitU, "Invalid limits");
require(msg.sender != _arbitrator, "Cannot arbitrate own offers");
_addOrUpdateUser(
msg.sender,
_contactData,
_location,
_username
);
Offer memory newOffer = Offer(
_margin,
_paymentMethods,
_limitL,
_limitU,
_asset,
_currency,
msg.sender,
_arbitrator,
false
);
uint256 offerId = offers.push(newOffer) - 1;
offerWhitelist[msg.sender][offerId] = true;
addressToOffers[msg.sender].push(offerId);
emit OfferAdded(
msg.sender,
offerId,
_asset,
_location,
_currency,
_username,
_paymentMethods,
_limitL,
_limitU,
_margin);
_stake(offerId, msg.sender, _asset);
}
/**
* @notice Remove user offer
* @dev Removed offers are marked as deleted instead of being deleted
* @param _offerId Id of the offer to remove
*/
function removeOffer(uint256 _offerId) external {
require(offerWhitelist[msg.sender][_offerId], "Offer does not exist");
offers[_offerId].deleted = true;
offerWhitelist[msg.sender][_offerId] = false;
emit OfferRemoved(msg.sender, _offerId);
_unstake(_offerId);
}
/**
* @notice Get the offer by Id
* @dev normally we'd access the offers array, but it would not return the payment methods
* @param _id Offer id
* @return Offer data (see Offer struct)
*/
function offer(uint256 _id) external view returns (
address asset,
string memory currency,
int16 margin,
uint[] memory paymentMethods,
uint limitL,
uint limitH,
address payable owner,
address payable arbitrator,
bool deleted
) {
Offer memory theOffer = offers[_id];
// In case arbitrator rejects the seller
address payable offerArbitrator = theOffer.arbitrator;
if(!arbitrationLicenses.isAllowed(theOffer.owner, offerArbitrator)){
offerArbitrator = address(0);
}
return (
theOffer.asset,
theOffer.currency,
theOffer.margin,
theOffer.paymentMethods,
theOffer.limitL,
theOffer.limitU,
theOffer.owner,
offerArbitrator,
theOffer.deleted
);
}
/**
* @notice Get the offer's owner by Id
* @dev Helper function
* @param _id Offer id
* @return Seller address
*/
function getOfferOwner(uint256 _id) external view returns (address payable) {
return (offers[_id].owner);
}
/**
* @notice Get the offer's asset by Id
* @dev Helper function
* @param _id Offer id
* @return Token address used in the offer
*/
function getAsset(uint256 _id) external view returns (address) {
return (offers[_id].asset);
}
/**
* @notice Get the offer's arbitrator by Id
* @dev Helper function
* @param _id Offer id
* @return Arbitrator address
*/
function getArbitrator(uint256 _id) external view returns (address payable) {
return (offers[_id].arbitrator);
}
/**
* @notice Get the size of the offers
* @return Number of offers stored in the contract
*/
function offersSize() external view returns (uint256) {
return offers.length;
}
/**
* @notice Get all the offer ids of the address in params
* @param _address Address of the offers
* @return Array of offer ids for a specific address
*/
function getOfferIds(address _address) external view returns (uint256[] memory) {
return addressToOffers[_address];
}
/**
* @dev Slash offer stake. If the sender is not the escrow contract, nothing will happen
* @param _offerId Offer Id to slash
*/
function slashStake(uint _offerId) external onlyAllowedContracts {
_slash(_offerId);
}
/**
* @dev Refunds a stake. Can be called automatically after an escrow is released
* @param _offerId Offer Id to slash
*/
function refundStake(uint _offerId) external onlyAllowedContracts {
_refundStake(_offerId);
}
}
// Contract that implements the relay recipient protocol. Inherited by Gatekeeper, or any other relay recipient.
//
// The recipient contract is responsible to:
// * pass a trusted IRelayHub singleton to the constructor.
// * Implement acceptRelayedCall, which acts as a whitelist/blacklist of senders. It is advised that the recipient's owner will be able to update that list to remove abusers.
// * In every function that cares about the sender, use "address sender = getSender()" instead of msg.sender. It'll return msg.sender for non-relayed transactions, or the real sender in case of relayed transactions.
contract IRelayRecipient {
/**
* return the relayHub of this contract.
*/
function getHubAddr() public view returns (address);
/**
* return the contract's balance on the RelayHub.
* can be used to determine if the contract can pay for incoming calls,
* before making any.
*/
function getRecipientBalance() public view returns (uint);
/*
* Called by Relay (and RelayHub), to validate if this recipient accepts this call.
* Note: Accepting this call means paying for the tx whether the relayed call reverted or not.
*
* @return "0" if the the contract is willing to accept the charges from this sender, for this function call.
* any other value is a failure. actual value is for diagnostics only.
* ** Note: values below 10 are reserved by canRelay
* @param relay the relay that attempts to relay this function call.
* the contract may restrict some encoded functions to specific known relays.
* @param from the sender (signer) of this function call.
* @param encodedFunction the encoded function call (without any ethereum signature).
* the contract may check the method-id for valid methods
* @param gasPrice - the gas price for this transaction
* @param transactionFee - the relay compensation (in %) for this transaction
* @param signature - sender's signature over all parameters except approvalData
* @param approvalData - extra dapp-specific data (e.g. signature from trusted party)
*/
function acceptRelayedCall(
address relay,
address from,
bytes calldata encodedFunction,
uint256 transactionFee,
uint256 gasPrice,
uint256 gasLimit,
uint256 nonce,
bytes calldata approvalData,
uint256 maxPossibleCharge
)
external
view
returns (uint256, bytes memory);
/*
* modifier to be used by recipients as access control protection for preRelayedCall & postRelayedCall
*/
modifier relayHubOnly() {
require(msg.sender == getHubAddr(),"Function can only be called by RelayHub");
_;
}
/** this method is called before the actual relayed function call.
* It may be used to charge the caller before (in conjuction with refunding him later in postRelayedCall for example).
* the method is given all parameters of acceptRelayedCall and actual used gas.
*
*
*** NOTICE: if this method modifies the contract's state, it must be protected with access control i.e. require msg.sender == getHubAddr()
*
*
* Revert in this functions causes a revert of the client's relayed call but not in the entire transaction
* (that is, the relay will still get compensated)
*/
function preRelayedCall(bytes calldata context) external returns (bytes32);
/** this method is called after the actual relayed function call.
* It may be used to record the transaction (e.g. charge the caller by some contract logic) for this call.
* the method is given all parameters of acceptRelayedCall, and also the success/failure status and actual used gas.
*
*
*** NOTICE: if this method modifies the contract's state, it must be protected with access control i.e. require msg.sender == getHubAddr()
*
*
* @param success - true if the relayed call succeeded, false if it reverted
* @param actualCharge - estimation of how much the recipient will be charged. This information may be used to perform local booking and
* charge the sender for this call (e.g. in tokens).
* @param preRetVal - preRelayedCall() return value passed back to the recipient
*
* Revert in this functions causes a revert of the client's relayed call but not in the entire transaction
* (that is, the relay will still get compensated)
*/
function postRelayedCall(bytes calldata context, bool success, uint actualCharge, bytes32 preRetVal) external;
}
contract IRelayHub {
// Relay management
// Add stake to a relay and sets its unstakeDelay.
// If the relay does not exist, it is created, and the caller
// of this function becomes its owner. If the relay already exists, only the owner can call this function. A relay
// cannot be its own owner.
// All Ether in this function call will be added to the relay's stake.
// Its unstake delay will be assigned to unstakeDelay, but the new value must be greater or equal to the current one.
// Emits a Staked event.
function stake(address relayaddr, uint256 unstakeDelay) external payable;
// Emited when a relay's stake or unstakeDelay are increased
event Staked(address indexed relay, uint256 stake, uint256 unstakeDelay);
// Registers the caller as a relay.
// The relay must be staked for, and not be a contract (i.e. this function must be called directly from an EOA).
// Emits a RelayAdded event.
// This function can be called multiple times, emitting new RelayAdded events. Note that the received transactionFee
// is not enforced by relayCall.
function registerRelay(uint256 transactionFee, string memory url) public;
// Emitted when a relay is registered or re-registerd. Looking at these events (and filtering out RelayRemoved
// events) lets a client discover the list of available relays.
event RelayAdded(address indexed relay, address indexed owner, uint256 transactionFee, uint256 stake, uint256 unstakeDelay, string url);
// Removes (deregisters) a relay. Unregistered (but staked for) relays can also be removed. Can only be called by
// the owner of the relay. After the relay's unstakeDelay has elapsed, unstake will be callable.
// Emits a RelayRemoved event.
function removeRelayByOwner(address relay) public;
// Emitted when a relay is removed (deregistered). unstakeTime is the time when unstake will be callable.
event RelayRemoved(address indexed relay, uint256 unstakeTime);
// Deletes the relay from the system, and gives back its stake to the owner. Can only be called by the relay owner,
// after unstakeDelay has elapsed since removeRelayByOwner was called.
// Emits an Unstaked event.
function unstake(address relay) public;
// Emitted when a relay is unstaked for, including the returned stake.
event Unstaked(address indexed relay, uint256 stake);
// States a relay can be in
enum RelayState {
Unknown, // The relay is unknown to the system: it has never been staked for
Staked, // The relay has been staked for, but it is not yet active
Registered, // The relay has registered itself, and is active (can relay calls)
Removed // The relay has been removed by its owner and can no longer relay calls. It must wait for its unstakeDelay to elapse before it can unstake
}
// Returns a relay's status. Note that relays can be deleted when unstaked or penalized.
function getRelay(address relay) external view returns (uint256 totalStake, uint256 unstakeDelay, uint256 unstakeTime, address payable owner, RelayState state);
// Balance management
// Deposits ether for a contract, so that it can receive (and pay for) relayed transactions. Unused balance can only
// be withdrawn by the contract itself, by callingn withdraw.
// Emits a Deposited event.
function depositFor(address target) public payable;
// Emitted when depositFor is called, including the amount and account that was funded.
event Deposited(address indexed recipient, address indexed from, uint256 amount);
// Returns an account's deposits. These can be either a contnract's funds, or a relay owner's revenue.
function balanceOf(address target) external view returns (uint256);
// Withdraws from an account's balance, sending it back to it. Relay owners call this to retrieve their revenue, and
// contracts can also use it to reduce their funding.
// Emits a Withdrawn event.
function withdraw(uint256 amount, address payable dest) public;
// Emitted when an account withdraws funds from RelayHub.
event Withdrawn(address indexed account, address indexed dest, uint256 amount);
// Relaying
// Check if the RelayHub will accept a relayed operation. Multiple things must be true for this to happen:
// - all arguments must be signed for by the sender (from)
// - the sender's nonce must be the current one
// - the recipient must accept this transaction (via acceptRelayedCall)
// Returns a PreconditionCheck value (OK when the transaction can be relayed), or a recipient-specific error code if
// it returns one in acceptRelayedCall.
function canRelay(
address relay,
address from,
address to,
bytes memory encodedFunction,
uint256 transactionFee,
uint256 gasPrice,
uint256 gasLimit,
uint256 nonce,
bytes memory signature,
bytes memory approvalData
) public view returns (uint256 status, bytes memory recipientContext);
// Preconditions for relaying, checked by canRelay and returned as the corresponding numeric values.
enum PreconditionCheck {
OK, // All checks passed, the call can be relayed
WrongSignature, // The transaction to relay is not signed by requested sender
WrongNonce, // The provided nonce has already been used by the sender
AcceptRelayedCallReverted, // The recipient rejected this call via acceptRelayedCall
InvalidRecipientStatusCode // The recipient returned an invalid (reserved) status code
}
// Relays a transaction. For this to suceed, multiple conditions must be met:
// - canRelay must return PreconditionCheck.OK
// - the sender must be a registered relay
// - the transaction's gas price must be larger or equal to the one that was requested by the sender
// - the transaction must have enough gas to not run out of gas if all internal transactions (calls to the
// recipient) use all gas available to them
// - the recipient must have enough balance to pay the relay for the worst-case scenario (i.e. when all gas is
// spent)
//
// If all conditions are met, the call will be relayed and the recipient charged. preRelayedCall, the encoded
// function and postRelayedCall will be called in order.
//
// Arguments:
// - from: the client originating the request
// - recipient: the target IRelayRecipient contract
// - encodedFunction: the function call to relay, including data
// - transactionFee: fee (%) the relay takes over actual gas cost
// - gasPrice: gas price the client is willing to pay
// - gasLimit: gas to forward when calling the encoded function
// - nonce: client's nonce
// - signature: client's signature over all previous params, plus the relay and RelayHub addresses
// - approvalData: dapp-specific data forwared to acceptRelayedCall. This value is *not* verified by the Hub, but
// it still can be used for e.g. a signature.
//
// Emits a TransactionRelayed event.
function relayCall(
address from,
address to,
bytes memory encodedFunction,
uint256 transactionFee,
uint256 gasPrice,
uint256 gasLimit,
uint256 nonce,
bytes memory signature,
bytes memory approvalData
) public;
// Emitted when an attempt to relay a call failed. This can happen due to incorrect relayCall arguments, or the
// recipient not accepting the relayed call. The actual relayed call was not executed, and the recipient not charged.
// The reason field contains an error code: values 1-10 correspond to PreconditionCheck entries, and values over 10
// are custom recipient error codes returned from acceptRelayedCall.
event CanRelayFailed(address indexed relay, address indexed from, address indexed to, bytes4 selector, uint256 reason);
// Emitted when a transaction is relayed. Note that the actual encoded function might be reverted: this will be
// indicated in the status field.
// Useful when monitoring a relay's operation and relayed calls to a contract.
// Charge is the ether value deducted from the recipient's balance, paid to the relay's owner.
event TransactionRelayed(address indexed relay, address indexed from, address indexed to, bytes4 selector, RelayCallStatus status, uint256 charge);
// Reason error codes for the TransactionRelayed event
enum RelayCallStatus {
OK, // The transaction was successfully relayed and execution successful - never included in the event
RelayedCallFailed, // The transaction was relayed, but the relayed call failed
PreRelayedFailed, // The transaction was not relayed due to preRelatedCall reverting
PostRelayedFailed, // The transaction was relayed and reverted due to postRelatedCall reverting
RecipientBalanceChanged // The transaction was relayed and reverted due to the recipient's balance changing
}
// Returns how much gas should be forwarded to a call to relayCall, in order to relay a transaction that will spend
// up to relayedCallStipend gas.
function requiredGas(uint256 relayedCallStipend) public view returns (uint256);
// Returns the maximum recipient charge, given the amount of gas forwarded, gas price and relay fee.
function maxPossibleCharge(uint256 relayedCallStipend, uint256 gasPrice, uint256 transactionFee) public view returns (uint256);
// Relay penalization. Any account can penalize relays, removing them from the system immediately, and rewarding the
// reporter with half of the relay's stake. The other half is burned so that, even if the relay penalizes itself, it
// still loses half of its stake.
// Penalize a relay that signed two transactions using the same nonce (making only the first one valid) and
// different data (gas price, gas limit, etc. may be different). The (unsigned) transaction data and signature for
// both transactions must be provided.
function penalizeRepeatedNonce(bytes memory unsignedTx1, bytes memory signature1, bytes memory unsignedTx2, bytes memory signature2) public;
// Penalize a relay that sent a transaction that didn't target RelayHub's registerRelay or relayCall.
function penalizeIllegalTransaction(bytes memory unsignedTx, bytes memory signature) public;
event Penalized(address indexed relay, address sender, uint256 amount);
function getNonce(address from) view external returns (uint256);
}
/*
Copyright 2018 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.
*/
library LibBytes {
using LibBytes for bytes;
/// @dev Gets the memory address for a byte array.
/// @param input Byte array to lookup.
/// @return memoryAddress Memory address of byte array. This
/// points to the header of the byte array which contains
/// the length.
function rawAddress(bytes memory input)
internal
pure
returns (uint256 memoryAddress)
{
assembly {
memoryAddress := input
}
return memoryAddress;
}
/// @dev Gets the memory address for the contents of a byte array.
/// @param input Byte array to lookup.
/// @return memoryAddress Memory address of the contents of the byte array.
function contentAddress(bytes memory input)
internal
pure
returns (uint256 memoryAddress)
{
assembly {
memoryAddress := add(input, 32)
}
return memoryAddress;
}
/// @dev Copies `length` bytes from memory location `source` to `dest`.
/// @param dest memory address to copy bytes to.
/// @param source memory address to copy bytes from.
/// @param length number of bytes to copy.
function memCopy(
uint256 dest,
uint256 source,
uint256 length
)
internal
pure
{
if (length < 32) {
// Handle a partial word by reading destination and masking
// off the bits we are interested in.
// This correctly handles overlap, zero lengths and source == dest
assembly {
let mask := sub(exp(256, sub(32, length)), 1)
let s := and(mload(source), not(mask))
let d := and(mload(dest), mask)
mstore(dest, or(s, d))
}
} else {
// Skip the O(length) loop when source == dest.
if (source == dest) {
return;
}
// For large copies we copy whole words at a time. The final
// word is aligned to the end of the range (instead of after the
// previous) to handle partial words. So a copy will look like this:
//
// ####
// ####
// ####
// ####
//
// We handle overlap in the source and destination range by
// changing the copying direction. This prevents us from
// overwriting parts of source that we still need to copy.
//
// This correctly handles source == dest
//
if (source > dest) {
assembly {
// We subtract 32 from `sEnd` and `dEnd` because it
// is easier to compare with in the loop, and these
// are also the addresses we need for copying the
// last bytes.
length := sub(length, 32)
let sEnd := add(source, length)
let dEnd := add(dest, length)
// Remember the last 32 bytes of source
// This needs to be done here and not after the loop
// because we may have overwritten the last bytes in
// source already due to overlap.
let last := mload(sEnd)
// Copy whole words front to back
// Note: the first check is always true,
// this could have been a do-while loop.
// solhint-disable-next-line no-empty-blocks
for {} lt(source, sEnd) {} {
mstore(dest, mload(source))
source := add(source, 32)
dest := add(dest, 32)
}
// Write the last 32 bytes
mstore(dEnd, last)
}
} else {
assembly {
// We subtract 32 from `sEnd` and `dEnd` because those
// are the starting points when copying a word at the end.
length := sub(length, 32)
let sEnd := add(source, length)
let dEnd := add(dest, length)
// Remember the first 32 bytes of source
// This needs to be done here and not after the loop
// because we may have overwritten the first bytes in
// source already due to overlap.
let first := mload(source)
// Copy whole words back to front
// We use a signed comparisson here to allow dEnd to become
// negative (happens when source and dest < 32). Valid
// addresses in local memory will never be larger than
// 2**255, so they can be safely re-interpreted as signed.
// Note: the first check is always true,
// this could have been a do-while loop.
// solhint-disable-next-line no-empty-blocks
for {} slt(dest, dEnd) {} {
mstore(dEnd, mload(sEnd))
sEnd := sub(sEnd, 32)
dEnd := sub(dEnd, 32)
}
// Write the first 32 bytes
mstore(dest, first)
}
}
}
}
/// @dev Returns a slices from a byte array.
/// @param b The byte array to take a slice from.
/// @param from The starting index for the slice (inclusive).
/// @param to The final index for the slice (exclusive).
/// @return result The slice containing bytes at indices [from, to)
function slice(
bytes memory b,
uint256 from,
uint256 to
)
internal
pure
returns (bytes memory result)
{
require(
from <= to,
"FROM_LESS_THAN_TO_REQUIRED"
);
require(
to <= b.length,
"TO_LESS_THAN_LENGTH_REQUIRED"
);
// Create a new bytes structure and copy contents
result = new bytes(to - from);
memCopy(
result.contentAddress(),
b.contentAddress() + from,
result.length
);
return result;
}
/// @dev Returns a slice from a byte array without preserving the input.
/// @param b The byte array to take a slice from. Will be destroyed in the process.
/// @param from The starting index for the slice (inclusive).
/// @param to The final index for the slice (exclusive).
/// @return result The slice containing bytes at indices [from, to)
/// @dev When `from == 0`, the original array will match the slice. In other cases its state will be corrupted.
function sliceDestructive(
bytes memory b,
uint256 from,
uint256 to
)
internal
pure
returns (bytes memory result)
{
require(
from <= to,
"FROM_LESS_THAN_TO_REQUIRED"
);
require(
to <= b.length,
"TO_LESS_THAN_LENGTH_REQUIRED"
);
// Create a new bytes structure around [from, to) in-place.
assembly {
result := add(b, from)
mstore(result, sub(to, from))
}
return result;
}
/// @dev Pops the last byte off of a byte array by modifying its length.
/// @param b Byte array that will be modified.
/// @return The byte that was popped off.
function popLastByte(bytes memory b)
internal
pure
returns (bytes1 result)
{
require(
b.length > 0,
"GREATER_THAN_ZERO_LENGTH_REQUIRED"
);
// Store last byte.
result = b[b.length - 1];
assembly {
// Decrement length of byte array.
let newLen := sub(mload(b), 1)
mstore(b, newLen)
}
return result;
}
/// @dev Pops the last 20 bytes off of a byte array by modifying its length.
/// @param b Byte array that will be modified.
/// @return The 20 byte address that was popped off.
function popLast20Bytes(bytes memory b)
internal
pure
returns (address result)
{
require(
b.length >= 20,
"GREATER_OR_EQUAL_TO_20_LENGTH_REQUIRED"
);
// Store last 20 bytes.
result = readAddress(b, b.length - 20);
assembly {
// Subtract 20 from byte array length.
let newLen := sub(mload(b), 20)
mstore(b, newLen)
}
return result;
}
/// @dev Tests equality of two byte arrays.
/// @param lhs First byte array to compare.
/// @param rhs Second byte array to compare.
/// @return True if arrays are the same. False otherwise.
function equals(
bytes memory lhs,
bytes memory rhs
)
internal
pure
returns (bool equal)
{
// Keccak gas cost is 30 + numWords * 6. This is a cheap way to compare.
// We early exit on unequal lengths, but keccak would also correctly
// handle this.
return lhs.length == rhs.length && keccak256(lhs) == keccak256(rhs);
}
/// @dev Reads an address from a position in a byte array.
/// @param b Byte array containing an address.
/// @param index Index in byte array of address.
/// @return address from byte array.
function readAddress(
bytes memory b,
uint256 index
)
internal
pure
returns (address result)
{
require(
b.length >= index + 20, // 20 is length of address
"GREATER_OR_EQUAL_TO_20_LENGTH_REQUIRED"
);
// Add offset to index:
// 1. Arrays are prefixed by 32-byte length parameter (add 32 to index)
// 2. Account for size difference between address length and 32-byte storage word (subtract 12 from index)
index += 20;
// Read address from array memory
assembly {
// 1. Add index to address of bytes array
// 2. Load 32-byte word from memory
// 3. Apply 20-byte mask to obtain address
result := and(mload(add(b, index)), 0xffffffffffffffffffffffffffffffffffffffff)
}
return result;
}
/// @dev Writes an address into a specific position in a byte array.
/// @param b Byte array to insert address into.
/// @param index Index in byte array of address.
/// @param input Address to put into byte array.
function writeAddress(
bytes memory b,
uint256 index,
address input
)
internal
pure
{
require(
b.length >= index + 20, // 20 is length of address
"GREATER_OR_EQUAL_TO_20_LENGTH_REQUIRED"
);
// Add offset to index:
// 1. Arrays are prefixed by 32-byte length parameter (add 32 to index)
// 2. Account for size difference between address length and 32-byte storage word (subtract 12 from index)
index += 20;
// Store address into array memory
assembly {
// The address occupies 20 bytes and mstore stores 32 bytes.
// First fetch the 32-byte word where we'll be storing the address, then
// apply a mask so we have only the bytes in the word that the address will not occupy.
// Then combine these bytes with the address and store the 32 bytes back to memory with mstore.
// 1. Add index to address of bytes array
// 2. Load 32-byte word from memory
// 3. Apply 12-byte mask to obtain extra bytes occupying word of memory where we'll store the address
let neighbors := and(
mload(add(b, index)),
0xffffffffffffffffffffffff0000000000000000000000000000000000000000
)
// Make sure input address is clean.
// (Solidity does not guarantee this)
input := and(input, 0xffffffffffffffffffffffffffffffffffffffff)
// Store the neighbors and address into memory
mstore(add(b, index), xor(input, neighbors))
}
}
/// @dev Reads a bytes32 value from a position in a byte array.
/// @param b Byte array containing a bytes32 value.
/// @param index Index in byte array of bytes32 value.
/// @return bytes32 value from byte array.
function readBytes32(
bytes memory b,
uint256 index
)
internal
pure
returns (bytes32 result)
{
require(
b.length >= index + 32,
"GREATER_OR_EQUAL_TO_32_LENGTH_REQUIRED"
);
// Arrays are prefixed by a 256 bit length parameter
index += 32;
// Read the bytes32 from array memory
assembly {
result := mload(add(b, index))
}
return result;
}
/// @dev Writes a bytes32 into a specific position in a byte array.
/// @param b Byte array to insert <input> into.
/// @param index Index in byte array of <input>.
/// @param input bytes32 to put into byte array.
function writeBytes32(
bytes memory b,
uint256 index,
bytes32 input
)
internal
pure
{
require(
b.length >= index + 32,
"GREATER_OR_EQUAL_TO_32_LENGTH_REQUIRED"
);
// Arrays are prefixed by a 256 bit length parameter
index += 32;
// Read the bytes32 from array memory
assembly {
mstore(add(b, index), input)
}
}
/// @dev Reads a uint256 value from a position in a byte array.
/// @param b Byte array containing a uint256 value.
/// @param index Index in byte array of uint256 value.
/// @return uint256 value from byte array.
function readUint256(
bytes memory b,
uint256 index
)
internal
pure
returns (uint256 result)
{
result = uint256(readBytes32(b, index));
return result;
}
/// @dev Writes a uint256 into a specific position in a byte array.
/// @param b Byte array to insert <input> into.
/// @param index Index in byte array of <input>.
/// @param input uint256 to put into byte array.
function writeUint256(
bytes memory b,
uint256 index,
uint256 input
)
internal
pure
{
writeBytes32(b, index, bytes32(input));
}
/// @dev Reads an unpadded bytes4 value from a position in a byte array.
/// @param b Byte array containing a bytes4 value.
/// @param index Index in byte array of bytes4 value.
/// @return bytes4 value from byte array.
function readBytes4(
bytes memory b,
uint256 index
)
internal
pure
returns (bytes4 result)
{
require(
b.length >= index + 4,
"GREATER_OR_EQUAL_TO_4_LENGTH_REQUIRED"
);
// Arrays are prefixed by a 32 byte length field
index += 32;
// Read the bytes4 from array memory
assembly {
result := mload(add(b, index))
// Solidity does not require us to clean the trailing bytes.
// We do it anyway
result := and(result, 0xFFFFFFFF00000000000000000000000000000000000000000000000000000000)
}
return result;
}
/// @dev Reads nested bytes from a specific position.
/// @dev NOTE: the returned value overlaps with the input value.
/// Both should be treated as immutable.
/// @param b Byte array containing nested bytes.
/// @param index Index of nested bytes.
/// @return result Nested bytes.
function readBytesWithLength(
bytes memory b,
uint256 index
)
internal
pure
returns (bytes memory result)
{
// Read length of nested bytes
uint256 nestedBytesLength = readUint256(b, index);
index += 32;
// Assert length of <b> is valid, given
// length of nested bytes
require(
b.length >= index + nestedBytesLength,
"GREATER_OR_EQUAL_TO_NESTED_BYTES_LENGTH_REQUIRED"
);
// Return a pointer to the byte array as it exists inside `b`
assembly {
result := add(b, index)
}
return result;
}
/// @dev Inserts bytes at a specific position in a byte array.
/// @param b Byte array to insert <input> into.
/// @param index Index in byte array of <input>.
/// @param input bytes to insert.
function writeBytesWithLength(
bytes memory b,
uint256 index,
bytes memory input
)
internal
pure
{
// Assert length of <b> is valid, given
// length of input
require(
b.length >= index + 32 + input.length, // 32 bytes to store length
"GREATER_OR_EQUAL_TO_NESTED_BYTES_LENGTH_REQUIRED"
);
// Copy <input> into <b>
memCopy(
b.contentAddress() + index,
input.rawAddress(), // includes length of <input>
input.length + 32 // +32 bytes to store <input> length
);
}
/// @dev Performs a deep copy of a byte array onto another byte array of greater than or equal length.
/// @param dest Byte array that will be overwritten with source bytes.
/// @param source Byte array to copy onto dest bytes.
function deepCopyBytes(
bytes memory dest,
bytes memory source
)
internal
pure
{
uint256 sourceLen = source.length;
// Dest length must be >= source length, or some bytes would not be copied.
require(
dest.length >= sourceLen,
"GREATER_OR_EQUAL_TO_SOURCE_BYTES_LENGTH_REQUIRED"
);
memCopy(
dest.contentAddress(),
source.contentAddress(),
sourceLen
);
}
}
contract RelayRecipient is IRelayRecipient {
IRelayHub private relayHub; // The IRelayHub singleton which is allowed to call us
function getHubAddr() public view returns (address) {
return address(relayHub);
}
/**
* Initialize the RelayHub of this contract.
* Must be called at least once (e.g. from the constructor), so that the contract can accept relayed calls.
* For ownable contracts, there should be a method to update the RelayHub, in case a new hub is deployed (since
* the RelayHub itself is not upgradeable)
* Otherwise, the contract might be locked on a dead hub, with no relays.
*/
function setRelayHub(IRelayHub _rhub) internal {
relayHub = _rhub;
//attempt a read method, just to validate the relay is a valid RelayHub contract.
getRecipientBalance();
}
function getRelayHub() internal view returns (IRelayHub) {
return relayHub;
}
/**
* return the balance of this contract.
* Note that this method will revert on configuration error (invalid relay address)
*/
function getRecipientBalance() public view returns (uint) {
return getRelayHub().balanceOf(address(this));
}
function getSenderFromData(address origSender, bytes memory msgData) public view returns (address) {
address sender = origSender;
if (origSender == getHubAddr()) {
// At this point we know that the sender is a trusted IRelayHub, so we trust that the last bytes of msg.data are the verified sender address.
// extract sender address from the end of msg.data
sender = LibBytes.readAddress(msgData, msgData.length - 20);
}
return sender;
}
/**
* return the sender of this call.
* if the call came through the valid RelayHub, return the original sender.
* otherwise, return `msg.sender`
* should be used in the contract anywhere instead of msg.sender
*/
function getSender() public view returns (address) {
return getSenderFromData(msg.sender, msg.data);
}
function getMessageData() public view returns (bytes memory) {
bytes memory origMsgData = msg.data;
if (msg.sender == getHubAddr()) {
// At this point we know that the sender is a trusted IRelayHub, so we trust that the last bytes of msg.data are the verified sender address.
// extract original message data from the start of msg.data
origMsgData = new bytes(msg.data.length - 20);
for (uint256 i = 0; i < origMsgData.length; i++)
{
origMsgData[i] = msg.data[i];
}
}
return origMsgData;
}
}
/**
* @title Escrow Relay (Gas Station Network)
*/
contract EscrowRelay is RelayRecipient, Ownable {
MetadataStore public metadataStore;
IEscrow public escrow;
address public snt;
mapping(address => uint) public lastActivity;
bytes4 constant CREATE_SIGNATURE = bytes4(keccak256("createEscrow(uint256,uint256,uint256,string,string,string)"));
bytes4 constant PAY_SIGNATURE = bytes4(keccak256("pay(uint256)"));
bytes4 constant CANCEL_SIGNATURE = bytes4(keccak256("cancel(uint256)"));
bytes4 constant OPEN_CASE_SIGNATURE = bytes4(keccak256("openCase(uint256,uint8)"));
bytes4 constant RATE_SIGNATURE = bytes4(keccak256("rateTransaction(uint256,uint256)"));
uint256 constant OK = 0;
uint256 constant ERROR_ENOUGH_BALANCE = 11;
uint256 constant ERROR_INVALID_ASSET = 12;
uint256 constant ERROR_TRX_TOO_SOON = 13;
uint256 constant ERROR_INVALID_BUYER = 14;
uint256 constant ERROR_GAS_PRICE = 15;
uint256 constant ERROR = 99;
/**
* @param _metadataStore Metadata Store Address
* @param _escrow IEscrow Instance Address
* @param _snt SNT address
*/
constructor(address _metadataStore, address _escrow, address _snt) public {
metadataStore = MetadataStore(_metadataStore);
escrow = IEscrow(_escrow);
snt = _snt;
}
/**
* @notice Set metadata store address
* @dev Only contract owner can execute this function
* @param _metadataStore New metadata store address
*/
function setMetadataStore(address _metadataStore) external onlyOwner {
metadataStore = MetadataStore(_metadataStore);
}
/**
* @notice Set escrow address
* @dev Only contract owner can execute this function
* @param _escrow New escrow address
*/
function setEscrow(address _escrow) external onlyOwner {
escrow = IEscrow(_escrow);
}
/**
* @notice Set gas station network hub address
* @dev Only contract owner can execute this function
* @param _relayHub New relay hub address
*/
function setRelayHubAddress(address _relayHub) external onlyOwner {
setRelayHub(IRelayHub(_relayHub));
}
/**
* @notice Determine if the timeout for relaying a create/cancel transaction has passed
* @param _account Account to verify
* @return bool
*/
function canCreateOrCancel(address _account) external view returns(bool) {
return (lastActivity[_account] + 15 minutes) < block.timestamp;
}
/**
* @notice Create a new escrow
* @param _offerId Offer
* @param _tokenAmount Amount buyer is willing to trade
* @param _fiatAmount Indicates how much FIAT will the user pay for the tokenAmount
* @param _contactData Contact Data ContactType:UserId
* @param _location The location on earth
* @param _username The username of the user
*/
function createEscrow(
uint _offerId,
uint _tokenAmount,
uint _fiatAmount,
string memory _contactData,
string memory _location,
string memory _username
) public returns (uint escrowId) {
address sender = getSender();
lastActivity[sender] = block.timestamp;
escrowId = escrow.createEscrow_relayed(
address(uint160(sender)),
_offerId,
_tokenAmount,
_fiatAmount,
_contactData,
_location,
_username
);
}
/**
* @notice Mark transaction as paid
* @param _escrowId Escrow to mark as paid
*/
function pay(uint _escrowId) external {
address sender = getSender();
escrow.pay_relayed(sender, _escrowId);
}
/**
* @notice Rate a transaction
* @param _escrowId Id of the escrow
* @param _rate rating of the transaction from 1 to 5
*/
function rateTransaction(uint _escrowId, uint _rate) external {
address sender = getSender();
escrow.rateTransaction_relayed(sender, _escrowId, _rate);
}
/**
* @notice Cancel an escrow
* @param _escrowId Escrow to cancel
*/
function cancel(uint _escrowId) external {
address sender = getSender();
lastActivity[sender] = block.timestamp;
escrow.cancel_relayed(sender, _escrowId);
}
/**
* @notice Open a dispute
* @param _escrowId Escrow to open a dispute
* @param _motive Motive a dispute is being opened
*/
function openCase(uint _escrowId, uint8 _motive) public {
address sender = getSender();
escrow.openCase_relayed(sender, _escrowId, _motive);
}
// =======================1=================================================
// Gas station network
/**
* @notice Function returning if we accept or not the relayed call (do we pay or not for the gas)
* @param from Address of the buyer getting a free transaction
* @param encodedFunction Function that will be called on the Escrow contract
* @param gasPrice Gas price
* @dev relay and transaction_fee are useless in our relay workflow
*/
function acceptRelayedCall(
address /* relay */,
address from,
bytes calldata encodedFunction,
uint256 /* transactionFee */,
uint256 gasPrice,
uint256 /* gasLimit */,
uint256 /* nonce */,
bytes calldata /* approvalData */,
uint256 /* maxPossibleCharge */
) external view returns (uint256, bytes memory)
{
bytes memory abiEncodedFunc = encodedFunction; // Call data elements cannot be accessed directly
bytes4 fSign;
uint dataValue;
assembly {
fSign := mload(add(abiEncodedFunc, add(0x20, 0)))
dataValue := mload(add(abiEncodedFunc, 36))
}
return (_evaluateConditionsToRelay(from, gasPrice, fSign, dataValue), "");
}
/**
* @dev Evaluates if the sender conditions are valid for relaying a escrow transaction
* @param from Sender
* @param gasPrice Gas Price
* @param functionSignature Function Signature
* @param dataValue Represents the escrowId or offerId depending on the function being called
*/
function _evaluateConditionsToRelay(address from, uint gasPrice, bytes4 functionSignature, uint dataValue) internal view returns (uint256) {
address token;
if(functionSignature == RATE_SIGNATURE && gasPrice < 20000000000){
return OK;
}
if(from.balance > 600000 * gasPrice) return ERROR_ENOUGH_BALANCE;
if(gasPrice > 20000000000) return ERROR_GAS_PRICE; // 20Gwei
if(functionSignature == PAY_SIGNATURE || functionSignature == CANCEL_SIGNATURE || functionSignature == OPEN_CASE_SIGNATURE){
address payable buyer;
(buyer, , token, ) = escrow.getBasicTradeData(dataValue);
if(buyer != from) return ERROR_INVALID_BUYER;
if(token != snt && token != address(0)) return ERROR_INVALID_ASSET;
if(functionSignature == CANCEL_SIGNATURE){ // Allow activity after 15min have passed
if((lastActivity[from] + 15 minutes) > block.timestamp) return ERROR_TRX_TOO_SOON;
}
return OK;
} else if(functionSignature == CREATE_SIGNATURE) {
token = metadataStore.getAsset(dataValue);
if(token != snt && token != address(0)) return ERROR_INVALID_ASSET;
// Allow activity after 15 min have passed
if((lastActivity[from] + 15 minutes) > block.timestamp) return ERROR_TRX_TOO_SOON;
return OK;
}
return ERROR;
}
/**
* @notice Function executed before the relay. Unused by us
*/
function preRelayedCall(bytes calldata) external returns (bytes32){
// nothing to be done pre-call.
// still, we must implement this method.
}
/**
* @notice Function executed after the relay. Unused by us
*/
function postRelayedCall(
bytes calldata /*context*/,
bool /*success*/,
uint /*actualCharge*/,
bytes32 /*preRetVal*/) external {
// nothing to be done post-call.
// still, we must implement this method.
}
}
|
Determine if the timeout for relaying a create/cancel transaction has passed _account Account to verify return bool/
|
function canCreateOrCancel(address _account) external view returns(bool) {
return (lastActivity[_account] + 15 minutes) < block.timestamp;
}
| 2,496,004 |
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity ^0.8.0;
import "./BlocksportTreasuryNode.sol";
import "./BlocksportAdminRole.sol";
import "./NFTMarketCore.sol";
import "./SendValueWithFallbackWithdraw.sol";
import "./NFTMarketCreators.sol";
import "./NFTMarketFees.sol";
import "./NFTMarketAuction.sol";
import "./NFTMarketReserveAuction.sol";
import "./ReentrancyGuardUpgradeable.sol";
/**
* @title A market for NFTs on Blocksport.
* @dev This top level file holds no data directly to ease future upgrades.
*/
contract BLSNFTMarket is
BlocksportTreasuryNode,
BlocksportAdminRole,
NFTMarketCore,
ReentrancyGuardUpgradeable,
NFTMarketCreators,
SendValueWithFallbackWithdraw,
NFTMarketFees,
NFTMarketAuction,
NFTMarketReserveAuction
{
/**
* @notice Called once to configure the contract after the initial deployment.
* @dev This farms the initialize call out to inherited contracts as needed.
*/
function initialize(address payable treasury) public initializer {
BlocksportTreasuryNode._initializeBlocksportTreasuryNode(treasury);
NFTMarketAuction._initializeNFTMarketAuction();
NFTMarketReserveAuction._initializeNFTMarketReserveAuction();
}
/**
* @notice Allows Blocksport to update the market configuration.
*/
function adminUpdateConfig(
uint256 minPercentIncrementInBasisPoints,
uint256 duration,
uint256 primaryblsFeeBasisPoints,
uint256 secondaryblsFeeBasisPoints,
uint256 secondaryCreatorFeeBasisPoints
) public onlyBlocksportAdmin {
_updateReserveAuctionConfig(minPercentIncrementInBasisPoints, duration);
_updateMarketFees(
primaryblsFeeBasisPoints,
secondaryblsFeeBasisPoints,
secondaryCreatorFeeBasisPoints
);
}
/**
* @dev Checks who the seller for an NFT is, this will check escrow or return the current owner if not in escrow.
* This is a no-op function required to avoid compile errors.
*/
function _getSellerFor(address nftContract, uint256 tokenId)
internal
view
virtual
override(NFTMarketCore, NFTMarketReserveAuction)
returns (address payable)
{
return super._getSellerFor(nftContract, tokenId);
}
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity ^0.8.0;
import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
import "./SafeMathUpgradeableExchange.sol";
import "./ReentrancyGuardUpgradeable.sol";
/**
* @notice Attempt to send ETH and if the transfer fails or runs out of gas, store the balance
* for future withdrawal instead.
*/
abstract contract SendValueWithFallbackWithdraw is ReentrancyGuardUpgradeable {
using AddressUpgradeable for address payable;
using SafeMathUpgradeableExchange for uint256;
mapping(address => uint256) private pendingWithdrawals;
event WithdrawPending(address indexed user, uint256 amount);
event Withdrawal(address indexed user, uint256 amount);
/**
* @notice Returns how much funds are available for manual withdraw due to failed transfers.
*/
function getPendingWithdrawal(address user) public view returns (uint256) {
return pendingWithdrawals[user];
}
/**
* @notice Allows a user to manually withdraw funds which originally failed to transfer to themselves.
*/
function withdraw() public {
withdrawFor(payable(msg.sender));
}
/**
* @notice Allows anyone to manually trigger a withdrawal of funds which originally failed to transfer for a user.
*/
function withdrawFor(address payable user) public nonReentrant {
uint256 amount = pendingWithdrawals[user];
require(amount > 0, "No funds are pending withdrawal");
pendingWithdrawals[user] = 0;
user.sendValue(amount);
emit Withdrawal(user, amount);
}
/**
* @dev Attempt to send a user ETH with a reasonably low gas limit of 20k,
* which is enough to send to contracts as well.
*/
function _sendValueWithFallbackWithdrawWithLowGasLimit(
address payable user,
uint256 amount
) internal {
_sendValueWithFallbackWithdraw(user, amount, 20000);
}
/**
* @dev Attempt to send a user or contract ETH with a moderate gas limit of 90k,
* which is enough for a 5-way split.
*/
function _sendValueWithFallbackWithdrawWithMediumGasLimit(
address payable user,
uint256 amount
) internal {
_sendValueWithFallbackWithdraw(user, amount, 210000);
}
/**
* @dev Attempt to send a user or contract ETH and if it fails store the amount owned for later withdrawal.
*/
function _sendValueWithFallbackWithdraw(
address payable user,
uint256 amount,
uint256 gasLimit
) private {
if (amount == 0) {
return;
}
// Cap the gas to prevent consuming all available gas to block a tx from completing successfully
// solhint-disable-next-line avoid-low-level-calls
(bool success, ) = user.call{value: amount, gas: gasLimit}("");
if (!success) {
// Record failed sends for a withdrawal later
// Transfers could fail if sent to a multisig with non-trivial receiver logic
// solhint-disable-next-line reentrancy
pendingWithdrawals[user] = pendingWithdrawals[user].add(amount);
emit WithdrawPending(user, amount);
}
}
uint256[499] private ______gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^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 SafeMathUpgradeableExchange {
/**
* @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.8.0;
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
function __ReentrancyGuard_init() internal initializer {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal initializer {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity ^0.8.0;
pragma abicoder v2; // solhint-disable-line
import "./SafeMathUpgradeableExchange.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol";
import "./ReentrancyGuardUpgradeable.sol";
import "./Constants.sol";
import "./NFTMarketCore.sol";
import "./NFTMarketFees.sol";
import "./SendValueWithFallbackWithdraw.sol";
import "./NFTMarketAuction.sol";
import "./BlocksportAdminRole.sol";
/**
* @notice Manages a reserve price auction for NFTs.
*/
abstract contract NFTMarketReserveAuction is
Constants,
BlocksportAdminRole,
NFTMarketCore,
ReentrancyGuardUpgradeable,
SendValueWithFallbackWithdraw,
NFTMarketFees,
NFTMarketAuction
{
using SafeMathUpgradeableExchange for uint256;
struct ReserveAuction {
address nftContract;
uint256 tokenId;
address payable seller;
uint256 duration;
uint256 extensionDuration;
uint256 endTime;
address payable bidder;
uint256 amount;
}
mapping(address => mapping(uint256 => uint256))
private nftContractToTokenIdToAuctionId;
mapping(uint256 => ReserveAuction) private auctionIdToAuction;
mapping(address => mapping(uint256 => bool)) public bannedTokens;
mapping(address => mapping(uint256 => ReserveAuction))
private bannedAuction;
uint256 private _minPercentIncrementInBasisPoints;
// This variable was used in an older version of the contract, left here as a gap to ensure upgrade compatibility
uint256 private ______gap_was_maxBidIncrementRequirement;
uint256 private _duration;
// These variables were used in an older version of the contract, left here as gaps to ensure upgrade compatibility
uint256 private ______gap_was_extensionDuration;
uint256 private ______gap_was_goLiveDate;
// Cap the max duration so that overflows will not occur
uint256 private constant MAX_MAX_DURATION = 1000 days;
uint256 private constant EXTENSION_DURATION = 15 minutes;
event ReserveAuctionConfigUpdated(
uint256 minPercentIncrementInBasisPoints,
uint256 maxBidIncrementRequirement,
uint256 duration,
uint256 extensionDuration,
uint256 goLiveDate
);
event ReserveAuctionCreated(
address indexed seller,
address indexed nftContract,
uint256 indexed tokenId,
uint256 duration,
uint256 extensionDuration,
uint256 reservePrice,
uint256 auctionId
);
event ReserveAuctionUpdated(
uint256 indexed auctionId,
uint256 reservePrice
);
event ReserveAuctionCanceled(uint256 indexed auctionId);
event ReserveAuctionBidPlaced(
uint256 indexed auctionId,
address indexed bidder,
uint256 amount,
uint256 endTime
);
event ReserveAuctionFinalized(
uint256 indexed auctionId,
address indexed seller,
address indexed bidder,
uint256 blsFee,
uint256 creatorFee,
uint256 ownerRev
);
event ReserveAuctionCanceledByAdmin(
uint256 indexed auctionId,
string reason
);
event ReserveAuctionBannedByAdmin(uint256 indexed auctionId, string reason);
event ReserveAuctionUnbannedByAdmin(uint256 indexed auctionId);
event TokenBannedByAdmin(
address indexed token,
uint256 indexed tokenId,
string reason
);
event TokenUnbannedByAdmin(address indexed token, uint256 indexed tokenId);
modifier onlyValidAuctionConfig(uint256 reservePrice) {
require(
reservePrice > 0,
"NFTMarketReserveAuction: Reserve price must be at least 1 wei"
);
_;
}
modifier notBanned(address nftContract, uint256 tokenId) {
require(
!bannedTokens[nftContract][tokenId],
"NFTMarketReserveAuction: This token banned"
);
_;
}
/**
* @notice Returns auction details for a given auctionId.
*/
function getReserveAuction(uint256 auctionId)
public
view
returns (ReserveAuction memory)
{
return auctionIdToAuction[auctionId];
}
/**
* @notice Returns the auctionId for a given NFT, or 0 if no auction is found.
* @dev If an auction is canceled, it will not be returned. However the auction may be over and pending finalization.
*/
function getReserveAuctionIdFor(address nftContract, uint256 tokenId)
public
view
returns (uint256)
{
return nftContractToTokenIdToAuctionId[nftContract][tokenId];
}
/**
* @dev Returns the seller that put a given NFT into escrow,
* or bubbles the call up to check the current owner if the NFT is not currently in escrow.
*/
function _getSellerFor(address nftContract, uint256 tokenId)
internal
view
virtual
override
returns (address payable)
{
address payable seller = auctionIdToAuction[
nftContractToTokenIdToAuctionId[nftContract][tokenId]
].seller;
if (seller == address(0)) {
return super._getSellerFor(nftContract, tokenId);
}
return seller;
}
/**
* @notice Returns the current configuration for reserve auctions.
*/
function getReserveAuctionConfig()
public
view
returns (uint256 minPercentIncrementInBasisPoints, uint256 duration)
{
minPercentIncrementInBasisPoints = _minPercentIncrementInBasisPoints;
duration = _duration;
}
function _initializeNFTMarketReserveAuction() internal {
_duration = 48 hours; // A sensible default value
}
function _updateReserveAuctionConfig(
uint256 minPercentIncrementInBasisPoints,
uint256 duration
) internal {
require(
minPercentIncrementInBasisPoints <= BASIS_POINTS,
"NFTMarketReserveAuction: Min increment must be <= 100%"
);
// Cap the max duration so that overflows will not occur
require(
duration <= MAX_MAX_DURATION,
"NFTMarketReserveAuction: Duration must be <= 1000 days"
);
require(
duration >= EXTENSION_DURATION,
"NFTMarketReserveAuction: Duration must be >= EXTENSION_DURATION"
);
_minPercentIncrementInBasisPoints = minPercentIncrementInBasisPoints;
_duration = duration;
// We continue to emit unused configuration variables to simplify the subgraph integration.
emit ReserveAuctionConfigUpdated(
minPercentIncrementInBasisPoints,
0,
duration,
EXTENSION_DURATION,
0
);
}
/**
* @notice Creates an auction for the given NFT.
* The NFT is held in escrow until the auction is finalized or canceled.
*/
function createReserveAuction(
address nftContract,
uint256 tokenId,
uint256 reservePrice
)
public
onlyValidAuctionConfig(reservePrice)
nonReentrant
notBanned(nftContract, tokenId)
{
// If an auction is already in progress then the NFT would be in escrow and the modifier would have failed
uint256 auctionId = _getNextAndIncrementAuctionId();
nftContractToTokenIdToAuctionId[nftContract][tokenId] = auctionId;
auctionIdToAuction[auctionId] = ReserveAuction(
nftContract,
tokenId,
payable(msg.sender),
_duration,
EXTENSION_DURATION,
0, // endTime is only known once the reserve price is met
payable(address(0)), // bidder is only known once a bid has been placed
reservePrice
);
IERC721Upgradeable(nftContract).transferFrom(
msg.sender,
address(this),
tokenId
);
emit ReserveAuctionCreated(
msg.sender,
nftContract,
tokenId,
_duration,
EXTENSION_DURATION,
reservePrice,
auctionId
);
}
/**
* @notice If an auction has been created but has not yet received bids, the configuration
* such as the reservePrice may be changed by the seller.
*/
function updateReserveAuction(uint256 auctionId, uint256 reservePrice)
public
onlyValidAuctionConfig(reservePrice)
{
ReserveAuction storage auction = auctionIdToAuction[auctionId];
require(
auction.seller == msg.sender,
"NFTMarketReserveAuction: Not your auction"
);
require(
auction.endTime == 0,
"NFTMarketReserveAuction: Auction in progress"
);
auction.amount = reservePrice;
emit ReserveAuctionUpdated(auctionId, reservePrice);
}
/**
* @notice If an auction has been created but has not yet received bids, it may be canceled by the seller.
* The NFT is returned to the seller from escrow.
*/
function cancelReserveAuction(uint256 auctionId) public nonReentrant {
ReserveAuction memory auction = auctionIdToAuction[auctionId];
require(
auction.seller == msg.sender,
"NFTMarketReserveAuction: Not your auction"
);
require(
auction.endTime == 0,
"NFTMarketReserveAuction: Auction in progress"
);
delete nftContractToTokenIdToAuctionId[auction.nftContract][
auction.tokenId
];
delete auctionIdToAuction[auctionId];
IERC721Upgradeable(auction.nftContract).transferFrom(
address(this),
auction.seller,
auction.tokenId
);
emit ReserveAuctionCanceled(auctionId);
}
/**
* @notice A bidder may place a bid which is at least the value defined by `getMinBidAmount`.
* If this is the first bid on the auction, the countdown will begin.
* If there is already an outstanding bid, the previous bidder will be refunded at this time
* and if the bid is placed in the final moments of the auction, the countdown may be extended.
*/
function placeBid(uint256 auctionId) public payable nonReentrant {
ReserveAuction storage auction = auctionIdToAuction[auctionId];
require(
auction.amount != 0,
"NFTMarketReserveAuction: Auction not found"
);
if (auction.endTime == 0) {
// If this is the first bid, ensure it's >= the reserve price
require(
auction.amount <= msg.value,
"NFTMarketReserveAuction: Bid must be at least the reserve price"
);
} else {
// If this bid outbids another, confirm that the bid is at least x% greater than the last
require(
auction.endTime >= block.timestamp,
"NFTMarketReserveAuction: Auction is over"
);
require(
auction.bidder != msg.sender,
"NFTMarketReserveAuction: You already have an outstanding bid"
);
uint256 minAmount = _getMinBidAmountForReserveAuction(
auction.amount
);
require(
msg.value >= minAmount,
"NFTMarketReserveAuction: Bid amount too low"
);
}
if (auction.endTime == 0) {
auction.amount = msg.value;
auction.bidder = payable(msg.sender);
// On the first bid, the endTime is now + duration
auction.endTime = block.timestamp + auction.duration;
} else {
// Cache and update bidder state before a possible reentrancy (via the value transfer)
uint256 originalAmount = auction.amount;
address payable originalBidder = auction.bidder;
auction.amount = msg.value;
auction.bidder = payable(msg.sender);
// When a bid outbids another, check to see if a time extension should apply.
if (auction.endTime - block.timestamp < auction.extensionDuration) {
auction.endTime = block.timestamp + auction.extensionDuration;
}
// Refund the previous bidder
_sendValueWithFallbackWithdrawWithLowGasLimit(
originalBidder,
originalAmount
);
}
emit ReserveAuctionBidPlaced(
auctionId,
msg.sender,
msg.value,
auction.endTime
);
}
/**
* @notice Once the countdown has expired for an auction, anyone can settle the auction.
* This will send the NFT to the highest bidder and distribute funds.
*/
function finalizeReserveAuction(uint256 auctionId) public nonReentrant {
ReserveAuction memory auction = auctionIdToAuction[auctionId];
require(
auction.endTime > 0,
"NFTMarketReserveAuction: Auction was already settled"
);
require(
auction.endTime < block.timestamp,
"NFTMarketReserveAuction: Auction still in progress"
);
delete nftContractToTokenIdToAuctionId[auction.nftContract][
auction.tokenId
];
delete auctionIdToAuction[auctionId];
IERC721Upgradeable(auction.nftContract).transferFrom(
address(this),
auction.bidder,
auction.tokenId
);
(
uint256 blsFee,
uint256 creatorFee,
uint256 ownerRev
) = _distributeFunds(
auction.nftContract,
auction.tokenId,
auction.seller,
auction.amount
);
emit ReserveAuctionFinalized(
auctionId,
auction.seller,
auction.bidder,
blsFee,
creatorFee,
ownerRev
);
}
/**
* @notice Returns the minimum amount a bidder must spend to participate in an auction.
*/
function getMinBidAmount(uint256 auctionId) public view returns (uint256) {
ReserveAuction storage auction = auctionIdToAuction[auctionId];
if (auction.endTime == 0) {
return auction.amount;
}
return _getMinBidAmountForReserveAuction(auction.amount);
}
/**
* @dev Determines the minimum bid amount when outbidding another user.
*/
function _getMinBidAmountForReserveAuction(uint256 currentBidAmount)
private
view
returns (uint256)
{
uint256 minIncrement = currentBidAmount.mul(
_minPercentIncrementInBasisPoints
) / BASIS_POINTS;
if (minIncrement == 0) {
// The next bid must be at least 1 wei greater than the current.
return currentBidAmount.add(1);
}
return minIncrement.add(currentBidAmount);
}
/**
* @notice Allows Blocksport to cancel an auction, refunding the bidder and returning the NFT to the seller.
* This should only be used for extreme cases such as DMCA takedown requests. The reason should always be provided.
*/
function _adminCancelReserveAuction(uint256 auctionId, string memory reason)
private
onlyBlocksportAdmin
{
require(
bytes(reason).length > 0,
"NFTMarketReserveAuction: Include a reason for this cancellation"
);
ReserveAuction memory auction = auctionIdToAuction[auctionId];
require(
auction.amount > 0,
"NFTMarketReserveAuction: Auction not found"
);
delete nftContractToTokenIdToAuctionId[auction.nftContract][
auction.tokenId
];
delete auctionIdToAuction[auctionId];
IERC721Upgradeable(auction.nftContract).transferFrom(
address(this),
auction.seller,
auction.tokenId
);
if (auction.bidder != address(0)) {
_sendValueWithFallbackWithdrawWithMediumGasLimit(
auction.bidder,
auction.amount
);
}
emit ReserveAuctionCanceledByAdmin(auctionId, reason);
}
function adminCancelReserveAuction(uint256 auctionId, string memory reason)
external
onlyBlocksportAdmin
{
_adminCancelReserveAuction(auctionId, reason);
}
/**
* @notice Allows Blocksport to ban token, refunding the bidder and returning the NFT to the seller.
*/
function adminBanToken(
address nftContract,
uint256 tokenId,
string memory reason
) public onlyBlocksportAdmin {
require(
bytes(reason).length > 0,
"NFTMarketReserveAuction: Include a reason for this ban"
);
require(!bannedTokens[nftContract][tokenId], "Token already banned");
uint256 auctionId = getReserveAuctionIdFor(nftContract, tokenId);
if (auctionIdToAuction[auctionId].tokenId == tokenId) {
bannedAuction[nftContract][tokenId] = auctionIdToAuction[auctionId];
_adminCancelReserveAuction(auctionId, reason);
emit ReserveAuctionBannedByAdmin(auctionId, reason);
}
bannedTokens[nftContract][tokenId] = true;
emit TokenBannedByAdmin(nftContract, tokenId, reason);
}
/**
* @notice Allows Blocksport to unban token, and list it again with no bids in the auction.
*/
function adminUnbanToken(address nftContract, uint256 tokenId)
public
onlyBlocksportAdmin
{
require(
!bannedTokens[nftContract][tokenId],
"NFTMarketReserveAuction: Token not banned"
);
if (bannedAuction[nftContract][tokenId].tokenId > 0) {
ReserveAuction memory auction = bannedAuction[nftContract][tokenId];
delete bannedAuction[nftContract][tokenId];
createReserveAuction(nftContract, auction.tokenId, auction.amount);
emit ReserveAuctionUnbannedByAdmin(auction.tokenId);
}
delete bannedTokens[nftContract][tokenId];
emit TokenUnbannedByAdmin(nftContract, tokenId);
}
uint256[1000] private ______gap;
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity ^0.8.0;
import "./SafeMathUpgradeableExchange.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol";
import "./BlocksportTreasuryNode.sol";
import "./Constants.sol";
import "./NFTMarketCore.sol";
import "./NFTMarketCreators.sol";
import "./SendValueWithFallbackWithdraw.sol";
/**
* @notice A mixin to distribute funds when an NFT is sold.
*/
abstract contract NFTMarketFees is
Constants,
Initializable,
BlocksportTreasuryNode,
NFTMarketCore,
NFTMarketCreators,
SendValueWithFallbackWithdraw
{
using SafeMathUpgradeableExchange for uint256;
event MarketFeesUpdated(
uint256 primaryBlocksportFeeBasisPoints,
uint256 secondaryBlocksportFeeBasisPoints,
uint256 secondaryCreatorFeeBasisPoints
);
uint256 private _primaryBlocksportFeeBasisPoints;
uint256 private _secondaryBlocksportFeeBasisPoints;
uint256 private _secondaryCreatorFeeBasisPoints;
mapping(address => mapping(uint256 => bool))
private nftContractToTokenIdToFirstSaleCompleted;
/**
* @notice Returns true if the given NFT has not been sold in this market previously and is being sold by the creator.
*/
function getIsPrimary(address nftContract, uint256 tokenId)
public
view
returns (bool)
{
return
_getIsPrimary(
nftContract,
tokenId,
_getCreator(nftContract, tokenId),
_getSellerFor(nftContract, tokenId)
);
}
/**
* @dev A helper that determines if this is a primary sale given the current seller.
* This is a minor optimization to use the seller if already known instead of making a redundant lookup call.
*/
function _getIsPrimary(
address nftContract,
uint256 tokenId,
address creator,
address seller
) private view returns (bool) {
return
!nftContractToTokenIdToFirstSaleCompleted[nftContract][tokenId] &&
creator == seller;
}
/**
* @notice Returns the current fee configuration in basis points.
*/
function getFeeConfig()
public
view
returns (
uint256 primaryBlocksportFeeBasisPoints,
uint256 secondaryBlocksportFeeBasisPoints,
uint256 secondaryCreatorFeeBasisPoints
)
{
return (
_primaryBlocksportFeeBasisPoints,
_secondaryBlocksportFeeBasisPoints,
_secondaryCreatorFeeBasisPoints
);
}
/**
* @notice Returns how funds will be distributed for a sale at the given price point.
* @dev This could be used to present exact fee distributing on listing or before a bid is placed.
*/
function getFees(
address nftContract,
uint256 tokenId,
uint256 price
)
public
view
returns (
uint256 blocksportFee,
uint256 creatorSecondaryFee,
uint256 ownerRev
)
{
(blocksportFee, , creatorSecondaryFee, , ownerRev) = _getFees(
nftContract,
tokenId,
_getSellerFor(nftContract, tokenId),
price
);
}
/**
* @dev Calculates how funds should be distributed for the given sale details.
* If this is a primary sale, the creator revenue will appear as `ownerRev`.
*/
function _getFees(
address nftContract,
uint256 tokenId,
address payable seller,
uint256 price
)
private
view
returns (
uint256 blocksportFee,
address payable creatorSecondaryFeeTo,
uint256 creatorSecondaryFee,
address payable ownerRevTo,
uint256 ownerRev
)
{
// The tokenCreatorPaymentAddress replaces the creator as the fee recipient.
(
address payable creator,
address payable tokenCreatorPaymentAddress
) = _getCreatorAndPaymentAddress(nftContract, tokenId);
uint256 blocksportFeeBasisPoints;
if (_getIsPrimary(nftContract, tokenId, creator, seller)) {
blocksportFeeBasisPoints = _primaryBlocksportFeeBasisPoints;
// On a primary sale, the creator is paid the remainder via `ownerRev`.
ownerRevTo = tokenCreatorPaymentAddress;
} else {
blocksportFeeBasisPoints = _secondaryBlocksportFeeBasisPoints;
// If there is no creator then funds go to the seller instead.
if (tokenCreatorPaymentAddress != address(0)) {
// SafeMath is not required when dividing by a constant value > 0.
creatorSecondaryFee =
price.mul(_secondaryCreatorFeeBasisPoints) /
BASIS_POINTS;
creatorSecondaryFeeTo = tokenCreatorPaymentAddress;
}
if (seller == creator) {
ownerRevTo = tokenCreatorPaymentAddress;
} else {
ownerRevTo = seller;
}
}
// SafeMath is not required when dividing by a constant value > 0.
blocksportFee = price.mul(blocksportFeeBasisPoints) / BASIS_POINTS;
ownerRev = price.sub(blocksportFee).sub(creatorSecondaryFee);
}
/**
* @dev Distributes funds to blocksport, creator, and NFT owner after a sale.
*/
function _distributeFunds(
address nftContract,
uint256 tokenId,
address payable seller,
uint256 price
)
internal
returns (
uint256 blocksportFee,
uint256 creatorFee,
uint256 ownerRev
)
{
address payable creatorFeeTo;
address payable ownerRevTo;
(
blocksportFee,
creatorFeeTo,
creatorFee,
ownerRevTo,
ownerRev
) = _getFees(nftContract, tokenId, seller, price);
// Anytime fees are distributed that indicates the first sale is complete,
// which will not change state during a secondary sale.
// This must come after the `_getFees` call above as this state is considered in the function.
nftContractToTokenIdToFirstSaleCompleted[nftContract][tokenId] = true;
_sendValueWithFallbackWithdrawWithLowGasLimit(
getBlocksportTreasury(),
blocksportFee
);
_sendValueWithFallbackWithdrawWithMediumGasLimit(
creatorFeeTo,
creatorFee
);
_sendValueWithFallbackWithdrawWithMediumGasLimit(ownerRevTo, ownerRev);
}
/**
* @notice Allows blocksport to change the market fees.
*/
function _updateMarketFees(
uint256 primaryBlocksportFeeBasisPoints,
uint256 secondaryBlocksportFeeBasisPoints,
uint256 secondaryCreatorFeeBasisPoints
) internal {
require(
primaryBlocksportFeeBasisPoints < BASIS_POINTS,
"NFTMarketFees: Fees >= 100%"
);
require(
secondaryBlocksportFeeBasisPoints.add(
secondaryCreatorFeeBasisPoints
) < BASIS_POINTS,
"NFTMarketFees: Fees >= 100%"
);
_primaryBlocksportFeeBasisPoints = primaryBlocksportFeeBasisPoints;
_secondaryBlocksportFeeBasisPoints = secondaryBlocksportFeeBasisPoints;
_secondaryCreatorFeeBasisPoints = secondaryCreatorFeeBasisPoints;
emit MarketFeesUpdated(
primaryBlocksportFeeBasisPoints,
secondaryBlocksportFeeBasisPoints,
secondaryCreatorFeeBasisPoints
);
}
uint256[1000] private ______gap;
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity ^0.8.0;
import "./IBLSNFT721.sol";
import "./ReentrancyGuardUpgradeable.sol";
/**
* @notice A mixin for associating creators to NFTs.
* @dev In the future this may store creators directly in order to support NFTs created on a different platform.
*/
abstract contract NFTMarketCreators is
ReentrancyGuardUpgradeable // Adding this unused mixin to help with linearization
{
/**
* @dev If the creator is not available then 0x0 is returned. Downstream this indicates that the creator
* fee should be sent to the current seller instead.
* This may apply when selling NFTs that were not minted on Blocksport.
*/
function _getCreator(address nftContract, uint256 tokenId)
internal
view
returns (address payable)
{
try IBLSNFT721(nftContract).tokenCreator(tokenId) returns (
address payable creator
) {
return creator;
} catch {
return payable(address(0));
}
}
/**
* @dev Returns the creator and a destination address for any payments to the creator,
* returns address(0) if the creator is unknown.
*/
function _getCreatorAndPaymentAddress(address nftContract, uint256 tokenId)
internal
view
returns (address payable, address payable)
{
address payable creator = _getCreator(nftContract, tokenId);
try
IBLSNFT721(nftContract).getTokenCreatorPaymentAddress(tokenId)
returns (address payable tokenCreatorPaymentAddress) {
if (tokenCreatorPaymentAddress != address(0)) {
return (creator, tokenCreatorPaymentAddress);
}
} catch // solhint-disable-next-line no-empty-blocks
{
// Fall through to return (creator, creator) below
}
return (creator, creator);
}
// 500 slots were added via the new SendValueWithFallbackWithdraw mixin
uint256[500] private ______gap;
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity ^0.8.0;
import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol";
/**
* @notice A place for common modifiers and functions used by various NFTMarket mixins, if any.
* @dev This also leaves a gap which can be used to add a new mixin to the top of the inheritance tree.
*/
abstract contract NFTMarketCore {
/**
* @dev If the auction did not have an escrowed seller to return, this falls back to return the current owner.
* This allows functions to calculate the correct fees before the NFT has been listed in auction.
*/
function _getSellerFor(address nftContract, uint256 tokenId)
internal
view
virtual
returns (address payable)
{
return payable(IERC721Upgradeable(nftContract).ownerOf(tokenId));
}
// 50 slots were consumed by adding ReentrancyGuardUpgradeable
uint256[950] private ______gap;
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity ^0.8.0;
/**
* @notice An abstraction layer for auctions.
* @dev This contract can be expanded with reusable calls and data as more auction types are added.
*/
abstract contract NFTMarketAuction {
/**
* @dev A global id for auctions of any type.
*/
uint256 private nextAuctionId;
function _initializeNFTMarketAuction() internal {
nextAuctionId = 1;
}
function _getNextAndIncrementAuctionId() internal returns (uint256) {
return nextAuctionId++;
}
uint256[1000] private ______gap;
}
// SPDX-License-Identifier: MIT OR Apache-2.0
// solhint-disable
pragma solidity ^0.8.0;
interface IBLSNFT721 {
function tokenCreator(uint256 tokenId)
external
view
returns (address payable);
function getTokenCreatorPaymentAddress(uint256 tokenId)
external
view
returns (address payable);
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity ^0.8.0;
/**
* @notice Interface for AdminRole which wraps the default admin role from
* OpenZeppelin's AccessControl for easy integration.
*/
interface IAdminRole {
function isAdmin(address account) external view returns (bool);
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity ^0.8.0;
/**
* @dev Constant values shared across mixins.
*/
abstract contract Constants {
uint256 internal constant BASIS_POINTS = 10000;
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity ^0.8.0;
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
/**
* @notice A mixin that stores a reference to the Blocksport treasury contract.
*/
abstract contract BlocksportTreasuryNode is Initializable {
using AddressUpgradeable for address payable;
address payable private treasury;
/**
* @dev Called once after the initial deployment to set the Blocksport treasury address.
*/
function _initializeBlocksportTreasuryNode(address payable _treasury)
internal
initializer
{
require(
_treasury.isContract(),
"BlocksportTreasuryNode: Address is not a contract"
);
treasury = _treasury;
}
/**
* @notice Returns the address of the Blocksport treasury.
*/
function getBlocksportTreasury() public view returns (address payable) {
return treasury;
}
// `______gap` is added to each mixin to allow adding new data slots or additional mixins in an upgrade-safe way.
uint256[2000] private __gap;
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity ^0.8.0;
import "./IAdminRole.sol";
import "./BlocksportTreasuryNode.sol";
/**
* @notice Allows a contract to leverage an admin role defined by the Blocksport contract.
*/
abstract contract BlocksportAdminRole is BlocksportTreasuryNode {
// This file uses 0 data slots (other than what's included via BlocksportTreasuryNode)
modifier onlyBlocksportAdmin() {
require(
IAdminRole(getBlocksportTreasury()).isAdmin(msg.sender),
"BlocksportAdminRole: caller does not have the Admin role"
);
_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165Upgradeable.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721Upgradeable is IERC165Upgradeable {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
|
Allows Blocksport to cancel an auction, refunding the bidder and returning the NFT to the seller. This should only be used for extreme cases such as DMCA takedown requests. The reason should always be provided./
|
function _adminCancelReserveAuction(uint256 auctionId, string memory reason)
private
onlyBlocksportAdmin
{
require(
bytes(reason).length > 0,
"NFTMarketReserveAuction: Include a reason for this cancellation"
);
ReserveAuction memory auction = auctionIdToAuction[auctionId];
require(
auction.amount > 0,
"NFTMarketReserveAuction: Auction not found"
);
delete nftContractToTokenIdToAuctionId[auction.nftContract][
auction.tokenId
];
delete auctionIdToAuction[auctionId];
IERC721Upgradeable(auction.nftContract).transferFrom(
address(this),
auction.seller,
auction.tokenId
);
if (auction.bidder != address(0)) {
_sendValueWithFallbackWithdrawWithMediumGasLimit(
auction.bidder,
auction.amount
);
}
emit ReserveAuctionCanceledByAdmin(auctionId, reason);
}
| 13,623,458 |
pragma solidity ^0.4.21;
/// @title SafeMath contract - Math operations with safety checks.
/// @author OpenZeppelin: https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/math/SafeMath.sol
contract SafeMath {
function mulsm(uint256 a, uint256 b) internal pure returns (uint256) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function divsm(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b > 0);
uint c = a / b;
assert(a == b * c + a % b);
return c;
}
function subsm(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function addsm(uint256 a, uint256 b) internal pure returns (uint256) {
uint c = a + b;
assert(c >= a);
return c;
}
function powsm(uint256 a, uint256 b) internal pure returns (uint256) {
uint c = a ** b;
assert(c >= a);
return c;
}
}
contract Owned {
event NewOwner(address old, address current);
event NewPotentialOwner(address old, address potential);
address public owner = msg.sender;
address public potentialOwner;
modifier onlyOwner {
require(msg.sender == owner);
_;
}
modifier onlyPotentialOwner {
require(msg.sender == potentialOwner);
_;
}
function setOwner(address _new) public onlyOwner {
emit NewPotentialOwner(owner, _new);
potentialOwner = _new;
}
function confirmOwnership() public onlyPotentialOwner {
emit NewOwner(owner, potentialOwner);
owner = potentialOwner;
potentialOwner = 0;
}
}
contract Managed is Owned {
event NewManager(address owner, address manager);
mapping (address => bool) public manager;
modifier onlyManager() {
require(manager[msg.sender] == true || msg.sender == owner);
_;
}
function setManager(address _manager) public onlyOwner {
emit NewManager(owner, _manager);
manager[_manager] = true;
}
function superManager(address _manager) internal {
emit NewManager(owner, _manager);
manager[_manager] = true;
}
function delManager(address _manager) public onlyOwner {
emit NewManager(owner, _manager);
manager[_manager] = false;
}
}
/// @title Abstract Token, ERC20 token interface
contract ERC20 {
function name() constant public returns (string);
function symbol() constant public returns (string);
function decimals() constant public returns (uint8);
function totalSupply() constant public returns (uint256);
function balanceOf(address owner) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
function allowance(address owner, address spender) public view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/// Full complete implements ERC 20 Token standard: https://github.com/ethereum/EIPs/issues/20
contract StandardToken is SafeMath, ERC20 {
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
mapping (address => uint256) internal balances;
mapping (address => mapping (address => uint256)) internal allowed;
/// @dev Returns number of tokens owned by given address.
function name() public view returns (string) {
return name;
}
/// @dev Returns number of tokens owned by given address.
function symbol() public view returns (string) {
return symbol;
}
/// @dev Returns number of tokens owned by given address.
function decimals() public view returns (uint8) {
return decimals;
}
/// @dev Returns number of tokens owned by given address.
function totalSupply() public view returns (uint256) {
return totalSupply;
}
/// @dev Returns number of tokens owned by given address.
/// @param _owner Address of token owner.
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
/// @dev Transfers sender's tokens to a given address. Returns success.
/// @param _to Address of token receiver.
/// @param _value Number of tokens to transfer.
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(this)); //prevent direct send to contract
if (balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]) {
balances[msg.sender] -= _value;
balances[_to] += _value;
emit Transfer(msg.sender, _to, _value);
return true;
}
else {
return false;
}
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]) {
balances[_to] += _value;
balances[_from] -= _value;
allowed[_from][msg.sender] -= _value;
emit Transfer(_from, _to, _value);
return true;
}
else {
return false;
}
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
}
/**
@title ERC827 interface, an extension of ERC20 token standard
Interface of a ERC827 token, following the ERC20 standard with extra
methods to transfer value and data and execute calls in transfers and
approvals.
*/
contract ERC827 {
function approve( address _spender, uint256 _value, bytes _data ) public returns (bool);
function transfer( address _to, uint256 _value, bytes _data ) public returns (bool);
function transferFrom( address _from, address _to, uint256 _value, bytes _data ) public returns (bool);
}
/**
@title ERC827, an extension of ERC20 token standard
Implementation the ERC827, following the ERC20 standard with extra
methods to transfer value and data and execute calls in transfers and
approvals.
Uses OpenZeppelin StandardToken.
*/
contract ERC827Token is ERC827, StandardToken {
/**
@dev Addition to ERC20 token methods. It allows to
approve the transfer of value and execute a call with the sent data.
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 that will spend the funds.
@param _value The amount of tokens to be spent.
@param _data ABI-encoded contract call to call `_to` address.
@return true if the call function was executed successfully
*/
function approve(address _spender, uint256 _value, bytes _data) public returns (bool) {
require(_spender != address(this));
super.approve(_spender, _value);
require(_spender.call(_data));
return true;
}
function transfer(address _to, uint256 _value, bytes _data) public returns (bool) {
require(_to != address(this));
super.transfer(_to, _value);
require(_to.call(_data));
return true;
}
function transferFrom(address _from, address _to, uint256 _value, bytes _data) public returns (bool) {
require(_to != address(this));
super.transferFrom(_from, _to, _value);
require(_to.call(_data));
return true;
}
}
contract MintableToken is ERC827Token {
uint256 constant maxSupply = 1e30; // max amount of tokens 1 trillion
bool internal mintable = true;
modifier isMintable() {
require(mintable);
_;
}
function stopMint() internal {
mintable = false;
}
// triggered when the total supply is increased
event Issuance(uint256 _amount);
// triggered when the total supply is decreased
event Destruction(uint256 _amount);
/**
@dev increases the token supply and sends the new tokens to an account
can only be called by the contract owner
@param _to account to receive the new amount
@param _amount amount to increase the supply by
*/
function issue(address _to, uint256 _amount) internal {
assert(totalSupply + _amount <= maxSupply); // prevent overflows
totalSupply += _amount;
balances[_to] += _amount;
emit Issuance(_amount);
emit Transfer(this, _to, _amount);
}
/**
@dev removes tokens from an account and decreases the token supply
can only be called by the contract owner
(if robbers detected, if will be consensus about token amount)
@param _from account to remove the amount from
@param _amount amount to decrease the supply by
*/
/* function destroy(address _from, uint256 _amount) public onlyOwner {
balances[_from] -= _amount;
_totalSupply -= _amount;
Transfer(_from, this, _amount);
Destruction(_amount);
} */
}
contract PaymentManager is MintableToken, Owned {
uint256 public receivedWais;
uint256 internal _price;
bool internal paused = false;
modifier isSuspended() {
require(!paused);
_;
}
function setPrice(uint256 _value) public onlyOwner returns (bool) {
_price = _value;
return true;
}
function watchPrice() public view returns (uint256 price) {
return _price;
}
function rateSystem(address _to, uint256 _value) internal returns (bool) {
uint256 _amount;
if(_value >= (1 ether / 1000) && _value <= 1 ether) {
_amount = _value * _price;
} else
if(_value >= 1 ether) {
_amount = divsm(powsm(_value, 2), 1 ether) * _price;
}
issue(_to, _amount);
if(paused == false) {
if(totalSupply > 1 * 10e9 * 1 * 1 ether) paused = true; // if more then 10 billions stop sell
}
return true;
}
/** @dev transfer ethereum from contract */
function transferEther(address _to, uint256 _value) public onlyOwner {
_to.transfer(_value);
}
}
contract InvestBox is PaymentManager, Managed {
// triggered when the amount of reaward are changed
event BonusChanged(uint256 _amount);
// triggered when making invest
event Invested(address _from, uint256 _value);
// triggered when invest closed or updated
event InvestClosed(address _who, uint256 _value);
// triggered when counted
event Counted(address _sender, uint256 _intervals);
uint256 constant _day = 24 * 60 * 60 * 1 seconds;
bytes5 internal _td = bytes5("day");
bytes5 internal _tw = bytes5("week");
bytes5 internal _tm = bytes5("month");
bytes5 internal _ty = bytes5("year");
uint256 internal _creation;
uint256 internal _1sty;
uint256 internal _2ndy;
uint256 internal min_invest;
uint256 internal max_invest;
struct invest {
bool exists;
uint256 balance;
uint256 created; // creation time
uint256 closed; // closing time
}
mapping (address => mapping (bytes5 => invest)) public investInfo;
function stringToBytes32(string memory source) internal pure returns (bytes32 result) {
bytes memory tempEmptyStringTest = bytes(source);
if (tempEmptyStringTest.length == 0) {
return 0x0;
}
assembly {
result := mload(add(source, 32))
}
}
/** @dev return in interface string encoded to bytes (max len 5 bytes) */
function stringToBytes5(string _data) public pure returns (bytes5) {
return bytes5(stringToBytes32(_data));
}
struct intervalBytecodes {
string day;
string week;
string month;
string year;
}
intervalBytecodes public IntervalBytecodes;
/** @dev setter min max params for investition */
function setMinMaxInvestValue(uint256 _min, uint256 _max) public onlyOwner {
min_invest = _min * 10 ** uint256(decimals);
max_invest = _max * 10 ** uint256(decimals);
}
/** @dev number of complete cycles d/m/w/y */
function countPeriod(address _investor, bytes5 _t) internal view returns (uint256) {
uint256 _period;
uint256 _now = now; // blocking timestamp
if (_t == _td) _period = 1 * _day;
if (_t == _tw) _period = 7 * _day;
if (_t == _tm) _period = 31 * _day;
if (_t == _ty) _period = 365 * _day;
invest storage inv = investInfo[_investor][_t];
if (_now - inv.created < _period) return 0;
return (_now - inv.created)/_period; // get full days
}
/** @dev loop 'for' wrapper, where 100,000%, 10^3 decimal */
function loopFor(uint256 _condition, uint256 _data, uint256 _bonus) internal pure returns (uint256 r) {
assembly {
for { let i := 0 } lt(i, _condition) { i := add(i, 1) } {
let m := mul(_data, _bonus)
let d := div(m, 100000)
_data := add(_data, d)
}
r := _data
}
}
/** @dev invest box controller */
function rewardController(address _investor, bytes5 _type) internal view returns (uint256) {
uint256 _period;
uint256 _balance;
uint256 _created;
invest storage inv = investInfo[msg.sender][_type];
_period = countPeriod(_investor, _type);
_balance = inv.balance;
_created = inv.created;
uint256 full_steps;
uint256 last_step;
uint256 _d;
if(_type == _td) _d = 365;
if(_type == _tw) _d = 54;
if(_type == _tm) _d = 12;
if(_type == _ty) _d = 1;
full_steps = _period/_d;
last_step = _period - (full_steps * _d);
for(uint256 i=0; i<full_steps; i++) { // not executed if zero
_balance = compaundIntrest(_d, _type, _balance, _created);
_created += 1 years;
}
if(last_step > 0) _balance = compaundIntrest(last_step, _type, _balance, _created);
return _balance;
}
/**
@dev Compaund Intrest realization, return balance + Intrest
@param _period - time interval dependent from invest time
*/
function compaundIntrest(uint256 _period, bytes5 _type, uint256 _balance, uint256 _created) internal view returns (uint256) {
uint256 full_steps;
uint256 last_step;
uint256 _d = 100; // safe divider
uint256 _bonus = bonusSystem(_type, _created);
if (_period>_d) {
full_steps = _period/_d;
last_step = _period - (full_steps * _d);
for(uint256 i=0; i<full_steps; i++) {
_balance = loopFor(_d, _balance, _bonus);
}
if(last_step > 0) _balance = loopFor(last_step, _balance, _bonus);
} else
if (_period<=_d) {
_balance = loopFor(_period, _balance, _bonus);
}
return _balance;
}
/** @dev Bonus program */
function bonusSystem(bytes5 _t, uint256 _now) internal view returns (uint256) {
uint256 _b;
if (_t == _td) {
if (_now < _1sty) {
_b = 600; // 0.6 %/day // 100.6 % by day => 887.69 % by year
} else
if (_now >= _1sty && _now < _2ndy) {
_b = 300; // 0.3 %/day
} else
if (_now >= _2ndy) {
_b = 30; // 0.03 %/day
}
}
if (_t == _tw) {
if (_now < _1sty) {
_b = 5370; // 0.75 %/day => 5.37 % by week => 1529.13 % by year
} else
if (_now >= _1sty && _now < _2ndy) {
_b = 2650; // 0.375 %/day
} else
if (_now >= _2ndy) {
_b = 270; // 0.038 %/day
}
}
if (_t == _tm) {
if (_now < _1sty) {
_b = 30000; // 0.85 %/day // 130 % by month => 2196.36 % by year
} else
if (_now >= _1sty && _now < _2ndy) {
_b = 14050; // 0.425 %/day
} else
if (_now >= _2ndy) {
_b = 1340; // 0.043 %/day
}
}
if (_t == _ty) {
if (_now < _1sty) {
_b = 3678000; // 1 %/day // 3678.34 * 1000 = 3678340 = 3678% by year
} else
if (_now >= _1sty && _now < _2ndy) {
_b = 517470; // 0.5 %/day
} else
if (_now >= _2ndy) {
_b = 20020; // 0.05 %/day
}
}
return _b;
}
/** @dev make invest */
function makeInvest(uint256 _value, bytes5 _interval) internal isMintable {
require(min_invest <= _value && _value <= max_invest); // min max condition
assert(balances[msg.sender] >= _value && balances[this] + _value > balances[this]);
balances[msg.sender] -= _value;
balances[this] += _value;
invest storage inv = investInfo[msg.sender][_interval];
if (inv.exists == false) { // if invest no exists
inv.balance = _value;
inv.created = now;
inv.closed = 0;
emit Transfer(msg.sender, this, _value);
} else
if (inv.exists == true) {
uint256 rew = rewardController(msg.sender, _interval);
inv.balance = _value + rew;
inv.closed = 0;
emit Transfer(0x0, this, rew); // fix rise total supply
}
inv.exists = true;
emit Invested(msg.sender, _value);
if(totalSupply > maxSupply) stopMint(); // stop invest
}
function makeDailyInvest(uint256 _value) public {
makeInvest(_value * 10 ** uint256(decimals), _td);
}
function makeWeeklyInvest(uint256 _value) public {
makeInvest(_value * 10 ** uint256(decimals), _tw);
}
function makeMonthlyInvest(uint256 _value) public {
makeInvest(_value * 10 ** uint256(decimals), _tm);
}
function makeAnnualInvest(uint256 _value) public {
makeInvest(_value * 10 ** uint256(decimals), _ty);
}
/** @dev close invest */
function closeInvest(bytes5 _interval) internal {
uint256 _intrest;
address _to = msg.sender;
uint256 _period = countPeriod(_to, _interval);
invest storage inv = investInfo[_to][_interval];
uint256 _value = inv.balance;
if (_period == 0) {
balances[this] -= _value;
balances[_to] += _value;
emit Transfer(this, _to, _value); // tx of begining balance
emit InvestClosed(_to, _value);
} else
if (_period > 0) {
// Destruction init
balances[this] -= _value;
totalSupply -= _value;
emit Transfer(this, 0x0, _value);
emit Destruction(_value);
// Issue init
_intrest = rewardController(_to, _interval);
if(manager[msg.sender]) {
_intrest = mulsm(divsm(_intrest, 100), 105); // addition 5% bonus for manager
}
issue(_to, _intrest); // tx of %
emit InvestClosed(_to, _intrest);
}
inv.exists = false; // invest inv clear
inv.balance = 0;
inv.closed = now;
}
function closeDailyInvest() public {
closeInvest(_td);
}
function closeWeeklyInvest() public {
closeInvest(_tw);
}
function closeMonthlyInvest() public {
closeInvest(_tm);
}
function closeAnnualInvest() public {
closeInvest(_ty);
}
/** @dev safe closing invest, checking for complete by date. */
function isFullInvest(address _ms, bytes5 _t) internal returns (uint256) {
uint256 res = countPeriod(_ms, _t);
emit Counted(msg.sender, res);
return res;
}
function countDays() public returns (uint256) {
return isFullInvest(msg.sender, _td);
}
function countWeeks() public returns (uint256) {
return isFullInvest(msg.sender, _tw);
}
function countMonths() public returns (uint256) {
return isFullInvest(msg.sender, _tm);
}
function countYears() public returns (uint256) {
return isFullInvest(msg.sender, _ty);
}
}
contract EthereumRisen is InvestBox {
// devs addresess, pay for code
address public devWallet = address(0x00FBB38c017843DFa86a97c31fECaCFF0a092F6F);
uint256 constant public devReward = 100000 * 1e18; // 100K
// fondation for pay by promotion this project
address public bountyWallet = address(0x00Ed07D0170B1c5F3EeDe1fC7261719e04b15ecD);
uint256 constant public bountyReward = 50000 * 1e18; // 50K
// will be send for first 10k rischest wallets, if it is enough to pay the commission
address public airdropWallet = address(0x000DdB5A903d15b2F7f7300f672d2EB9bF882143);
uint256 constant public airdropReward = 99900 * 1e18; // 99.9K
bool internal _airdrop_status = false;
uint256 internal _paySize;
/** init airdrop program if cap will reach сost price */
function startAirdrop() public onlyOwner {
if(address(this).balance < 5 ether && _airdrop_status == true) revert();
issue(airdropWallet, airdropReward);
_paySize = 999 * 1e16; // 9.99 tokens
_airdrop_status = true;
}
/**
@dev notify owners about their balances was in promo action.
@param _holders addresses of the owners to be notified ["address_1", "address_2", ..]
*/
function airdropper(address [] _holders, uint256 _pay_size) public onlyManager {
if(_pay_size == 0) _pay_size = _paySize; // if empty set default
if(_pay_size < 1 * 1e18) revert(); // limit no less then 1 token
uint256 count = _holders.length;
require(count <= 200);
assert(_pay_size * count <= balanceOf(msg.sender));
for (uint256 i = 0; i < count; i++) {
transfer(_holders [i], _pay_size);
}
}
function EthereumRisen() public {
name = "Ethereum Risen";
symbol = "ETR";
decimals = 18;
totalSupply = 0;
_creation = now;
_1sty = now + 365 * 1 days;
_2ndy = now + 2 * 365 * 1 days;
PaymentManager.setPrice(10000);
Managed.setManager(bountyWallet);
InvestBox.IntervalBytecodes = intervalBytecodes(
"0x6461790000",
"0x7765656b00",
"0x6d6f6e7468",
"0x7965617200"
);
InvestBox.setMinMaxInvestValue(1000,100000000);
issue(bountyWallet, bountyReward);
issue(devWallet, devReward);
}
function() public payable isSuspended {
require(msg.value >= (1 ether / 100));
if(msg.value >= 5 ether) superManager(msg.sender); // you can make airdrop from this contract
rateSystem(msg.sender, msg.value);
receivedWais = addsm(receivedWais, msg.value); // count ether which was spent to contract
}
}
|
Bonus program /
|
function bonusSystem(bytes5 _t, uint256 _now) internal view returns (uint256) {
uint256 _b;
if (_t == _td) {
if (_now < _1sty) {
} else
if (_now >= _1sty && _now < _2ndy) {
} else
if (_now >= _2ndy) {
}
}
if (_t == _td) {
if (_now < _1sty) {
} else
if (_now >= _1sty && _now < _2ndy) {
} else
if (_now >= _2ndy) {
}
}
if (_t == _td) {
if (_now < _1sty) {
} else
if (_now >= _1sty && _now < _2ndy) {
} else
if (_now >= _2ndy) {
}
}
if (_t == _td) {
if (_now < _1sty) {
} else
if (_now >= _1sty && _now < _2ndy) {
} else
if (_now >= _2ndy) {
}
}
if (_t == _tw) {
if (_now < _1sty) {
} else
if (_now >= _1sty && _now < _2ndy) {
} else
if (_now >= _2ndy) {
}
}
if (_t == _tw) {
if (_now < _1sty) {
} else
if (_now >= _1sty && _now < _2ndy) {
} else
if (_now >= _2ndy) {
}
}
if (_t == _tw) {
if (_now < _1sty) {
} else
if (_now >= _1sty && _now < _2ndy) {
} else
if (_now >= _2ndy) {
}
}
if (_t == _tw) {
if (_now < _1sty) {
} else
if (_now >= _1sty && _now < _2ndy) {
} else
if (_now >= _2ndy) {
}
}
if (_t == _tm) {
if (_now < _1sty) {
} else
if (_now >= _1sty && _now < _2ndy) {
} else
if (_now >= _2ndy) {
}
}
if (_t == _tm) {
if (_now < _1sty) {
} else
if (_now >= _1sty && _now < _2ndy) {
} else
if (_now >= _2ndy) {
}
}
if (_t == _tm) {
if (_now < _1sty) {
} else
if (_now >= _1sty && _now < _2ndy) {
} else
if (_now >= _2ndy) {
}
}
if (_t == _tm) {
if (_now < _1sty) {
} else
if (_now >= _1sty && _now < _2ndy) {
} else
if (_now >= _2ndy) {
}
}
if (_t == _ty) {
if (_now < _1sty) {
} else
if (_now >= _1sty && _now < _2ndy) {
} else
if (_now >= _2ndy) {
}
}
return _b;
if (_t == _ty) {
if (_now < _1sty) {
} else
if (_now >= _1sty && _now < _2ndy) {
} else
if (_now >= _2ndy) {
}
}
return _b;
if (_t == _ty) {
if (_now < _1sty) {
} else
if (_now >= _1sty && _now < _2ndy) {
} else
if (_now >= _2ndy) {
}
}
return _b;
if (_t == _ty) {
if (_now < _1sty) {
} else
if (_now >= _1sty && _now < _2ndy) {
} else
if (_now >= _2ndy) {
}
}
return _b;
}
| 2,369,422 |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
/**
* @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;
}
}
/**
* @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);
function name() external view returns (string memory);
function mint(address account, uint amount) external;
function burn(uint amount) external;
function governance() external view returns (address);
/**
* @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);
/** YFV, vUSD, vETH has minters **/
function minters(address account) external view 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);
}
contract Context {
constructor () internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
library Address {
function isContract(address account) internal view returns (bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly {codehash := extcodehash(account)}
return (codehash != 0x0 && codehash != accountHash);
}
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
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");
}
}
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 {
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));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
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");
}
}
}
interface IController {
function withdraw(address, uint256) external;
function balanceOf(address) external view returns (uint256);
function maxAcceptAmount(address) external view returns (uint256);
function doHardWork(address, uint256) external;
function yfvInsuranceFund() external view returns (address);
function performanceReward() external view returns (address);
}
interface IYFVReferral {
function setReferrer(address farmer, address referrer) external;
function getReferrer(address farmer) external view returns (address);
}
interface IFreeFromUpTo {
function freeFromUpTo(address from, uint256 value) external returns (uint256 freed);
}
contract YFVGovernanceVault {
using SafeMath for uint256;
using SafeERC20 for IERC20;
IFreeFromUpTo public constant chi = IFreeFromUpTo(0x0000000000004946c0e9F43F4Dee607b0eF1fA1c);
modifier discountCHI {
uint256 gasStart = gasleft();
_;
uint256 gasSpent = 21000 + gasStart - gasleft() + 16 * msg.data.length;
chi.freeFromUpTo(msg.sender, (gasSpent + 14154) / 41130);
}
IERC20 public yfv; // stake token
IERC20 public value; // reward token
IERC20 public vUSD; // reward token
IERC20 public vETH; // reward token
uint256 public fundCap = 9500; // use up to 95% of fund (to keep small withdrawals cheap)
uint256 public constant FUND_CAP_DENOMINATOR = 10000;
uint256 public earnLowerlimit;
address public governance;
address public controller;
address public rewardReferral;
struct Staker {
uint256 stake;
uint256 payout;
uint256 total_out;
}
mapping(address => Staker) public stakers; // stakerAddress -> staker's info
struct Global {
uint256 total_stake;
uint256 total_out;
uint256 earnings_per_share;
}
Global public global; // global data
uint256 constant internal magnitude = 10 ** 40;
string public getName;
uint256 public vETH_REWARD_FRACTION_RATE = 1000;
uint256 public constant DURATION = 7 days;
uint8 public constant NUMBER_EPOCHS = 36;
uint256 public constant REFERRAL_COMMISSION_PERCENT = 1;
uint256 public currentEpochReward = 0;
uint256 public totalAccumulatedReward = 0;
uint8 public currentEpoch = 0;
uint256 public starttime = 1598968800; // Tuesday, September 1, 2020 2:00:00 PM (GMT+0)
uint256 public periodFinish = 0;
uint256 public rewardRate = 0;
uint256 public valueRewardRateMultipler = 0;
bool public isOpened;
uint256 public lastUpdateTime;
uint256 public rewardPerTokenStored;
uint256 public constant DEFAULT_EPOCH_REWARD = 230000 * (10 ** 9); // 230,000 vUSD (and 230 vETH)
uint256 public constant TOTAL_REWARD = DEFAULT_EPOCH_REWARD * NUMBER_EPOCHS; // 8,740,000 vUSD (and 8,740 vETH)
uint256 public constant DEFAULT_VALUE_EPOCH_REWARD = 23000 * (10 ** 18); // 23,000 VALUE
uint256 public epochReward = DEFAULT_EPOCH_REWARD;
uint256 public valueEpochReward = DEFAULT_VALUE_EPOCH_REWARD;
uint256 public minStakingAmount = 0 ether;
uint256 public unstakingFrozenTime = 40 hours;
uint256 public minStakeTimeToClaimVaultReward = 24 hours;
// ** unlockWithdrawFee = 1.92%: stakers will need to pay 1.92% (sent to insurance fund)of amount they want to withdraw if the coin still frozen
uint256 public unlockWithdrawFee = 0; // per ten thousand (eg. 15 -> 0.15%)
address public yfvInsuranceFund = 0xb7b2Ea8A1198368f950834875047aA7294A2bDAa; // set to Governance Multisig at start
mapping(address => uint256) public userRewardPerTokenPaid;
mapping(address => uint256) public rewards;
mapping(address => uint256) public lastStakeTimes;
mapping(address => uint256) public accumulatedStakingPower; // will accumulate every time staker does getReward()
event RewardAdded(uint256 reward);
event YfvRewardAdded(uint256 reward);
event Burned(uint256 reward);
event Staked(address indexed user, uint256 amount, uint256 actualStakeAmount);
event Withdrawn(address indexed user, uint256 amount, uint256 actualWithdrawAmount);
event RewardPaid(address indexed user, uint256 reward);
event CommissionPaid(address indexed user, uint256 reward);
constructor (address _yfv, address _value, address _vUSD, address _vETH, uint256 _earnLowerlimit) public {
yfv = IERC20(_yfv);
value = IERC20(_value);
vUSD = IERC20(_vUSD);
vETH = IERC20(_vETH);
getName = string(abi.encodePacked("YFV:GovVault:v2"));
earnLowerlimit = _earnLowerlimit * 1e18;
governance = msg.sender;
}
function setGovernance(address _governance) public {
require(msg.sender == governance, "!governance");
governance = _governance;
}
function balance() public view returns (uint256) {
uint256 bal = yfv.balanceOf(address(this));
if (controller != address(0)) bal = bal.add(IController(controller).balanceOf(address(yfv)));
return bal;
}
function setFundCap(uint256 _fundCap) external {
require(msg.sender == governance, "!governance");
fundCap = _fundCap;
}
function setController(address _controller) public {
require(msg.sender == governance, "!governance");
controller = _controller;
}
function setRewardReferral(address _rewardReferral) external {
require(msg.sender == governance, "!governance");
rewardReferral = _rewardReferral;
}
function setIsOpened(bool _isOpened) external {
require(msg.sender == governance, "!governance");
isOpened = _isOpened;
}
function setEarnLowerlimit(uint256 _earnLowerlimit) public {
require(msg.sender == governance, "!governance");
earnLowerlimit = _earnLowerlimit;
}
function setYfvInsuranceFund(address _yfvInsuranceFund) public {
require(msg.sender == governance, "!governance");
yfvInsuranceFund = _yfvInsuranceFund;
}
function setEpochReward(uint256 _epochReward) public {
require(msg.sender == governance, "!governance");
require(_epochReward <= DEFAULT_EPOCH_REWARD * 10, "Insane big _epochReward!"); // At most 10x only
epochReward = _epochReward;
}
function setValueEpochReward(uint256 _valueEpochReward) public {
require(msg.sender == governance, "!governance");
valueEpochReward = _valueEpochReward;
}
function setMinStakingAmount(uint256 _minStakingAmount) public {
require(msg.sender == governance, "!governance");
minStakingAmount = _minStakingAmount;
}
function setUnstakingFrozenTime(uint256 _unstakingFrozenTime) public {
require(msg.sender == governance, "!governance");
unstakingFrozenTime = _unstakingFrozenTime;
}
function setUnlockWithdrawFee(uint256 _unlockWithdrawFee) public {
require(msg.sender == governance, "!governance");
require(_unlockWithdrawFee <= 1000, "Dont be too greedy"); // <= 10%
unlockWithdrawFee = _unlockWithdrawFee;
}
function setMinStakeTimeToClaimVaultReward(uint256 _minStakeTimeToClaimVaultReward) public {
require(msg.sender == governance, "!governance");
minStakeTimeToClaimVaultReward = _minStakeTimeToClaimVaultReward;
}
// To upgrade vUSD contract (v1 is still experimental, we may need vUSDv2 with rebase() function working soon - then governance will call this upgrade)
function upgradeVUSDContract(address _vUSDContract) public {
require(msg.sender == governance, "!governance");
vUSD = IERC20(_vUSDContract);
}
// To upgrade vETH contract (v1 is still experimental, we may need vETHv2 with rebase() function working soon - then governance will call this upgrade)
function upgradeVETHContract(address _vETHContract) public {
require(msg.sender == governance, "!governance");
vETH = IERC20(_vETHContract);
}
modifier updateReward(address account) {
rewardPerTokenStored = rewardPerToken();
lastUpdateTime = lastTimeRewardApplicable();
if (account != address(0)) {
rewards[account] = earned(account);
userRewardPerTokenPaid[account] = rewardPerTokenStored;
}
_;
}
function lastTimeRewardApplicable() public view returns (uint256) {
if (block.timestamp < periodFinish) return block.timestamp;
else return periodFinish;
}
function rewardPerToken() public view returns (uint256) {
if (global.total_stake == 0) {
return rewardPerTokenStored;
}
return
rewardPerTokenStored.add(
lastTimeRewardApplicable()
.sub(lastUpdateTime)
.mul(rewardRate)
.mul(1e18)
.div(global.total_stake)
);
}
// vUSD balance
function earned(address account) public view returns (uint256) {
uint256 calculatedEarned = stakers[account].stake
.mul(rewardPerToken().sub(userRewardPerTokenPaid[account]))
.div(1e18)
.add(rewards[account]);
uint256 poolBalance = vUSD.balanceOf(address(this));
// some rare case the reward can be slightly bigger than real number, we need to check against how much we have left in pool
if (calculatedEarned > poolBalance) return poolBalance;
return calculatedEarned;
}
function stakingPower(address account) public view returns (uint256) {
return accumulatedStakingPower[account].add(earned(account));
}
function earnedVETH(address account) public view returns (uint256) {
return earned(account).div(vETH_REWARD_FRACTION_RATE);
}
function earnedValue(address account) public view returns (uint256) {
return earned(account).mul(valueRewardRateMultipler);
}
// Custom logic in here for how much the vault allows to be borrowed
// Sets minimum required on-hand to keep small withdrawals cheap
function available() public view returns (uint256) {
return yfv.balanceOf(address(this)).mul(fundCap).div(FUND_CAP_DENOMINATOR);
}
function doHardWork() public discountCHI {
if (controller != address(0)) {
uint256 _amount = available();
uint256 _accepted = IController(controller).maxAcceptAmount(address(yfv));
if (_amount > _accepted) _amount = _accepted;
if (_amount > 0) {
yfv.safeTransfer(controller, _amount);
IController(controller).doHardWork(address(yfv), _amount);
}
}
}
function stake(uint256 amount, address referrer) public discountCHI updateReward(msg.sender) checkNextEpoch {
require(isOpened, "Pool is not opening to stake");
yfv.safeTransferFrom(msg.sender, address(this), amount);
stakers[msg.sender].stake = stakers[msg.sender].stake.add(amount);
require(stakers[msg.sender].stake > minStakingAmount, "Cannot stake below minStakingAmount");
if (global.earnings_per_share != 0) {
stakers[msg.sender].payout = stakers[msg.sender].payout.add(
global.earnings_per_share.mul(amount).sub(1).div(magnitude).add(1)
);
}
global.total_stake = global.total_stake.add(amount);
if (yfv.balanceOf(address(this)) > earnLowerlimit) {
doHardWork();
}
lastStakeTimes[msg.sender] = block.timestamp;
if (rewardReferral != address(0) && referrer != address(0)) {
IYFVReferral(rewardReferral).setReferrer(msg.sender, referrer);
}
}
function unfrozenStakeTime(address account) public view returns (uint256) {
return lastStakeTimes[account] + unstakingFrozenTime;
}
// No rebalance implementation for lower fees and faster swaps
function withdraw(uint256 amount) public discountCHI updateReward(msg.sender) checkNextEpoch {
require(amount > 0, "Cannot withdraw 0");
claim();
require(amount <= stakers[msg.sender].stake, "!balance");
uint256 actualWithdrawAmount = amount;
// Check balance
uint256 b = yfv.balanceOf(address(this));
if (b < actualWithdrawAmount) {
if (controller != address(0)) {
uint256 _withdraw = actualWithdrawAmount.sub(b);
IController(controller).withdraw(address(yfv), _withdraw);
uint256 _after = yfv.balanceOf(address(this));
uint256 _diff = _after.sub(b);
if (_diff < _withdraw) {
actualWithdrawAmount = b.add(_diff);
}
} else {
actualWithdrawAmount = b;
}
}
stakers[msg.sender].payout = stakers[msg.sender].payout.sub(
global.earnings_per_share.mul(amount).div(magnitude)
);
stakers[msg.sender].stake = stakers[msg.sender].stake.sub(amount);
global.total_stake = global.total_stake.sub(amount);
if (block.timestamp < unfrozenStakeTime(msg.sender)) {
// if coin is still frozen and governance does not allow stakers to unstake before timer ends
if (unlockWithdrawFee == 0) revert("Coin is still frozen");
// otherwise withdrawFee will be calculated based on the rate
uint256 withdrawFee = amount.mul(unlockWithdrawFee).div(10000);
uint256 r = amount.sub(withdrawFee);
if (actualWithdrawAmount > r) {
withdrawFee = actualWithdrawAmount.sub(r);
actualWithdrawAmount = r;
if (yfvInsuranceFund != address(0)) { // send fee to insurance
safeTokenTransfer(yfv, yfvInsuranceFund, withdrawFee);
emit RewardPaid(yfvInsuranceFund, withdrawFee);
} else { // or burn
yfv.burn(withdrawFee);
emit Burned(withdrawFee);
}
}
}
safeTokenTransfer(yfv, msg.sender, actualWithdrawAmount);
emit Withdrawn(msg.sender, amount, actualWithdrawAmount);
}
function make_profit(uint256 amount) public discountCHI {
require(amount > 0, "not 0");
value.safeTransferFrom(msg.sender, address(this), amount);
global.earnings_per_share = global.earnings_per_share.add(
amount.mul(magnitude).div(global.total_stake)
);
global.total_out = global.total_out.add(amount);
}
function cal_out(address user) public view returns (uint256) {
uint256 _cal = global.earnings_per_share.mul(stakers[user].stake).div(magnitude);
if (_cal < stakers[user].payout) {
return 0;
} else {
return _cal.sub(stakers[user].payout);
}
}
function cal_out_pending(uint256 _pendingBalance, address user) public view returns (uint256) {
uint256 _earnings_per_share = global.earnings_per_share.add(
_pendingBalance.mul(magnitude).div(global.total_stake)
);
uint256 _cal = _earnings_per_share.mul(stakers[user].stake).div(magnitude);
_cal = _cal.sub(cal_out(user));
if (_cal < stakers[user].payout) {
return 0;
} else {
return _cal.sub(stakers[user].payout);
}
}
function claim() public discountCHI {
uint256 out = cal_out(msg.sender);
stakers[msg.sender].payout = global.earnings_per_share.mul(stakers[msg.sender].stake).div(magnitude);
stakers[msg.sender].total_out = stakers[msg.sender].total_out.add(out);
if (out > 0) {
uint256 _stakeTime = now - lastStakeTimes[msg.sender];
if (controller != address(0) && _stakeTime < minStakeTimeToClaimVaultReward) { // deposit in less than requirement
uint256 actually_out = _stakeTime.mul(out).mul(1e18).div(minStakeTimeToClaimVaultReward).div(1e18);
uint256 to_team = out.sub(actually_out);
safeTokenTransfer(value, IController(controller).performanceReward(), to_team);
out = actually_out;
}
safeTokenTransfer(value, msg.sender, out);
}
}
function exit() external discountCHI {
withdraw(stakers[msg.sender].stake);
getReward();
}
function getReward() public discountCHI updateReward(msg.sender) checkNextEpoch {
uint256 reward = rewards[msg.sender];
if (reward > 0) {
accumulatedStakingPower[msg.sender] = accumulatedStakingPower[msg.sender].add(rewards[msg.sender]);
rewards[msg.sender] = 0;
safeTokenTransfer(vUSD, msg.sender, reward);
safeTokenTransfer(vETH, msg.sender, reward.div(vETH_REWARD_FRACTION_RATE));
emit RewardPaid(msg.sender, reward);
uint256 valueReward = reward.mul(valueRewardRateMultipler);
uint256 actualValuePaid = valueReward.mul(100 - REFERRAL_COMMISSION_PERCENT).div(100); // 99%
uint256 valueCommission = valueReward - actualValuePaid; // 1%
safeTokenTransfer(value, msg.sender, actualValuePaid);
address referrer = address(0);
if (rewardReferral != address(0)) {
referrer = IYFVReferral(rewardReferral).getReferrer(msg.sender);
}
if (referrer != address(0)) { // send commission to referrer
safeTokenTransfer(value, referrer, valueCommission);
} else {// or burn
safeTokenBurn(value, valueCommission);
emit Burned(valueCommission);
}
}
}
modifier checkNextEpoch() {
if (block.timestamp >= periodFinish) {
currentEpochReward = epochReward;
if (totalAccumulatedReward.add(currentEpochReward) > TOTAL_REWARD) {
currentEpochReward = TOTAL_REWARD.sub(totalAccumulatedReward); // limit total reward
}
if (currentEpochReward > 0) {
if (!vUSD.minters(address(this)) || !vETH.minters(address(this))) {
currentEpochReward = 0;
} else {
vUSD.mint(address(this), currentEpochReward);
vETH.mint(address(this), currentEpochReward.div(vETH_REWARD_FRACTION_RATE));
totalAccumulatedReward = totalAccumulatedReward.add(currentEpochReward);
}
currentEpoch++;
}
rewardRate = currentEpochReward.div(DURATION);
if (currentEpochReward > 0) {
value.mint(address(this), valueEpochReward);
valueRewardRateMultipler = valueEpochReward.div(currentEpochReward);
} else {
valueRewardRateMultipler = 0;
}
lastUpdateTime = block.timestamp;
periodFinish = block.timestamp.add(DURATION);
emit RewardAdded(currentEpochReward);
}
_;
}
function addValueReward(uint256 _amount) external discountCHI {
require(periodFinish > 0, "Pool has not started yet");
uint256 remaining = periodFinish.sub(block.timestamp);
require(remaining > 1 days, "Too little time to distribute. Wait for next epoch");
value.safeTransferFrom(msg.sender, address(this), _amount);
uint256 leftover = remaining.mul(rewardRate);
uint256 valueLeftover = leftover.mul(valueRewardRateMultipler);
valueRewardRateMultipler = valueLeftover.add(_amount).div(leftover);
}
// Safe token transfer function, just in case if rounding error causes pool to not have enough token.
function safeTokenTransfer(IERC20 _token, address _to, uint256 _amount) internal {
uint256 bal = _token.balanceOf(address(this));
if (_amount > bal) {
_token.safeTransfer(_to, bal);
} else {
_token.safeTransfer(_to, _amount);
}
}
// Safe token burn function, just in case if rounding error causes pool to not have enough token.
function safeTokenBurn(IERC20 _token, uint256 _amount) internal {
uint256 bal = _token.balanceOf(address(this));
if (_amount > bal) {
_token.burn(bal);
} else {
_token.burn(_amount);
}
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw() public discountCHI {
require(block.timestamp >= unfrozenStakeTime(msg.sender), "Wait until coin unfrozen");
uint256 amount = stakers[msg.sender].stake;
uint256 b = yfv.balanceOf(address(this));
if (b < amount) amount = b;
stakers[msg.sender].payout = stakers[msg.sender].payout.sub(
global.earnings_per_share.mul(amount).div(magnitude)
);
stakers[msg.sender].stake = stakers[msg.sender].stake.sub(amount);
global.total_stake = global.total_stake.sub(amount);
safeTokenTransfer(yfv, msg.sender, amount);
emit Withdrawn(msg.sender, amount, amount);
}
// This function allows governance to take unsupported tokens out of the contract, since this pool exists longer than the other pools.
// This is in an effort to make someone whole, should they seriously mess up.
// There is no guarantee governance will vote to return these.
// It also allows for removal of airdropped tokens.
function governanceRecoverUnsupported(IERC20 _token, uint256 amount, address to) external {
require(msg.sender == governance, "!governance");
// cant take staked asset
require(_token != yfv || global.total_stake.add(amount) <= yfv.balanceOf(address(this)), "cant withdraw more than stuck YFV");
// transfer to
_token.safeTransfer(to, amount);
}
}
|
No rebalance implementation for lower fees and faster swaps Check balance if coin is still frozen and governance does not allow stakers to unstake before timer ends otherwise withdrawFee will be calculated based on the rate
|
function withdraw(uint256 amount) public discountCHI updateReward(msg.sender) checkNextEpoch {
require(amount > 0, "Cannot withdraw 0");
claim();
require(amount <= stakers[msg.sender].stake, "!balance");
uint256 actualWithdrawAmount = amount;
uint256 b = yfv.balanceOf(address(this));
if (b < actualWithdrawAmount) {
if (controller != address(0)) {
uint256 _withdraw = actualWithdrawAmount.sub(b);
IController(controller).withdraw(address(yfv), _withdraw);
uint256 _after = yfv.balanceOf(address(this));
uint256 _diff = _after.sub(b);
if (_diff < _withdraw) {
actualWithdrawAmount = b.add(_diff);
}
actualWithdrawAmount = b;
}
}
stakers[msg.sender].payout = stakers[msg.sender].payout.sub(
global.earnings_per_share.mul(amount).div(magnitude)
);
stakers[msg.sender].stake = stakers[msg.sender].stake.sub(amount);
global.total_stake = global.total_stake.sub(amount);
if (block.timestamp < unfrozenStakeTime(msg.sender)) {
if (unlockWithdrawFee == 0) revert("Coin is still frozen");
uint256 withdrawFee = amount.mul(unlockWithdrawFee).div(10000);
uint256 r = amount.sub(withdrawFee);
if (actualWithdrawAmount > r) {
withdrawFee = actualWithdrawAmount.sub(r);
actualWithdrawAmount = r;
safeTokenTransfer(yfv, yfvInsuranceFund, withdrawFee);
emit RewardPaid(yfvInsuranceFund, withdrawFee);
yfv.burn(withdrawFee);
emit Burned(withdrawFee);
}
}
}
safeTokenTransfer(yfv, msg.sender, actualWithdrawAmount);
emit Withdrawn(msg.sender, amount, actualWithdrawAmount);
| 7,762,955 |
//Address: 0xa7ace3440fd2d6afa37d12f18e3a9f25c55d1e47
//Contract name: TreeLib
//Balance: 0 Ether
//Verification Date: 9/10/2017
//Transacion Count: 1
// CODE STARTS HERE
pragma solidity ^0.4.15;
library TreeLib {
using IntervalLib for IntervalLib.Interval;
using ListLib for ListLib.List;
// TODO: remove need for redefinition here
uint8 constant SEARCH_DONE = 0x00;
uint8 constant SEARCH_EARLIER = 0x01;
uint8 constant SEARCH_LATER = 0x10;
bool constant TRAVERSED_EARLIER = false;
bool constant TRAVERSED_LATER = true;
struct Tree {
// global table of intervals
mapping (uint => IntervalLib.Interval) intervals;
uint numIntervals;
// tree nodes
mapping (uint => Node) nodes;
uint numNodes;
// pointer to root of tree
uint rootNode;
}
struct Node {
uint earlier;
uint later;
ListLib.List intervals;
}
/*
* adding intervals
*/
function addInterval(Tree storage tree,
uint begin,
uint end,
bytes32 data)
internal
{
uint intervalID = _createInterval(tree, begin, end, data);
// if the tree is empty, create the root
if (tree.rootNode == 0) {
var nodeID = _createNode(tree);
tree.rootNode = nodeID;
tree.nodes[nodeID].intervals.add(begin, end, intervalID);
return;
}
/*
* depth-first search tree for place to add interval.
* for each step of the search:
* if the new interval contains the current node's center:
* add interval to current node
* stop search
*
* if the new interval < center:
* recurse "before"
* if the new interval > center:
* recurse "after"
*/
uint curID = tree.rootNode;
bool found = false;
do {
Node storage curNode = tree.nodes[curID];
// track direction of recursion each step, to update correct pointer
// upon needing to add a new node
bool recurseDirection;
if (end <= curNode.intervals.center) {
// traverse before
curID = curNode.earlier;
recurseDirection = TRAVERSED_EARLIER;
} else if (begin > curNode.intervals.center) {
// traverse after
curID = curNode.later;
recurseDirection = TRAVERSED_LATER;
} else {
// found!
found = true;
break;
}
// if traversing yields null pointer for child node, must create
if (curID == 0) {
curID = _createNode(tree);
// update appropriate pointer
if (recurseDirection == TRAVERSED_EARLIER) {
curNode.earlier = curID;
} else {
curNode.later = curID;
}
// creating a new node means we've found the place to put the interval
found = true;
}
} while (!found);
tree.nodes[curID].intervals.add(begin, end, intervalID);
}
/*
* retrieval
*/
function getInterval(Tree storage tree, uint intervalID)
constant
internal
returns (uint begin, uint end, bytes32 data)
{
require(intervalID > 0 && intervalID <= tree.numIntervals);
var interval = tree.intervals[intervalID];
return (interval.begin, interval.end, interval.data);
}
/*
* searching
*/
function search(Tree storage tree, uint point)
constant
internal
returns (uint[] memory intervalIDs)
{
// can't search empty trees
require(tree.rootNode != 0x0);
// HACK repeatedly mallocs new arrays of matching interval IDs
intervalIDs = new uint[](0);
uint[] memory tempIDs;
uint[] memory matchingIDs;
uint i; // for list copying loops
/*
* search traversal
*
* starting at root node
*/
uint curID = tree.rootNode;
uint8 searchNext;
do {
Node storage curNode = tree.nodes[curID];
/*
* search current node
*/
(matchingIDs, searchNext) = curNode.intervals.matching(point);
/*
* add matching intervals to results array
*
* allocate temp array and copy in both prior and new matches
*/
if (matchingIDs.length > 0) {
tempIDs = new uint[](intervalIDs.length + matchingIDs.length);
for (i = 0; i < intervalIDs.length; i++) {
tempIDs[i] = intervalIDs[i];
}
for (i = 0; i < matchingIDs.length; i++) {
tempIDs[i + intervalIDs.length] = matchingIDs[i];
}
intervalIDs = tempIDs;
}
/*
* recurse according to node search results
*/
if (searchNext == SEARCH_EARLIER) {
curID = curNode.earlier;
} else if (searchNext == SEARCH_LATER) { // SEARCH_LATER
curID = curNode.later;
}
} while (searchNext != SEARCH_DONE && curID != 0x0);
}
/*
* data create helpers helpers
*/
function _createInterval(Tree storage tree, uint begin, uint end, bytes32 data)
internal
returns (uint intervalID)
{
intervalID = ++tree.numIntervals;
tree.intervals[intervalID] = IntervalLib.Interval({
begin: begin,
end: end,
data: data
});
}
function _createNode(Tree storage tree) returns (uint nodeID) {
nodeID = ++tree.numNodes;
tree.nodes[nodeID] = Node({
earlier: 0,
later: 0,
intervals: ListLib.createNew(nodeID)
});
}
}
library IntervalLib {
struct Interval {
uint begin;
uint end;
bytes32 data;
}
}
library GroveLib {
/*
* Indexes for ordered data
*
* Address: 0x7c1eb207c07e7ab13cf245585bd03d0fa478d034
*/
struct Index {
bytes32 root;
mapping (bytes32 => Node) nodes;
}
struct Node {
bytes32 id;
int value;
bytes32 parent;
bytes32 left;
bytes32 right;
uint height;
}
function max(uint a, uint b) internal returns (uint) {
if (a >= b) {
return a;
}
return b;
}
/*
* Node getters
*/
/// @dev Retrieve the unique identifier for the node.
/// @param index The index that the node is part of.
/// @param id The id for the node to be looked up.
function getNodeId(Index storage index, bytes32 id) constant returns (bytes32) {
return index.nodes[id].id;
}
/// @dev Retrieve the value for the node.
/// @param index The index that the node is part of.
/// @param id The id for the node to be looked up.
function getNodeValue(Index storage index, bytes32 id) constant returns (int) {
return index.nodes[id].value;
}
/// @dev Retrieve the height of the node.
/// @param index The index that the node is part of.
/// @param id The id for the node to be looked up.
function getNodeHeight(Index storage index, bytes32 id) constant returns (uint) {
return index.nodes[id].height;
}
/// @dev Retrieve the parent id of the node.
/// @param index The index that the node is part of.
/// @param id The id for the node to be looked up.
function getNodeParent(Index storage index, bytes32 id) constant returns (bytes32) {
return index.nodes[id].parent;
}
/// @dev Retrieve the left child id of the node.
/// @param index The index that the node is part of.
/// @param id The id for the node to be looked up.
function getNodeLeftChild(Index storage index, bytes32 id) constant returns (bytes32) {
return index.nodes[id].left;
}
/// @dev Retrieve the right child id of the node.
/// @param index The index that the node is part of.
/// @param id The id for the node to be looked up.
function getNodeRightChild(Index storage index, bytes32 id) constant returns (bytes32) {
return index.nodes[id].right;
}
/// @dev Retrieve the node id of the next node in the tree.
/// @param index The index that the node is part of.
/// @param id The id for the node to be looked up.
function getPreviousNode(Index storage index, bytes32 id) constant returns (bytes32) {
Node storage currentNode = index.nodes[id];
if (currentNode.id == 0x0) {
// Unknown node, just return 0x0;
return 0x0;
}
Node memory child;
if (currentNode.left != 0x0) {
// Trace left to latest child in left tree.
child = index.nodes[currentNode.left];
while (child.right != 0) {
child = index.nodes[child.right];
}
return child.id;
}
if (currentNode.parent != 0x0) {
// Now we trace back up through parent relationships, looking
// for a link where the child is the right child of it's
// parent.
Node storage parent = index.nodes[currentNode.parent];
child = currentNode;
while (true) {
if (parent.right == child.id) {
return parent.id;
}
if (parent.parent == 0x0) {
break;
}
child = parent;
parent = index.nodes[parent.parent];
}
}
// This is the first node, and has no previous node.
return 0x0;
}
/// @dev Retrieve the node id of the previous node in the tree.
/// @param index The index that the node is part of.
/// @param id The id for the node to be looked up.
function getNextNode(Index storage index, bytes32 id) constant returns (bytes32) {
Node storage currentNode = index.nodes[id];
if (currentNode.id == 0x0) {
// Unknown node, just return 0x0;
return 0x0;
}
Node memory child;
if (currentNode.right != 0x0) {
// Trace right to earliest child in right tree.
child = index.nodes[currentNode.right];
while (child.left != 0) {
child = index.nodes[child.left];
}
return child.id;
}
if (currentNode.parent != 0x0) {
// if the node is the left child of it's parent, then the
// parent is the next one.
Node storage parent = index.nodes[currentNode.parent];
child = currentNode;
while (true) {
if (parent.left == child.id) {
return parent.id;
}
if (parent.parent == 0x0) {
break;
}
child = parent;
parent = index.nodes[parent.parent];
}
// Now we need to trace all the way up checking to see if any parent is the
}
// This is the final node.
return 0x0;
}
/// @dev Updates or Inserts the id into the index at its appropriate location based on the value provided.
/// @param index The index that the node is part of.
/// @param id The unique identifier of the data element the index node will represent.
/// @param value The value of the data element that represents it's total ordering with respect to other elementes.
function insert(Index storage index, bytes32 id, int value) public {
if (index.nodes[id].id == id) {
// A node with this id already exists. If the value is
// the same, then just return early, otherwise, remove it
// and reinsert it.
if (index.nodes[id].value == value) {
return;
}
remove(index, id);
}
bytes32 previousNodeId = 0x0;
if (index.root == 0x0) {
index.root = id;
}
Node storage currentNode = index.nodes[index.root];
// Do insertion
while (true) {
if (currentNode.id == 0x0) {
// This is a new unpopulated node.
currentNode.id = id;
currentNode.parent = previousNodeId;
currentNode.value = value;
break;
}
// Set the previous node id.
previousNodeId = currentNode.id;
// The new node belongs in the right subtree
if (value >= currentNode.value) {
if (currentNode.right == 0x0) {
currentNode.right = id;
}
currentNode = index.nodes[currentNode.right];
continue;
}
// The new node belongs in the left subtree.
if (currentNode.left == 0x0) {
currentNode.left = id;
}
currentNode = index.nodes[currentNode.left];
}
// Rebalance the tree
_rebalanceTree(index, currentNode.id);
}
/// @dev Checks whether a node for the given unique identifier exists within the given index.
/// @param index The index that should be searched
/// @param id The unique identifier of the data element to check for.
function exists(Index storage index, bytes32 id) constant returns (bool) {
return (index.nodes[id].height > 0);
}
/// @dev Remove the node for the given unique identifier from the index.
/// @param index The index that should be removed
/// @param id The unique identifier of the data element to remove.
function remove(Index storage index, bytes32 id) public {
bytes32 rebalanceOrigin;
Node storage nodeToDelete = index.nodes[id];
if (nodeToDelete.id != id) {
// The id does not exist in the tree.
return;
}
if (nodeToDelete.left != 0x0 || nodeToDelete.right != 0x0) {
// This node is not a leaf node and thus must replace itself in
// it's tree by either the previous or next node.
if (nodeToDelete.left != 0x0) {
// This node is guaranteed to not have a right child.
Node storage replacementNode = index.nodes[getPreviousNode(index, nodeToDelete.id)];
}
else {
// This node is guaranteed to not have a left child.
replacementNode = index.nodes[getNextNode(index, nodeToDelete.id)];
}
// The replacementNode is guaranteed to have a parent.
Node storage parent = index.nodes[replacementNode.parent];
// Keep note of the location that our tree rebalancing should
// start at.
rebalanceOrigin = replacementNode.id;
// Join the parent of the replacement node with any subtree of
// the replacement node. We can guarantee that the replacement
// node has at most one subtree because of how getNextNode and
// getPreviousNode are used.
if (parent.left == replacementNode.id) {
parent.left = replacementNode.right;
if (replacementNode.right != 0x0) {
Node storage child = index.nodes[replacementNode.right];
child.parent = parent.id;
}
}
if (parent.right == replacementNode.id) {
parent.right = replacementNode.left;
if (replacementNode.left != 0x0) {
child = index.nodes[replacementNode.left];
child.parent = parent.id;
}
}
// Now we replace the nodeToDelete with the replacementNode.
// This includes parent/child relationships for all of the
// parent, the left child, and the right child.
replacementNode.parent = nodeToDelete.parent;
if (nodeToDelete.parent != 0x0) {
parent = index.nodes[nodeToDelete.parent];
if (parent.left == nodeToDelete.id) {
parent.left = replacementNode.id;
}
if (parent.right == nodeToDelete.id) {
parent.right = replacementNode.id;
}
}
else {
// If the node we are deleting is the root node update the
// index root node pointer.
index.root = replacementNode.id;
}
replacementNode.left = nodeToDelete.left;
if (nodeToDelete.left != 0x0) {
child = index.nodes[nodeToDelete.left];
child.parent = replacementNode.id;
}
replacementNode.right = nodeToDelete.right;
if (nodeToDelete.right != 0x0) {
child = index.nodes[nodeToDelete.right];
child.parent = replacementNode.id;
}
}
else if (nodeToDelete.parent != 0x0) {
// The node being deleted is a leaf node so we only erase it's
// parent linkage.
parent = index.nodes[nodeToDelete.parent];
if (parent.left == nodeToDelete.id) {
parent.left = 0x0;
}
if (parent.right == nodeToDelete.id) {
parent.right = 0x0;
}
// keep note of where the rebalancing should begin.
rebalanceOrigin = parent.id;
}
else {
// This is both a leaf node and the root node, so we need to
// unset the root node pointer.
index.root = 0x0;
}
// Now we zero out all of the fields on the nodeToDelete.
nodeToDelete.id = 0x0;
nodeToDelete.value = 0;
nodeToDelete.parent = 0x0;
nodeToDelete.left = 0x0;
nodeToDelete.right = 0x0;
nodeToDelete.height = 0;
// Walk back up the tree rebalancing
if (rebalanceOrigin != 0x0) {
_rebalanceTree(index, rebalanceOrigin);
}
}
bytes2 constant GT = ">";
bytes2 constant LT = "<";
bytes2 constant GTE = ">=";
bytes2 constant LTE = "<=";
bytes2 constant EQ = "==";
function _compare(int left, bytes2 operator, int right) internal returns (bool) {
require(
operator == GT || operator == LT || operator == GTE ||
operator == LTE || operator == EQ
);
if (operator == GT) {
return (left > right);
}
if (operator == LT) {
return (left < right);
}
if (operator == GTE) {
return (left >= right);
}
if (operator == LTE) {
return (left <= right);
}
if (operator == EQ) {
return (left == right);
}
}
function _getMaximum(Index storage index, bytes32 id) internal returns (int) {
Node storage currentNode = index.nodes[id];
while (true) {
if (currentNode.right == 0x0) {
return currentNode.value;
}
currentNode = index.nodes[currentNode.right];
}
}
function _getMinimum(Index storage index, bytes32 id) internal returns (int) {
Node storage currentNode = index.nodes[id];
while (true) {
if (currentNode.left == 0x0) {
return currentNode.value;
}
currentNode = index.nodes[currentNode.left];
}
}
/** @dev Query the index for the edge-most node that satisfies the
* given query. For >, >=, and ==, this will be the left-most node
* that satisfies the comparison. For < and <= this will be the
* right-most node that satisfies the comparison.
*/
/// @param index The index that should be queried
/** @param operator One of '>', '>=', '<', '<=', '==' to specify what
* type of comparison operator should be used.
*/
function query(Index storage index, bytes2 operator, int value) public returns (bytes32) {
bytes32 rootNodeId = index.root;
if (rootNodeId == 0x0) {
// Empty tree.
return 0x0;
}
Node storage currentNode = index.nodes[rootNodeId];
while (true) {
if (_compare(currentNode.value, operator, value)) {
// We have found a match but it might not be the
// *correct* match.
if ((operator == LT) || (operator == LTE)) {
// Need to keep traversing right until this is no
// longer true.
if (currentNode.right == 0x0) {
return currentNode.id;
}
if (_compare(_getMinimum(index, currentNode.right), operator, value)) {
// There are still nodes to the right that
// match.
currentNode = index.nodes[currentNode.right];
continue;
}
return currentNode.id;
}
if ((operator == GT) || (operator == GTE) || (operator == EQ)) {
// Need to keep traversing left until this is no
// longer true.
if (currentNode.left == 0x0) {
return currentNode.id;
}
if (_compare(_getMaximum(index, currentNode.left), operator, value)) {
currentNode = index.nodes[currentNode.left];
continue;
}
return currentNode.id;
}
}
if ((operator == LT) || (operator == LTE)) {
if (currentNode.left == 0x0) {
// There are no nodes that are less than the value
// so return null.
return 0x0;
}
currentNode = index.nodes[currentNode.left];
continue;
}
if ((operator == GT) || (operator == GTE)) {
if (currentNode.right == 0x0) {
// There are no nodes that are greater than the value
// so return null.
return 0x0;
}
currentNode = index.nodes[currentNode.right];
continue;
}
if (operator == EQ) {
if (currentNode.value < value) {
if (currentNode.right == 0x0) {
return 0x0;
}
currentNode = index.nodes[currentNode.right];
continue;
}
if (currentNode.value > value) {
if (currentNode.left == 0x0) {
return 0x0;
}
currentNode = index.nodes[currentNode.left];
continue;
}
}
}
}
function _rebalanceTree(Index storage index, bytes32 id) internal {
// Trace back up rebalancing the tree and updating heights as
// needed..
Node storage currentNode = index.nodes[id];
while (true) {
int balanceFactor = _getBalanceFactor(index, currentNode.id);
if (balanceFactor == 2) {
// Right rotation (tree is heavy on the left)
if (_getBalanceFactor(index, currentNode.left) == -1) {
// The subtree is leaning right so it need to be
// rotated left before the current node is rotated
// right.
_rotateLeft(index, currentNode.left);
}
_rotateRight(index, currentNode.id);
}
if (balanceFactor == -2) {
// Left rotation (tree is heavy on the right)
if (_getBalanceFactor(index, currentNode.right) == 1) {
// The subtree is leaning left so it need to be
// rotated right before the current node is rotated
// left.
_rotateRight(index, currentNode.right);
}
_rotateLeft(index, currentNode.id);
}
if ((-1 <= balanceFactor) && (balanceFactor <= 1)) {
_updateNodeHeight(index, currentNode.id);
}
if (currentNode.parent == 0x0) {
// Reached the root which may be new due to tree
// rotation, so set it as the root and then break.
break;
}
currentNode = index.nodes[currentNode.parent];
}
}
function _getBalanceFactor(Index storage index, bytes32 id) internal returns (int) {
Node storage node = index.nodes[id];
return int(index.nodes[node.left].height) - int(index.nodes[node.right].height);
}
function _updateNodeHeight(Index storage index, bytes32 id) internal {
Node storage node = index.nodes[id];
node.height = max(index.nodes[node.left].height, index.nodes[node.right].height) + 1;
}
function _rotateLeft(Index storage index, bytes32 id) internal {
Node storage originalRoot = index.nodes[id];
// Cannot rotate left if there is no right originalRoot to rotate into
// place.
assert(originalRoot.right != 0x0);
// The right child is the new root, so it gets the original
// `originalRoot.parent` as it's parent.
Node storage newRoot = index.nodes[originalRoot.right];
newRoot.parent = originalRoot.parent;
// The original root needs to have it's right child nulled out.
originalRoot.right = 0x0;
if (originalRoot.parent != 0x0) {
// If there is a parent node, it needs to now point downward at
// the newRoot which is rotating into the place where `node` was.
Node storage parent = index.nodes[originalRoot.parent];
// figure out if we're a left or right child and have the
// parent point to the new node.
if (parent.left == originalRoot.id) {
parent.left = newRoot.id;
}
if (parent.right == originalRoot.id) {
parent.right = newRoot.id;
}
}
if (newRoot.left != 0) {
// If the new root had a left child, that moves to be the
// new right child of the original root node
Node storage leftChild = index.nodes[newRoot.left];
originalRoot.right = leftChild.id;
leftChild.parent = originalRoot.id;
}
// Update the newRoot's left node to point at the original node.
originalRoot.parent = newRoot.id;
newRoot.left = originalRoot.id;
if (newRoot.parent == 0x0) {
index.root = newRoot.id;
}
// TODO: are both of these updates necessary?
_updateNodeHeight(index, originalRoot.id);
_updateNodeHeight(index, newRoot.id);
}
function _rotateRight(Index storage index, bytes32 id) internal {
Node storage originalRoot = index.nodes[id];
// Cannot rotate right if there is no left node to rotate into
// place.
assert(originalRoot.left != 0x0);
// The left child is taking the place of node, so we update it's
// parent to be the original parent of the node.
Node storage newRoot = index.nodes[originalRoot.left];
newRoot.parent = originalRoot.parent;
// Null out the originalRoot.left
originalRoot.left = 0x0;
if (originalRoot.parent != 0x0) {
// If the node has a parent, update the correct child to point
// at the newRoot now.
Node storage parent = index.nodes[originalRoot.parent];
if (parent.left == originalRoot.id) {
parent.left = newRoot.id;
}
if (parent.right == originalRoot.id) {
parent.right = newRoot.id;
}
}
if (newRoot.right != 0x0) {
Node storage rightChild = index.nodes[newRoot.right];
originalRoot.left = newRoot.right;
rightChild.parent = originalRoot.id;
}
// Update the new root's right node to point to the original node.
originalRoot.parent = newRoot.id;
newRoot.right = originalRoot.id;
if (newRoot.parent == 0x0) {
index.root = newRoot.id;
}
// Recompute heights.
_updateNodeHeight(index, originalRoot.id);
_updateNodeHeight(index, newRoot.id);
}
}
library ListLib {
uint8 constant SEARCH_DONE = 0x00;
uint8 constant SEARCH_EARLIER = 0x01;
uint8 constant SEARCH_LATER = 0x10;
using GroveLib for GroveLib.Index;
using IntervalLib for IntervalLib.Interval;
struct List {
uint length;
uint center;
// maps item ID to items
mapping (uint => IntervalLib.Interval) items;
GroveLib.Index beginIndex;
GroveLib.Index endIndex;
bytes32 lowestBegin;
bytes32 highestEnd;
}
function createNew()
internal
returns (List)
{
return createNew(block.number);
}
function createNew(uint id)
internal
returns (List)
{
return List({
length: 0,
center: 0xDEADBEEF,
lowestBegin: 0x0,
highestEnd: 0x0,
beginIndex: GroveLib.Index(sha3(this, bytes32(id * 2))),
endIndex: GroveLib.Index(sha3(this, bytes32(id * 2 + 1)))
});
}
function add(List storage list, uint begin, uint end, uint intervalID) internal {
var _intervalID = bytes32(intervalID);
var _begin = _getBeginIndexKey(begin);
var _end = _getEndIndexKey(end);
list.beginIndex.insert(_intervalID, _begin);
list.endIndex.insert(_intervalID, _end);
list.length++;
if (list.length == 1) {
list.lowestBegin = list.beginIndex.root;
list.highestEnd = list.endIndex.root;
list.center = begin + (end - begin) / 2;
return;
}
var newLowest = list.beginIndex.getPreviousNode(list.lowestBegin);
if (newLowest != 0x0) {
list.lowestBegin = newLowest;
}
var newHighest = list.endIndex.getNextNode(list.highestEnd);
if (newHighest != 0x0) {
list.highestEnd = newHighest;
}
}
/*
* @dev Searches interval list for:
* - matching intervals
* - information on how search should proceed
* @param node The node to search
* @param point The point to search for
*/
function matching(List storage list, uint point)
constant
internal
returns (uint[] memory intervalIDs, uint8 searchNext)
{
uint[] memory _intervalIDs = new uint[](list.length);
uint num = 0;
bytes32 cur;
if (point == list.center) {
/*
* case: point exactly matches the list's center
*
* collect (all) matching intervals (every interval in list, by def)
*/
cur = list.lowestBegin;
while (cur != 0x0) {
_intervalIDs[num] = uint(list.beginIndex.getNodeId(cur));
num++;
cur = _next(list, cur);
}
/*
* search is done:
* no other nodes in tree have intervals containing point
*/
searchNext = SEARCH_DONE;
} else if (point < list.center) {
/*
* case: point is earlier than center.
*
*
* collect matching intervals.
*
* shortcut:
*
* starting with lowest beginning interval, search sorted begin list
* until begin is later than point
*
* point
* :
* : center
* : |
* (0) *----:-----|----------o
* (1) *-:-----|---o
* (-) x *---|------o
* (-) *--|--o
* (-) *-|----o
*
*
* this works because intervals contained in an interval list are
* guaranteed tocontain `center`
*/
cur = list.lowestBegin;
while (cur != 0x0) {
uint begin = _begin(list, cur);
if (begin > point) {
break;
}
_intervalIDs[num] = uint(list.beginIndex.getNodeId(cur));
num++;
cur = _next(list, cur);
}
/*
* search should proceed to earlier
*/
searchNext = SEARCH_EARLIER;
} else if (point > list.center) {
/*
* case: point is later than center.
*
*
* collect matching intervals.
*
* shortcut:
*
* starting with highest ending interval, search sorted end list
* until end is earlier than or equal to point
*
* point
* :
* center :
* | :
* *----------|----:-----o (0)
* *---|----:-o (1)
* *-|----o (not matching, done.)
* *-------|---o (-)
* *--|--o (-)
*
*
* this works because intervals contained in an interval list are
* guaranteed to contain `center`
*/
cur = list.highestEnd;
while (cur != 0x0) {
uint end = _end(list, cur);
if (end <= point) {
break;
}
_intervalIDs[num] = uint(list.endIndex.getNodeId(cur));
num++;
cur = _previous(list, cur);
}
/*
* search proceeds to later intervals
*/
searchNext = SEARCH_LATER;
}
/*
* return correctly-sized array of intervalIDs
*/
if (num == _intervalIDs.length) {
intervalIDs = _intervalIDs;
} else {
intervalIDs = new uint[](num);
for (uint i = 0; i < num; i++) {
intervalIDs[i] = _intervalIDs[i];
}
}
}
/*
* Grove linked list traversal
*/
function _begin(List storage list, bytes32 indexNode) constant internal returns (uint) {
return _getBegin(list.beginIndex.getNodeValue(indexNode));
}
function _end(List storage list, bytes32 indexNode) constant internal returns (uint) {
return _getEnd(list.endIndex.getNodeValue(indexNode));
}
function _next(List storage list, bytes32 cur) constant internal returns (bytes32) {
return list.beginIndex.getNextNode(cur);
}
function _previous(List storage list, bytes32 cur) constant internal returns (bytes32) {
return list.endIndex.getPreviousNode(cur);
}
/*
* uint / int conversions for Grove nodeIDs
*/
function _getBeginIndexKey(uint begin) constant internal returns (int) {
// convert to signed int in order-preserving manner
return int(begin - 0x8000000000000000000000000000000000000000000000000000000000000000);
}
function _getEndIndexKey(uint end) constant internal returns (int) {
// convert to signed int in order-preserving manner
return int(end - 0x8000000000000000000000000000000000000000000000000000000000000000);
}
function _getBegin(int beginIndexKey) constant internal returns (uint) {
// convert to unsigned int in order-preserving manner
return uint(beginIndexKey) + 0x8000000000000000000000000000000000000000000000000000000000000000;
}
function _getEnd(int endIndexKey) constant internal returns (uint) {
// convert to unsigned int in order-preserving manner
return uint(endIndexKey) + 0x8000000000000000000000000000000000000000000000000000000000000000;
}
}
|
data create helpers helpers/
|
function _createInterval(Tree storage tree, uint begin, uint end, bytes32 data)
internal
returns (uint intervalID)
{
intervalID = ++tree.numIntervals;
tree.intervals[intervalID] = IntervalLib.Interval({
begin: begin,
end: end,
data: data
});
}
| 5,546,595 |
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);
}
/**
* @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;
}
}
library SafeMath16 {
function mul(uint16 a, uint16 b) internal pure returns (uint16) {
if (a == 0) {
return 0;
}
uint16 c = a * b;
assert(c / a == b);
return c;
}
function div(uint16 a, uint16 b) internal pure returns (uint16) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint16 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn’t hold
return c;
}
function sub(uint16 a, uint16 b) internal pure returns (uint16) {
assert(b <= a);
return a - b;
}
function add(uint16 a, uint16 b) internal pure returns (uint16) {
uint16 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @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 SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
function safeTransfer(
ERC20Basic _token,
address _to,
uint256 _value
)
internal
{
require(_token.transfer(_to, _value));
}
function safeTransferFrom(
ERC20 _token,
address _from,
address _to,
uint256 _value
)
internal
{
require(_token.transferFrom(_from, _to, _value));
}
function safeApprove(
ERC20 _token,
address _spender,
uint256 _value
)
internal
{
require(_token.approve(_spender, _value));
}
}
/*****************************************************************
* Core contract of the Million Dollar Decentralized Application *
*****************************************************************/
/**
* @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;
}
}
/**
* @title Contracts that should not own Ether
* @author Remco Bloemen <remco@2π.com>
* @dev This tries to block incoming ether to prevent accidental loss of Ether. Should Ether end up
* in the contract, it will allow the owner to reclaim this Ether.
* @notice Ether can still be sent to this contract by:
* calling functions labeled `payable`
* `selfdestruct(contract_address)`
* mining directly to the contract address
*/
contract HasNoEther is Ownable {
/**
* @dev Constructor that rejects incoming Ether
* The `payable` flag is added so we can access `msg.value` without compiler warning. If we
* leave out payable, then Solidity will allow inheriting contracts to implement a payable
* constructor. By doing it this way we prevent a payable constructor from working. Alternatively
* we could use assembly to access msg.value.
*/
constructor() public payable {
require(msg.value == 0);
}
/**
* @dev Disallows direct send by setting a default function without the `payable` flag.
*/
function() external {
}
/**
* @dev Transfer all Ether held by the contract to the owner.
*/
function reclaimEther() external onlyOwner {
owner.transfer(address(this).balance);
}
}
/**
* @title Contracts that should be able to recover tokens
* @author SylTi
* @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner.
* This will prevent any accidental loss of tokens.
*/
contract CanReclaimToken is Ownable {
using SafeERC20 for ERC20Basic;
/**
* @dev Reclaim all ERC20Basic compatible tokens
* @param _token ERC20Basic The address of the token contract
*/
function reclaimToken(ERC20Basic _token) external onlyOwner {
uint256 balance = _token.balanceOf(this);
_token.safeTransfer(owner, balance);
}
}
/**
* @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];
}
}
/**
* @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;
}
}
/**
* @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)
{
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;
}
}
/**
* @title MDAPPToken
* @dev Token for the Million Dollar Decentralized Application (MDAPP).
* Once a holder uses it to claim pixels the appropriate tokens are burned (1 Token <=> 10x10 pixel).
* If one releases his pixels new tokens are generated and credited to ones balance. Therefore, supply will
* vary between 0 and 10,000 tokens.
* Tokens are transferable once minting has finished.
* @dev Owned by MDAPP.sol
*/
contract MDAPPToken is MintableToken {
using SafeMath16 for uint16;
using SafeMath for uint256;
string public constant name = "MillionDollarDapp";
string public constant symbol = "MDAPP";
uint8 public constant decimals = 0;
mapping (address => uint16) locked;
bool public forceTransferEnable = false;
/*********************************************************
* *
* Events *
* *
*********************************************************/
// Emitted when owner force-allows transfers of tokens.
event AllowTransfer();
/*********************************************************
* *
* Modifiers *
* *
*********************************************************/
modifier hasLocked(address _account, uint16 _value) {
require(_value <= locked[_account], "Not enough locked tokens available.");
_;
}
modifier hasUnlocked(address _account, uint16 _value) {
require(balanceOf(_account).sub(uint256(locked[_account])) >= _value, "Not enough unlocked tokens available.");
_;
}
/**
* @dev Checks whether it can transfer or otherwise throws.
*/
modifier canTransfer(address _sender, uint256 _value) {
require(_value <= transferableTokensOf(_sender), "Not enough unlocked tokens available.");
_;
}
/*********************************************************
* *
* Limited Transfer Logic *
* Taken from openzeppelin 1.3.0 *
* *
*********************************************************/
function lockToken(address _account, uint16 _value) onlyOwner hasUnlocked(_account, _value) public {
locked[_account] = locked[_account].add(_value);
}
function unlockToken(address _account, uint16 _value) onlyOwner hasLocked(_account, _value) public {
locked[_account] = locked[_account].sub(_value);
}
/**
* @dev Checks modifier and allows transfer if tokens are not locked.
* @param _to The address that will receive the tokens.
* @param _value The amount of tokens to be transferred.
*/
function transfer(address _to, uint256 _value) canTransfer(msg.sender, _value) public returns (bool) {
return super.transfer(_to, _value);
}
/**
* @dev Checks modifier and allows transfer if tokens are not locked.
* @param _from The address that will send the tokens.
* @param _to The address that will receive the tokens.
* @param _value The amount of tokens to be transferred.
*/
function transferFrom(address _from, address _to, uint256 _value) canTransfer(_from, _value) public returns (bool) {
return super.transferFrom(_from, _to, _value);
}
/**
* @dev Allow the holder to transfer his tokens only if every token in
* existence has already been distributed / minting is finished.
* Tokens which are locked for a claimed space cannot be transferred.
*/
function transferableTokensOf(address _holder) public view returns (uint16) {
if (!mintingFinished && !forceTransferEnable) return 0;
return uint16(balanceOf(_holder)).sub(locked[_holder]);
}
/**
* @dev Get the number of pixel-locked tokens.
*/
function lockedTokensOf(address _holder) public view returns (uint16) {
return locked[_holder];
}
/**
* @dev Get the number of unlocked tokens usable for claiming pixels.
*/
function unlockedTokensOf(address _holder) public view returns (uint256) {
return balanceOf(_holder).sub(uint256(locked[_holder]));
}
// Allow transfer of tokens even if minting is not yet finished.
function allowTransfer() onlyOwner public {
require(forceTransferEnable == false, 'Transfer already force-allowed.');
forceTransferEnable = true;
emit AllowTransfer();
}
}
/**
* @title MDAPP
*/
contract MDAPP is Ownable, HasNoEther, CanReclaimToken {
using SafeMath for uint256;
using SafeMath16 for uint16;
// The tokens contract.
MDAPPToken public token;
// The sales contracts address. Only it is allowed to to call the public mint function.
address public sale;
// When are presale participants allowed to place ads?
uint256 public presaleAdStart;
// When are all token owners allowed to place ads?
uint256 public allAdStart;
// Quantity of tokens bought during presale.
mapping (address => uint16) presales;
// Indicates whether a 10x10px block is claimed or not.
bool[80][125] grid;
// Struct that represents an ad.
struct Ad {
address owner;
Rect rect;
}
// Struct describing an rectangle area.
struct Rect {
uint16 x;
uint16 y;
uint16 width;
uint16 height;
}
// Don't store ad details on blockchain. Use events as storage as they are significantly cheaper.
// ads are stored in an array, the id of an ad is its index in this array.
Ad[] ads;
// The following holds a list of currently active ads (without holes between the indexes)
uint256[] adIds;
// Holds the mapping from adID to its index in the above adIds array. If an ad gets released, we know which index to
// delete and being filled with the last element instead.
mapping (uint256 => uint256) adIdToIndex;
/*********************************************************
* *
* Events *
* *
*********************************************************/
/*
* Event for claiming pixel blocks.
* @param id ID of the new ad
* @param owner Who owns the used tokens
* @param x Upper left corner x coordinate
* @param y Upper left corner y coordinate
* @param width Width of the claimed area
* @param height Height of the claimed area
*/
event Claim(uint256 indexed id, address indexed owner, uint16 x, uint16 y, uint16 width, uint16 height);
/*
* Event for releasing pixel blocks.
* @param id ID the fading ad
* @param owner Who owns the claimed blocks
*/
event Release(uint256 indexed id, address indexed owner);
/*
* Event for editing an ad.
* @param id ID of the ad
* @param owner Who owns the ad
* @param link A link
* @param title Title of the ad
* @param text Description of the ad
* @param NSFW Whether the ad is safe for work
* @param digest IPFS hash digest
* @param hashFunction IPFS hash function
* @param size IPFS length of digest
* @param storageEngine e.g. ipfs or swrm (swarm)
*/
event EditAd(uint256 indexed id, address indexed owner, string link, string title, string text, string contact, bool NSFW, bytes32 indexed digest, bytes2 hashFunction, uint8 size, bytes4 storageEngine);
event ForceNSFW(uint256 indexed id);
/*********************************************************
* *
* Modifiers *
* *
*********************************************************/
modifier coordsValid(uint16 _x, uint16 _y, uint16 _width, uint16 _height) {
require((_x + _width - 1) < 125, "Invalid coordinates.");
require((_y + _height - 1) < 80, "Invalid coordinates.");
_;
}
modifier onlyAdOwner(uint256 _id) {
require(ads[_id].owner == msg.sender, "Access denied.");
_;
}
modifier enoughTokens(uint16 _width, uint16 _height) {
require(uint16(token.unlockedTokensOf(msg.sender)) >= _width.mul(_height), "Not enough unlocked tokens available.");
_;
}
modifier claimAllowed(uint16 _width, uint16 _height) {
require(_width > 0 &&_width <= 125 && _height > 0 && _height <= 80, "Invalid dimensions.");
require(now >= presaleAdStart, "Claim period not yet started.");
if (now < allAdStart) {
// Sender needs enough presale tokens to claim at this point.
uint16 tokens = _width.mul(_height);
require(presales[msg.sender] >= tokens, "Not enough unlocked presale tokens available.");
presales[msg.sender] = presales[msg.sender].sub(tokens);
}
_;
}
modifier onlySale() {
require(msg.sender == sale);
_;
}
modifier adExists(uint256 _id) {
uint256 index = adIdToIndex[_id];
require(adIds[index] == _id, "Ad does not exist.");
_;
}
/*********************************************************
* *
* Initialization *
* *
*********************************************************/
constructor(uint256 _presaleAdStart, uint256 _allAdStart, address _token) public {
require(_presaleAdStart >= now);
require(_allAdStart > _presaleAdStart);
presaleAdStart = _presaleAdStart;
allAdStart = _allAdStart;
token = MDAPPToken(_token);
}
function setMDAPPSale(address _mdappSale) onlyOwner external {
require(sale == address(0));
sale = _mdappSale;
}
/*********************************************************
* *
* Logic *
* *
*********************************************************/
// Proxy function to pass minting from sale contract to token contract.
function mint(address _beneficiary, uint256 _tokenAmount, bool isPresale) onlySale external {
if (isPresale) {
presales[_beneficiary] = presales[_beneficiary].add(uint16(_tokenAmount));
}
token.mint(_beneficiary, _tokenAmount);
}
// Proxy function to pass finishMinting() from sale contract to token contract.
function finishMinting() onlySale external {
token.finishMinting();
}
// Public function proxy to forward single parameters as a struct.
function claim(uint16 _x, uint16 _y, uint16 _width, uint16 _height)
claimAllowed(_width, _height)
coordsValid(_x, _y, _width, _height)
external returns (uint)
{
Rect memory rect = Rect(_x, _y, _width, _height);
return claimShortParams(rect);
}
// Claims pixels and requires to have the sender enough unlocked tokens.
// Has a modifier to take some of the "stack burden" from the proxy function.
function claimShortParams(Rect _rect)
enoughTokens(_rect.width, _rect.height)
internal returns (uint id)
{
token.lockToken(msg.sender, _rect.width.mul(_rect.height));
// Check affected pixelblocks.
for (uint16 i = 0; i < _rect.width; i++) {
for (uint16 j = 0; j < _rect.height; j++) {
uint16 x = _rect.x.add(i);
uint16 y = _rect.y.add(j);
if (grid[x][y]) {
revert("Already claimed.");
}
// Mark block as claimed.
grid[x][y] = true;
}
}
// Create placeholder ad.
id = createPlaceholderAd(_rect);
emit Claim(id, msg.sender, _rect.x, _rect.y, _rect.width, _rect.height);
return id;
}
// Delete an ad, unclaim pixelblocks and unlock tokens.
function release(uint256 _id) adExists(_id) onlyAdOwner(_id) external {
uint16 tokens = ads[_id].rect.width.mul(ads[_id].rect.height);
// Mark blocks as unclaimed.
for (uint16 i = 0; i < ads[_id].rect.width; i++) {
for (uint16 j = 0; j < ads[_id].rect.height; j++) {
uint16 x = ads[_id].rect.x.add(i);
uint16 y = ads[_id].rect.y.add(j);
// Mark block as unclaimed.
grid[x][y] = false;
}
}
// Delete ad
delete ads[_id];
// Reorganize index array and map
uint256 key = adIdToIndex[_id];
// Fill gap with last element of adIds
adIds[key] = adIds[adIds.length - 1];
// Update adIdToIndex
adIdToIndex[adIds[key]] = key;
// Decrease length of adIds array by 1
adIds.length--;
// Unlock tokens
if (now < allAdStart) {
// The ad must have locked presale tokens.
presales[msg.sender] = presales[msg.sender].add(tokens);
}
token.unlockToken(msg.sender, tokens);
emit Release(_id, msg.sender);
}
// The image must be an URL either of bzz, ipfs or http(s).
function editAd(uint _id, string _link, string _title, string _text, string _contact, bool _NSFW, bytes32 _digest, bytes2 _hashFunction, uint8 _size, bytes4 _storageEnginge) adExists(_id) onlyAdOwner(_id) public {
emit EditAd(_id, msg.sender, _link, _title, _text, _contact, _NSFW, _digest, _hashFunction, _size, _storageEnginge);
}
// Allows contract owner to set the NSFW flag for a given ad.
function forceNSFW(uint256 _id) onlyOwner adExists(_id) external {
emit ForceNSFW(_id);
}
// Helper function for claim() to avoid a deep stack.
function createPlaceholderAd(Rect _rect) internal returns (uint id) {
Ad memory ad = Ad(msg.sender, _rect);
id = ads.push(ad) - 1;
uint256 key = adIds.push(id) - 1;
adIdToIndex[id] = key;
return id;
}
// Returns remaining balance of tokens purchased during presale period qualifying for earlier claims.
function presaleBalanceOf(address _holder) public view returns (uint16) {
return presales[_holder];
}
// Returns all currently active adIds.
function getAdIds() external view returns (uint256[]) {
return adIds;
}
/*********************************************************
* *
* Other *
* *
*********************************************************/
// Allow transfer of tokens even if minting is not yet finished.
function allowTransfer() onlyOwner external {
token.allowTransfer();
}
}
|
Public function proxy to forward single parameters as a struct.
|
function claim(uint16 _x, uint16 _y, uint16 _width, uint16 _height)
claimAllowed(_width, _height)
coordsValid(_x, _y, _width, _height)
external returns (uint)
{
Rect memory rect = Rect(_x, _y, _width, _height);
return claimShortParams(rect);
}
| 129,047 |
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.7.6;
pragma abicoder v2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "./../lib/uniswap/UniswapV2Library.sol";
import "./../lib/uniswap/UniswapV2OracleLibrary.sol";
import "./../lib/uniswap/FixedPoint.sol";
import "./../lib/math/MathUtils.sol";
import "./../external-interfaces/compound-finance/ICToken.sol";
import "./../external-interfaces/compound-finance/IComptroller.sol";
import "./../external-interfaces/compound-finance/IUniswapAnchoredOracle.sol";
import "./../external-interfaces/uniswap/IUniswapV2Router.sol";
import "./CompoundProvider.sol";
import "./../IController.sol";
import "./ICompoundCumulator.sol";
import "./../oracle/IYieldOracle.sol";
import "./../oracle/IYieldOraclelizable.sol";
contract CompoundController is IController, ICompoundCumulator, IYieldOraclelizable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
address public constant UNISWAP_FACTORY = 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f;
address public constant UNISWAP_ROUTER_V2 = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
uint256 public constant MAX_UINT256 = uint256(-1);
uint256 public constant DOUBLE_SCALE = 1e36;
uint256 public constant BLOCKS_PER_DAY = 5760; // 4 * 60 * 24 (assuming 4 blocks per minute)
uint256 public harvestedLast;
// last time we cumulated
uint256 public prevCumulationTime;
// exchnageRateStored last time we cumulated
uint256 public prevExchnageRateCurrent;
// cumulative supply rate += ((new underlying) / underlying)
uint256 public cumulativeSupplyRate;
// cumulative COMP distribution rate += ((new underlying) / underlying)
uint256 public cumulativeDistributionRate;
// compound.finance comptroller.compSupplyState right after the previous deposit/withdraw
IComptroller.CompMarketState public prevCompSupplyState;
uint256 public underlyingDecimals;
// uniswap path for COMP to underlying
address[] public uniswapPath;
// uniswap pairs for COMP to underlying
address[] public uniswapPairs;
// uniswap cumulative prices needed for COMP to underlying
uint256[] public uniswapPriceCumulatives;
// keys for uniswap cumulativePrice{0 | 1}
uint8[] public uniswapPriceKeys;
event Harvest(address indexed caller, uint256 compRewardTotal, uint256 compRewardSold, uint256 underlyingPoolShare, uint256 underlyingReward, uint256 harvestCost);
modifier onlyPool {
require(
msg.sender == pool,
"CC: only pool"
);
_;
}
constructor(
address pool_,
address smartYield_,
address bondModel_,
address[] memory uniswapPath_
)
IController()
{
pool = pool_;
smartYield = smartYield_;
underlyingDecimals = ERC20(ICToken(CompoundProvider(pool).cToken()).underlying()).decimals();
setBondModel(bondModel_);
setUniswapPath(uniswapPath_);
updateAllowances();
}
function updateAllowances()
public
{
ICToken cToken = ICToken(CompoundProvider(pool).cToken());
IComptroller comptroller = IComptroller(cToken.comptroller());
IERC20 rewardToken = IERC20(comptroller.getCompAddress());
IERC20 uToken = IERC20(CompoundProvider(pool).uToken());
uint256 routerRewardAllowance = rewardToken.allowance(address(this), uniswapRouter());
rewardToken.safeIncreaseAllowance(uniswapRouter(), MAX_UINT256.sub(routerRewardAllowance));
uint256 poolUnderlyingAllowance = uToken.allowance(address(this), address(pool));
uToken.safeIncreaseAllowance(address(pool), MAX_UINT256.sub(poolUnderlyingAllowance));
}
// should start with rewardCToken and with uToken, and have intermediary hops if needed
// path[0] = address(rewardCToken);
// path[1] = address(wethToken);
// path[2] = address(uToken);
function setUniswapPath(address[] memory newUniswapPath_)
public virtual
onlyDao
{
require(
2 <= newUniswapPath_.length,
"CC: setUniswapPath length"
);
uniswapPath = newUniswapPath_;
address[] memory newUniswapPairs = new address[](newUniswapPath_.length - 1);
uint8[] memory newUniswapPriceKeys = new uint8[](newUniswapPath_.length - 1);
for (uint256 f = 0; f < newUniswapPath_.length - 1; f++) {
newUniswapPairs[f] = UniswapV2Library.pairFor(UNISWAP_FACTORY, newUniswapPath_[f], newUniswapPath_[f + 1]);
(address token0, ) = UniswapV2Library.sortTokens(newUniswapPath_[f], newUniswapPath_[f + 1]);
newUniswapPriceKeys[f] = token0 == newUniswapPath_[f] ? 0 : 1;
}
uniswapPairs = newUniswapPairs;
uniswapPriceKeys = newUniswapPriceKeys;
uniswapPriceCumulatives = uniswapPriceCumulativesNow();
}
function uniswapRouter()
public view virtual returns(address)
{
// mockable
return UNISWAP_ROUTER_V2;
}
// claims and sells COMP on uniswap, returns total received comp and caller reward
function harvest(uint256 maxCompAmount_)
public
returns (uint256 compGot, uint256 underlyingHarvestReward)
{
require(
harvestedLast < block.timestamp,
"PPC: harvest later"
);
ICToken cToken = ICToken(CompoundProvider(pool).cToken());
IERC20 uToken = IERC20(CompoundProvider(pool).uToken());
IComptroller comptroller = IComptroller(cToken.comptroller());
IERC20 rewardToken = IERC20(comptroller.getCompAddress());
address caller = msg.sender;
// claim pool comp
address[] memory holders = new address[](1);
holders[0] = pool;
address[] memory markets = new address[](1);
markets[0] = address(cToken);
comptroller.claimComp(holders, markets, false, true);
// transfer all comp from pool to self
rewardToken.safeTransferFrom(pool, address(this), rewardToken.balanceOf(pool));
uint256 compRewardTotal = rewardToken.balanceOf(address(this)); // COMP
// only sell upmost maxCompAmount_, if maxCompAmount_ sell all
maxCompAmount_ = (maxCompAmount_ == 0) ? compRewardTotal : maxCompAmount_;
uint256 compRewardSold = MathUtils.min(maxCompAmount_, compRewardTotal);
require(
compRewardSold > 0,
"PPC: harvested nothing"
);
// pool share is (comp to underlying) - (harvest cost percent)
uint256 poolShare = MathUtils.fractionOf(
quoteSpotCompToUnderlying(compRewardSold),
EXP_SCALE.sub(HARVEST_COST)
);
// make sure we get at least the poolShare
IUniswapV2Router(uniswapRouter()).swapExactTokensForTokens(
compRewardSold,
poolShare,
uniswapPath,
address(this),
block.timestamp
);
uint256 underlyingGot = uToken.balanceOf(address(this));
require(
underlyingGot >= poolShare,
"PPC: harvest poolShare"
);
// deposit pool reward share with liquidity provider
CompoundProvider(pool)._takeUnderlying(address(this), poolShare);
CompoundProvider(pool)._depositProvider(poolShare, 0);
// pay caller
uint256 callerReward = uToken.balanceOf(address(this));
uToken.safeTransfer(caller, callerReward);
harvestedLast = block.timestamp;
emit Harvest(caller, compRewardTotal, compRewardSold, poolShare, callerReward, HARVEST_COST);
return (compRewardTotal, callerReward);
}
function _beforeCTokenBalanceChange()
external override
onlyPool
{ }
function _afterCTokenBalanceChange(uint256 prevCTokenBalance_)
external override
onlyPool
{
// at this point compound.finance state is updated since the pool did a deposit or withdrawl just before, so no need to ping
updateCumulativesInternal(prevCTokenBalance_, false);
IYieldOracle(oracle).update();
}
function providerRatePerDay()
public override virtual
returns (uint256)
{
return MathUtils.min(
MathUtils.min(BOND_MAX_RATE_PER_DAY, spotDailyRate()),
IYieldOracle(oracle).consult(1 days)
);
}
function cumulatives()
external override
returns (uint256)
{
uint256 timeElapsed = block.timestamp - prevCumulationTime;
// only cumulate once per block
if (0 == timeElapsed) {
return cumulativeSupplyRate.add(cumulativeDistributionRate);
}
uint256 cTokenBalance = CompoundProvider(pool).cTokenBalance();
updateCumulativesInternal(cTokenBalance, true);
return cumulativeSupplyRate.add(cumulativeDistributionRate);
}
function updateCumulativesInternal(uint256 prevCTokenBalance_, bool pingCompound_)
private
{
uint256 timeElapsed = block.timestamp - prevCumulationTime;
// only cumulate once per block
if (0 == timeElapsed) {
return;
}
ICToken cToken = ICToken(CompoundProvider(pool).cToken());
IComptroller comptroller = IComptroller(cToken.comptroller());
uint256[] memory currentUniswapPriceCumulatives = uniswapPriceCumulativesNow();
if (pingCompound_) {
// echangeRateStored will be up to date below
cToken.accrueInterest();
// compSupplyState will be up to date below
comptroller.mintAllowed(address(cToken), address(this), 0);
}
uint256 exchangeRateStoredNow = cToken.exchangeRateStored();
(uint224 nowSupplyStateIndex, uint32 blk) = comptroller.compSupplyState(address(cToken));
if (prevExchnageRateCurrent > 0) {
// cumulate a new supplyRate delta: cumulativeSupplyRate += (cToken.exchangeRateCurrent() - prevExchnageRateCurrent) / prevExchnageRateCurrent
// cumulativeSupplyRate eventually overflows, but that's ok due to the way it's used in the oracle
cumulativeSupplyRate += exchangeRateStoredNow.sub(prevExchnageRateCurrent).mul(EXP_SCALE).div(prevExchnageRateCurrent);
if (prevCTokenBalance_ > 0) {
uint256 expectedComp = expectedDistributeSupplierComp(prevCTokenBalance_, nowSupplyStateIndex, prevCompSupplyState.index);
uint256 expectedCompInUnderlying = quoteCompToUnderlying(
expectedComp,
timeElapsed,
uniswapPriceCumulatives,
currentUniswapPriceCumulatives
);
uint256 poolShare = MathUtils.fractionOf(expectedCompInUnderlying, EXP_SCALE.sub(HARVEST_COST));
// cumulate a new distributionRate delta: cumulativeDistributionRate += (expectedDistributeSupplierComp in underlying - harvest cost) / prevUnderlyingBalance
// cumulativeDistributionRate eventually overflows, but that's ok due to the way it's used in the oracle
cumulativeDistributionRate += poolShare.mul(EXP_SCALE).div(cTokensToUnderlying(prevCTokenBalance_, prevExchnageRateCurrent));
}
}
prevCumulationTime = block.timestamp;
// uniswap cumulatives only change once per block
uniswapPriceCumulatives = currentUniswapPriceCumulatives;
// compSupplyState changes only once per block
prevCompSupplyState = IComptroller.CompMarketState(nowSupplyStateIndex, blk);
// exchangeRateStored can increase multiple times per block
prevExchnageRateCurrent = exchangeRateStoredNow;
}
// computes how much COMP tokens compound.finance will have given us after a mint/redeem/redeemUnderlying
// source: https://github.com/compound-finance/compound-protocol/blob/master/contracts/Comptroller.sol#L1145
function expectedDistributeSupplierComp(
uint256 cTokenBalance_, uint224 nowSupplyStateIndex_, uint224 prevSupplyStateIndex_
) public pure returns (uint256) {
uint256 supplyIndex = uint256(nowSupplyStateIndex_);
uint256 supplierIndex = uint256(prevSupplyStateIndex_);
uint256 deltaIndex = (supplyIndex).sub(supplierIndex); // a - b
return (cTokenBalance_).mul(deltaIndex).div(DOUBLE_SCALE); // a * b / doubleScale => uint
}
function cTokensToUnderlying(
uint256 cTokens_, uint256 exchangeRate_
) public pure returns (uint256) {
return cTokens_.mul(exchangeRate_).div(EXP_SCALE);
}
function uniswapPriceCumulativeNow(
address pair_, uint8 priceKey_
) public view returns (uint256) {
(uint256 price0, uint256 price1, ) = UniswapV2OracleLibrary.currentCumulativePrices(pair_);
return 0 == priceKey_ ? price0 : price1;
}
function uniswapPriceCumulativesNow()
public view virtual returns (uint256[] memory)
{
uint256[] memory newUniswapPriceCumulatives = new uint256[](uniswapPairs.length);
for (uint256 f = 0; f < uniswapPairs.length; f++) {
newUniswapPriceCumulatives[f] = uniswapPriceCumulativeNow(uniswapPairs[f], uniswapPriceKeys[f]);
}
return newUniswapPriceCumulatives;
}
function quoteCompToUnderlying(
uint256 compIn_, uint256 timeElapsed_, uint256[] memory prevUniswapPriceCumulatives_, uint256[] memory nowUniswapPriceCumulatives_
) public pure returns (uint256) {
uint256 amountIn = compIn_;
for (uint256 f = 0; f < prevUniswapPriceCumulatives_.length; f++) {
amountIn = uniswapAmountOut(prevUniswapPriceCumulatives_[f], nowUniswapPriceCumulatives_[f], timeElapsed_, amountIn);
}
return amountIn;
}
function quoteSpotCompToUnderlying(
uint256 compIn_
) public view virtual returns (uint256) {
ICToken cToken = ICToken(CompoundProvider(pool).cToken());
IUniswapAnchoredOracle compOracle = IUniswapAnchoredOracle(IComptroller(cToken.comptroller()).oracle());
uint256 underlyingOut = compIn_.mul(compOracle.price("COMP")).mul(10**12).div(compOracle.getUnderlyingPrice(address(cToken)));
return underlyingOut;
}
function uniswapAmountOut(
uint256 prevPriceCumulative_, uint256 nowPriceCumulative_, uint256 timeElapsed_, uint256 amountIn_
) public pure returns (uint256) {
// per: https://github.com/Uniswap/uniswap-v2-periphery/blob/master/contracts/examples/ExampleSlidingWindowOracle.sol#L93
FixedPoint.uq112x112 memory priceAverage = FixedPoint.uq112x112(
uint224((nowPriceCumulative_ - prevPriceCumulative_) / timeElapsed_)
);
return FixedPoint.decode144(FixedPoint.mul(priceAverage, amountIn_));
}
// compound spot supply rate per day
function spotDailySupplyRateProvider()
public view returns (uint256)
{
// supplyRatePerBlock() * BLOCKS_PER_DAY
return ICToken(CompoundProvider(pool).cToken()).supplyRatePerBlock().mul(BLOCKS_PER_DAY);
}
// compound spot distribution rate per day
function spotDailyDistributionRateProvider()
public view returns (uint256)
{
ICToken cToken = ICToken(CompoundProvider(pool).cToken());
IComptroller comptroller = IComptroller(cToken.comptroller());
IUniswapAnchoredOracle compOracle = IUniswapAnchoredOracle(comptroller.oracle());
// compSpeeds(cToken) * price("COMP") * BLOCKS_PER_DAY
uint256 compDollarsPerDay = comptroller.compSpeeds(address(cToken)).mul(compOracle.price("COMP")).mul(BLOCKS_PER_DAY).mul(10**12);
// (totalBorrows() + getCash()) * getUnderlyingPrice(cToken)
uint256 totalSuppliedDollars = cToken.totalBorrows().add(cToken.getCash()).mul(compOracle.getUnderlyingPrice(address(cToken)));
// (compDollarsPerDay / totalSuppliedDollars)
return compDollarsPerDay.mul(EXP_SCALE).div(totalSuppliedDollars);
}
// smart yield spot daily rate includes: spot supply + spot distribution
function spotDailyRate()
public view returns (uint256)
{
uint256 expectedSpotDailyDistributionRate = MathUtils.fractionOf(spotDailyDistributionRateProvider(), EXP_SCALE.sub(HARVEST_COST));
// spotDailySupplyRateProvider() + (spotDailyDistributionRateProvider() - fraction lost to harvest)
return spotDailySupplyRateProvider().add(expectedSpotDailyDistributionRate);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../utils/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal virtual {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
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");
}
}
}
pragma solidity >=0.5.0;
import '@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol';
import "@openzeppelin/contracts/math/SafeMath.sol";
library UniswapV2Library {
using SafeMath for uint;
// returns sorted token addresses, used to handle return values from pairs sorted in this order
function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {
require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES');
(token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS');
}
// calculates the CREATE2 address for a pair without making any external calls
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = sortTokens(tokenA, tokenB);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
// fetches and sorts the reserves for a pair
function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) {
(address token0,) = sortTokens(tokenA, tokenB);
(uint reserve0, uint reserve1,) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves();
(reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
}
// given some amount of an asset and pair reserves, returns an equivalent amount of the other asset
function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) {
require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT');
require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
amountB = amountA.mul(reserveB) / reserveA;
}
// given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) {
require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
uint amountInWithFee = amountIn.mul(997);
uint numerator = amountInWithFee.mul(reserveOut);
uint denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
// given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) {
require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
uint numerator = reserveIn.mul(amountOut).mul(1000);
uint denominator = reserveOut.sub(amountOut).mul(997);
amountIn = (numerator / denominator).add(1);
}
// performs chained getAmountOut calculations on any number of pairs
function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'UniswapV2Library: INVALID_PATH');
amounts = new uint[](path.length);
amounts[0] = amountIn;
for (uint i; i < path.length - 1; i++) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]);
amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut);
}
}
// performs chained getAmountIn calculations on any number of pairs
function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'UniswapV2Library: INVALID_PATH');
amounts = new uint[](path.length);
amounts[amounts.length - 1] = amountOut;
for (uint i = path.length - 1; i > 0; i--) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]);
amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut);
}
}
}
pragma solidity >=0.5.0;
import '@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol';
import './FixedPoint.sol';
// library with helper methods for oracles that are concerned with computing average prices
library UniswapV2OracleLibrary {
using FixedPoint for *;
// helper function that returns the current block timestamp within the range of uint32, i.e. [0, 2**32 - 1]
function currentBlockTimestamp() internal view returns (uint32) {
return uint32(block.timestamp % 2 ** 32);
}
// produces the cumulative price using counterfactuals to save gas and avoid a call to sync.
function currentCumulativePrices(
address pair
) internal view returns (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) {
blockTimestamp = currentBlockTimestamp();
price0Cumulative = IUniswapV2Pair(pair).price0CumulativeLast();
price1Cumulative = IUniswapV2Pair(pair).price1CumulativeLast();
// if time has elapsed since the last update on the pair, mock the accumulated price values
(uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = IUniswapV2Pair(pair).getReserves();
if (blockTimestampLast != blockTimestamp) {
// subtraction overflow is desired
uint32 timeElapsed = blockTimestamp - blockTimestampLast;
// addition overflow is desired
// counterfactual
price0Cumulative += uint(FixedPoint.fraction(reserve1, reserve0)._x) * timeElapsed;
// counterfactual
price1Cumulative += uint(FixedPoint.fraction(reserve0, reserve1)._x) * timeElapsed;
}
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity >=0.4.0;
import './FullMath.sol';
import './Babylonian.sol';
import './BitMath.sol';
// a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format))
library FixedPoint {
// range: [0, 2**112 - 1]
// resolution: 1 / 2**112
struct uq112x112 {
uint224 _x;
}
// range: [0, 2**144 - 1]
// resolution: 1 / 2**112
struct uq144x112 {
uint256 _x;
}
uint8 public constant RESOLUTION = 112;
uint256 public constant Q112 = 0x10000000000000000000000000000; // 2**112
uint256 private constant Q224 = 0x100000000000000000000000000000000000000000000000000000000; // 2**224
uint256 private constant LOWER_MASK = 0xffffffffffffffffffffffffffff; // decimal of UQ*x112 (lower 112 bits)
// encode a uint112 as a UQ112x112
function encode(uint112 x) internal pure returns (uq112x112 memory) {
return uq112x112(uint224(x) << RESOLUTION);
}
// encodes a uint144 as a UQ144x112
function encode144(uint144 x) internal pure returns (uq144x112 memory) {
return uq144x112(uint256(x) << RESOLUTION);
}
// decode a UQ112x112 into a uint112 by truncating after the radix point
function decode(uq112x112 memory self) internal pure returns (uint112) {
return uint112(self._x >> RESOLUTION);
}
// decode a UQ144x112 into a uint144 by truncating after the radix point
function decode144(uq144x112 memory self) internal pure returns (uint144) {
return uint144(self._x >> RESOLUTION);
}
// multiply a UQ112x112 by a uint, returning a UQ144x112
// reverts on overflow
function mul(uq112x112 memory self, uint256 y) internal pure returns (uq144x112 memory) {
uint256 z = 0;
require(y == 0 || (z = self._x * y) / y == self._x, 'FixedPoint::mul: overflow');
return uq144x112(z);
}
// multiply a UQ112x112 by an int and decode, returning an int
// reverts on overflow
function muli(uq112x112 memory self, int256 y) internal pure returns (int256) {
uint256 z = FullMath.mulDiv(self._x, uint256(y < 0 ? -y : y), Q112);
require(z < 2**255, 'FixedPoint::muli: overflow');
return y < 0 ? -int256(z) : int256(z);
}
// multiply a UQ112x112 by a UQ112x112, returning a UQ112x112
// lossy
function muluq(uq112x112 memory self, uq112x112 memory other) internal pure returns (uq112x112 memory) {
if (self._x == 0 || other._x == 0) {
return uq112x112(0);
}
uint112 upper_self = uint112(self._x >> RESOLUTION); // * 2^0
uint112 lower_self = uint112(self._x & LOWER_MASK); // * 2^-112
uint112 upper_other = uint112(other._x >> RESOLUTION); // * 2^0
uint112 lower_other = uint112(other._x & LOWER_MASK); // * 2^-112
// partial products
uint224 upper = uint224(upper_self) * upper_other; // * 2^0
uint224 lower = uint224(lower_self) * lower_other; // * 2^-224
uint224 uppers_lowero = uint224(upper_self) * lower_other; // * 2^-112
uint224 uppero_lowers = uint224(upper_other) * lower_self; // * 2^-112
// so the bit shift does not overflow
require(upper <= uint112(-1), 'FixedPoint::muluq: upper overflow');
// this cannot exceed 256 bits, all values are 224 bits
uint256 sum = uint256(upper << RESOLUTION) + uppers_lowero + uppero_lowers + (lower >> RESOLUTION);
// so the cast does not overflow
require(sum <= uint224(-1), 'FixedPoint::muluq: sum overflow');
return uq112x112(uint224(sum));
}
// divide a UQ112x112 by a UQ112x112, returning a UQ112x112
function divuq(uq112x112 memory self, uq112x112 memory other) internal pure returns (uq112x112 memory) {
require(other._x > 0, 'FixedPoint::divuq: division by zero');
if (self._x == other._x) {
return uq112x112(uint224(Q112));
}
if (self._x <= uint144(-1)) {
uint256 value = (uint256(self._x) << RESOLUTION) / other._x;
require(value <= uint224(-1), 'FixedPoint::divuq: overflow');
return uq112x112(uint224(value));
}
uint256 result = FullMath.mulDiv(Q112, self._x, other._x);
require(result <= uint224(-1), 'FixedPoint::divuq: overflow');
return uq112x112(uint224(result));
}
// returns a UQ112x112 which represents the ratio of the numerator to the denominator
// can be lossy
function fraction(uint256 numerator, uint256 denominator) internal pure returns (uq112x112 memory) {
require(denominator > 0, 'FixedPoint::fraction: division by zero');
if (numerator == 0) return FixedPoint.uq112x112(0);
if (numerator <= uint144(-1)) {
uint256 result = (numerator << RESOLUTION) / denominator;
require(result <= uint224(-1), 'FixedPoint::fraction: overflow');
return uq112x112(uint224(result));
} else {
uint256 result = FullMath.mulDiv(numerator, Q112, denominator);
require(result <= uint224(-1), 'FixedPoint::fraction: overflow');
return uq112x112(uint224(result));
}
}
// take the reciprocal of a UQ112x112
// reverts on overflow
// lossy
function reciprocal(uq112x112 memory self) internal pure returns (uq112x112 memory) {
require(self._x != 0, 'FixedPoint::reciprocal: reciprocal of zero');
require(self._x != 1, 'FixedPoint::reciprocal: overflow');
return uq112x112(uint224(Q224 / self._x));
}
// square root of a UQ112x112
// lossy between 0/1 and 40 bits
function sqrt(uq112x112 memory self) internal pure returns (uq112x112 memory) {
if (self._x <= uint144(-1)) {
return uq112x112(uint224(Babylonian.sqrt(uint256(self._x) << 112)));
}
uint8 safeShiftBits = 255 - BitMath.mostSignificantBit(self._x);
safeShiftBits -= safeShiftBits % 2;
return uq112x112(uint224(Babylonian.sqrt(uint256(self._x) << safeShiftBits) << ((112 - safeShiftBits) / 2)));
}
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.7.6;
import "@openzeppelin/contracts/math/SafeMath.sol";
library MathUtils {
using SafeMath for uint256;
uint256 public constant EXP_SCALE = 1e18;
function min(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = x < y ? x : y;
}
function max(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = x > y ? x : y;
}
function compound(
// in wei
uint256 principal,
// rate is * EXP_SCALE
uint256 ratePerPeriod,
uint16 periods
) internal pure returns (uint256) {
if (0 == ratePerPeriod) {
return principal;
}
while (periods > 0) {
// principal += principal * ratePerPeriod / EXP_SCALE;
principal = principal.add(principal.mul(ratePerPeriod).div(EXP_SCALE));
periods -= 1;
}
return principal;
}
function compound2(
uint256 principal,
uint256 ratePerPeriod,
uint16 periods
) internal pure returns (uint256) {
if (0 == ratePerPeriod) {
return principal;
}
while (periods > 0) {
if (periods % 2 == 1) {
//principal += principal * ratePerPeriod / EXP_SCALE;
principal = principal.add(principal.mul(ratePerPeriod).div(EXP_SCALE));
periods -= 1;
} else {
//ratePerPeriod = ((2 * ratePerPeriod * EXP_SCALE) + (ratePerPeriod * ratePerPeriod)) / EXP_SCALE;
ratePerPeriod = ((uint256(2).mul(ratePerPeriod).mul(EXP_SCALE)).add(ratePerPeriod.mul(ratePerPeriod))).div(EXP_SCALE);
periods /= 2;
}
}
return principal;
}
// computes a * f / EXP_SCALE
function fractionOf(uint256 a, uint256 f) internal pure returns (uint256) {
return a.mul(f).div(EXP_SCALE);
}
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.7.6;
interface ICToken {
function mint(uint mintAmount) external returns (uint256);
function redeemUnderlying(uint redeemAmount) external returns (uint256);
function accrueInterest() external returns (uint256);
function exchangeRateStored() external view returns (uint256);
function exchangeRateCurrent() external returns (uint256);
function supplyRatePerBlock() external view returns (uint256);
function totalBorrows() external view returns (uint256);
function getCash() external view returns (uint256);
function underlying() external view returns (address);
function comptroller() external view returns (address);
}
interface ICTokenErc20 {
function balanceOf(address to) external view returns (uint256);
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.7.6;
interface IComptroller {
struct CompMarketState {
uint224 index;
uint32 block;
}
function enterMarkets(address[] memory cTokens) external returns (uint256[] memory);
function claimComp(address[] memory holders, address[] memory cTokens, bool borrowers, bool suppliers) external;
function mintAllowed(address cToken, address minter, uint256 mintAmount) external returns (uint256);
function getCompAddress() external view returns(address);
function compSupplyState(address cToken) external view returns (uint224, uint32);
function compSpeeds(address cToken) external view returns (uint256);
function oracle() external view returns (address);
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.7.6;
interface IUniswapAnchoredOracle {
function price(string memory symbol) external view returns (uint256);
function getUnderlyingPrice(address cToken) external view returns (uint256);
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.7.6;
interface IUniswapV2Router {
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.7.6;
pragma abicoder v2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "./../external-interfaces/compound-finance/ICToken.sol";
import "./../external-interfaces/compound-finance/IComptroller.sol";
import "./CompoundController.sol";
import "./ICompoundCumulator.sol";
import "./../IProvider.sol";
contract CompoundProvider is IProvider {
using SafeMath for uint256;
using SafeERC20 for IERC20;
uint256 public constant MAX_UINT256 = uint256(-1);
uint256 public constant EXP_SCALE = 1e18;
address public override smartYield;
address public override controller;
// fees colected in underlying
uint256 public override underlyingFees;
// underlying token (ie. DAI)
address public uToken; // IERC20
// claim token (ie. cDAI)
address public cToken;
// cToken.balanceOf(this) measuring only deposits by users (excludes direct cToken transfers to pool)
uint256 public cTokenBalance;
uint256 public exchangeRateCurrentCached;
uint256 public exchangeRateCurrentCachedAt;
bool public _setup;
event TransferFees(address indexed caller, address indexed feesOwner, uint256 fees);
modifier onlySmartYield {
require(
msg.sender == smartYield,
"PPC: only smartYield"
);
_;
}
modifier onlyController {
require(
msg.sender == controller,
"PPC: only controller"
);
_;
}
modifier onlySmartYieldOrController {
require(
msg.sender == smartYield || msg.sender == controller,
"PPC: only smartYield/controller"
);
_;
}
modifier onlyControllerOrDao {
require(
msg.sender == controller || msg.sender == CompoundController(controller).dao(),
"PPC: only controller/DAO"
);
_;
}
constructor(address cToken_)
{
cToken = cToken_;
uToken = ICToken(cToken_).underlying();
}
function setup(
address smartYield_,
address controller_
)
external
{
require(
false == _setup,
"PPC: already setup"
);
smartYield = smartYield_;
controller = controller_;
_enterMarket();
updateAllowances();
_setup = true;
}
function setController(address newController_)
external override
onlyControllerOrDao
{
// remove allowance on old controller
IERC20 rewardToken = IERC20(IComptroller(ICToken(cToken).comptroller()).getCompAddress());
rewardToken.safeApprove(controller, 0);
controller = newController_;
// give allowance to new controler
updateAllowances();
}
function updateAllowances()
public
{
IERC20 rewardToken = IERC20(IComptroller(ICToken(cToken).comptroller()).getCompAddress());
uint256 controllerRewardAllowance = rewardToken.allowance(address(this), controller);
rewardToken.safeIncreaseAllowance(controller, MAX_UINT256.sub(controllerRewardAllowance));
}
// externals
// take underlyingAmount_ from from_
function _takeUnderlying(address from_, uint256 underlyingAmount_)
external override
onlySmartYieldOrController
{
uint256 balanceBefore = IERC20(uToken).balanceOf(address(this));
IERC20(uToken).safeTransferFrom(from_, address(this), underlyingAmount_);
uint256 balanceAfter = IERC20(uToken).balanceOf(address(this));
require(
0 == (balanceAfter - balanceBefore - underlyingAmount_),
"PPC: _takeUnderlying amount"
);
}
// transfer away underlyingAmount_ to to_
function _sendUnderlying(address to_, uint256 underlyingAmount_)
external override
onlySmartYield
{
uint256 balanceBefore = IERC20(uToken).balanceOf(to_);
IERC20(uToken).safeTransfer(to_, underlyingAmount_);
uint256 balanceAfter = IERC20(uToken).balanceOf(to_);
require(
0 == (balanceAfter - balanceBefore - underlyingAmount_),
"PPC: _sendUnderlying amount"
);
}
// deposit underlyingAmount_ with the liquidity provider, callable by smartYield or controller
function _depositProvider(uint256 underlyingAmount_, uint256 takeFees_)
external override
onlySmartYieldOrController
{
_depositProviderInternal(underlyingAmount_, takeFees_);
}
// deposit underlyingAmount_ with the liquidity provider, store resulting cToken balance in cTokenBalance
function _depositProviderInternal(uint256 underlyingAmount_, uint256 takeFees_)
internal
{
// underlyingFees += takeFees_
underlyingFees = underlyingFees.add(takeFees_);
ICompoundCumulator(controller)._beforeCTokenBalanceChange();
IERC20(uToken).approve(address(cToken), underlyingAmount_);
uint256 err = ICToken(cToken).mint(underlyingAmount_);
require(0 == err, "PPC: _depositProvider mint");
ICompoundCumulator(controller)._afterCTokenBalanceChange(cTokenBalance);
// cTokenBalance is used to compute the pool yield, make sure no one interferes with the computations between deposits/withdrawls
cTokenBalance = ICTokenErc20(cToken).balanceOf(address(this));
}
// withdraw underlyingAmount_ from the liquidity provider, callable by smartYield
function _withdrawProvider(uint256 underlyingAmount_, uint256 takeFees_)
external override
onlySmartYield
{
_withdrawProviderInternal(underlyingAmount_, takeFees_);
}
// withdraw underlyingAmount_ from the liquidity provider, store resulting cToken balance in cTokenBalance
function _withdrawProviderInternal(uint256 underlyingAmount_, uint256 takeFees_)
internal
{
// underlyingFees += takeFees_;
underlyingFees = underlyingFees.add(takeFees_);
ICompoundCumulator(controller)._beforeCTokenBalanceChange();
uint256 err = ICToken(cToken).redeemUnderlying(underlyingAmount_);
require(0 == err, "PPC: _withdrawProvider redeemUnderlying");
ICompoundCumulator(controller)._afterCTokenBalanceChange(cTokenBalance);
// cTokenBalance is used to compute the pool yield, make sure no one interferes with the computations between deposits/withdrawls
cTokenBalance = ICTokenErc20(cToken).balanceOf(address(this));
}
function transferFees()
external
override
{
_withdrawProviderInternal(underlyingFees, 0);
underlyingFees = 0;
uint256 fees = IERC20(uToken).balanceOf(address(this));
address to = CompoundController(controller).feesOwner();
IERC20(uToken).safeTransfer(to, fees);
emit TransferFees(msg.sender, to, fees);
}
// current total underlying balance, as measured by pool, without fees
function underlyingBalance()
external virtual override
returns (uint256)
{
// https://compound.finance/docs#protocol-math
// (total balance in underlying) - underlyingFees
// cTokenBalance * exchangeRateCurrent() / EXP_SCALE - underlyingFees;
return cTokenBalance.mul(exchangeRateCurrent()).div(EXP_SCALE).sub(underlyingFees);
}
// /externals
// public
// get exchangeRateCurrent from compound and cache it for the current block
function exchangeRateCurrent()
public virtual
returns (uint256)
{
// only once per block
if (block.timestamp > exchangeRateCurrentCachedAt) {
exchangeRateCurrentCachedAt = block.timestamp;
exchangeRateCurrentCached = ICToken(cToken).exchangeRateCurrent();
}
return exchangeRateCurrentCached;
}
// /public
// internals
// call comptroller.enterMarkets()
// needs to be called only once BUT before any interactions with the provider
function _enterMarket()
internal
{
address[] memory markets = new address[](1);
markets[0] = cToken;
uint256[] memory err = IComptroller(ICToken(cToken).comptroller()).enterMarkets(markets);
require(err[0] == 0, "PPC: _enterMarket");
}
// /internals
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.7.6;
pragma abicoder v2;
import "./Governed.sol";
import "./IProvider.sol";
import "./ISmartYield.sol";
abstract contract IController is Governed {
uint256 public constant EXP_SCALE = 1e18;
address public pool; // compound provider pool
address public smartYield; // smartYield
address public oracle; // IYieldOracle
address public bondModel; // IBondModel
address public feesOwner; // fees are sent here
// max accepted cost of harvest when converting COMP -> underlying,
// if harvest gets less than (COMP to underlying at spot price) - HARVEST_COST%, it will revert.
// if it gets more, the difference goes to the harvest caller
uint256 public HARVEST_COST = 40 * 1e15; // 4%
// fee for buying jTokens
uint256 public FEE_BUY_JUNIOR_TOKEN = 3 * 1e15; // 0.3%
// fee for redeeming a sBond
uint256 public FEE_REDEEM_SENIOR_BOND = 100 * 1e15; // 10%
// max rate per day for sBonds
uint256 public BOND_MAX_RATE_PER_DAY = 719065000000000; // APY 30% / year
// max duration of a purchased sBond
uint16 public BOND_LIFE_MAX = 90; // in days
bool public PAUSED_BUY_JUNIOR_TOKEN = false;
bool public PAUSED_BUY_SENIOR_BOND = false;
function setHarvestCost(uint256 newValue_)
public
onlyDao
{
require(
HARVEST_COST < EXP_SCALE,
"IController: HARVEST_COST too large"
);
HARVEST_COST = newValue_;
}
function setBondMaxRatePerDay(uint256 newVal_)
public
onlyDao
{
BOND_MAX_RATE_PER_DAY = newVal_;
}
function setBondLifeMax(uint16 newVal_)
public
onlyDao
{
BOND_LIFE_MAX = newVal_;
}
function setFeeBuyJuniorToken(uint256 newVal_)
public
onlyDao
{
FEE_BUY_JUNIOR_TOKEN = newVal_;
}
function setFeeRedeemSeniorBond(uint256 newVal_)
public
onlyDao
{
FEE_REDEEM_SENIOR_BOND = newVal_;
}
function setPaused(bool buyJToken_, bool buySBond_)
public
onlyDaoOrGuardian
{
PAUSED_BUY_JUNIOR_TOKEN = buyJToken_;
PAUSED_BUY_SENIOR_BOND = buySBond_;
}
function setOracle(address newVal_)
public
onlyDao
{
oracle = newVal_;
}
function setBondModel(address newVal_)
public
onlyDao
{
bondModel = newVal_;
}
function setFeesOwner(address newVal_)
public
onlyDao
{
feesOwner = newVal_;
}
function yieldControllTo(address newController_)
public
onlyDao
{
IProvider(pool).setController(newController_);
ISmartYield(smartYield).setController(newController_);
}
function providerRatePerDay() external virtual returns (uint256);
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.7.6;
pragma abicoder v2;
interface ICompoundCumulator {
function _beforeCTokenBalanceChange() external;
function _afterCTokenBalanceChange(uint256 prevCTokenBalance_) external;
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.7.6;
pragma abicoder v2;
interface IYieldOracle {
function update() external;
function consult(uint256 forInterval) external returns (uint256 amountOut);
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.7.6;
pragma abicoder v2;
interface IYieldOraclelizable {
// accumulates/updates internal state and returns cumulatives
// oracle should call this when updating
function cumulatives()
external
returns(uint256 cumulativeYield);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev 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;
/**
* @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);
}
}
}
}
pragma solidity >=0.5.0;
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
// SPDX-License-Identifier: CC-BY-4.0
pragma solidity >=0.4.0;
// taken from https://medium.com/coinmonks/math-in-solidity-part-3-percents-and-proportions-4db014e080b1
// license is CC-BY-4.0
library FullMath {
function fullMul(uint256 x, uint256 y) internal pure returns (uint256 l, uint256 h) {
uint256 mm = mulmod(x, y, uint256(-1));
l = x * y;
h = mm - l;
if (mm < l) h -= 1;
}
function fullDiv(
uint256 l,
uint256 h,
uint256 d
) private pure returns (uint256) {
uint256 pow2 = d & -d;
d /= pow2;
l /= pow2;
l += h * ((-pow2) / pow2 + 1);
uint256 r = 1;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
return l * r;
}
function mulDiv(
uint256 x,
uint256 y,
uint256 d
) internal pure returns (uint256) {
(uint256 l, uint256 h) = fullMul(x, y);
uint256 mm = mulmod(x, y, d);
if (mm > l) h -= 1;
l -= mm;
if (h == 0) return l / d;
require(h < d, 'FullMath: FULLDIV_OVERFLOW');
return fullDiv(l, h, d);
}
}
// 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 {
// credit for this implementation goes to
// https://github.com/abdk-consulting/abdk-libraries-solidity/blob/master/ABDKMath64x64.sol#L687
function sqrt(uint256 x) internal pure returns (uint256) {
if (x == 0) return 0;
// this block is equivalent to r = uint256(1) << (BitMath.mostSignificantBit(x) / 2);
// however that code costs significantly more gas
uint256 xx = x;
uint256 r = 1;
if (xx >= 0x100000000000000000000000000000000) {
xx >>= 128;
r <<= 64;
}
if (xx >= 0x10000000000000000) {
xx >>= 64;
r <<= 32;
}
if (xx >= 0x100000000) {
xx >>= 32;
r <<= 16;
}
if (xx >= 0x10000) {
xx >>= 16;
r <<= 8;
}
if (xx >= 0x100) {
xx >>= 8;
r <<= 4;
}
if (xx >= 0x10) {
xx >>= 4;
r <<= 2;
}
if (xx >= 0x8) {
r <<= 1;
}
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1; // Seven iterations should be enough
uint256 r1 = x / r;
return (r < r1 ? r : r1);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity >=0.5.0;
library BitMath {
// returns the 0 indexed position of the most significant bit of the input x
// s.t. x >= 2**msb and x < 2**(msb+1)
function mostSignificantBit(uint256 x) internal pure returns (uint8 r) {
require(x > 0, 'BitMath::mostSignificantBit: zero');
if (x >= 0x100000000000000000000000000000000) {
x >>= 128;
r += 128;
}
if (x >= 0x10000000000000000) {
x >>= 64;
r += 64;
}
if (x >= 0x100000000) {
x >>= 32;
r += 32;
}
if (x >= 0x10000) {
x >>= 16;
r += 16;
}
if (x >= 0x100) {
x >>= 8;
r += 8;
}
if (x >= 0x10) {
x >>= 4;
r += 4;
}
if (x >= 0x4) {
x >>= 2;
r += 2;
}
if (x >= 0x2) r += 1;
}
// returns the 0 indexed position of the least significant bit of the input x
// s.t. (x & 2**lsb) != 0 and (x & (2**(lsb) - 1)) == 0)
// i.e. the bit at the index is set and the mask of all lower bits is 0
function leastSignificantBit(uint256 x) internal pure returns (uint8 r) {
require(x > 0, 'BitMath::leastSignificantBit: zero');
r = 255;
if (x & uint128(-1) > 0) {
r -= 128;
} else {
x >>= 128;
}
if (x & uint64(-1) > 0) {
r -= 64;
} else {
x >>= 64;
}
if (x & uint32(-1) > 0) {
r -= 32;
} else {
x >>= 32;
}
if (x & uint16(-1) > 0) {
r -= 16;
} else {
x >>= 16;
}
if (x & uint8(-1) > 0) {
r -= 8;
} else {
x >>= 8;
}
if (x & 0xf > 0) {
r -= 4;
} else {
x >>= 4;
}
if (x & 0x3 > 0) {
r -= 2;
} else {
x >>= 2;
}
if (x & 0x1 > 0) r -= 1;
}
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.7.6;
pragma abicoder v2;
interface IProvider {
function smartYield() external view returns (address);
function controller() external view returns (address);
function underlyingFees() external view returns (uint256);
// deposit underlyingAmount_ into provider, add takeFees_ to fees
function _depositProvider(uint256 underlyingAmount_, uint256 takeFees_) external;
// withdraw underlyingAmount_ from provider, add takeFees_ to fees
function _withdrawProvider(uint256 underlyingAmount_, uint256 takeFees_) external;
function _takeUnderlying(address from_, uint256 amount_) external;
function _sendUnderlying(address to_, uint256 amount_) external;
function transferFees() external;
// current total underlying balance as measured by the provider pool, without fees
function underlyingBalance() external returns (uint256);
function setController(address newController_) external;
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.7.6;
pragma abicoder v2;
abstract contract Governed {
address public dao;
address public guardian;
modifier onlyDao {
require(
dao == msg.sender,
"GOV: not dao"
);
_;
}
modifier onlyDaoOrGuardian {
require(
msg.sender == dao || msg.sender == guardian,
"GOV: not dao/guardian"
);
_;
}
constructor()
{
dao = msg.sender;
guardian = msg.sender;
}
function setDao(address dao_)
external
onlyDao
{
dao = dao_;
}
function setGuardian(address guardian_)
external
onlyDao
{
guardian = guardian_;
}
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.7.6;
pragma abicoder v2;
interface ISmartYield {
// a senior BOND (metadata for NFT)
struct SeniorBond {
// amount seniors put in
uint256 principal;
// amount yielded at the end. total = principal + gain
uint256 gain;
// bond was issued at timestamp
uint256 issuedAt;
// bond matures at timestamp
uint256 maturesAt;
// was it liquidated yet
bool liquidated;
}
// a junior BOND (metadata for NFT)
struct JuniorBond {
// amount of tokens (jTokens) junior put in
uint256 tokens;
// bond matures at timestamp
uint256 maturesAt;
}
// a checkpoint for all JuniorBonds with same maturity date JuniorBond.maturesAt
struct JuniorBondsAt {
// sum of JuniorBond.tokens for JuniorBonds with the same JuniorBond.maturesAt
uint256 tokens;
// price at which JuniorBonds will be paid. Initially 0 -> unliquidated (price is in the future or not yet liquidated)
uint256 price;
}
function controller() external view returns (address);
function buyBond(uint256 principalAmount_, uint256 minGain_, uint256 deadline_, uint16 forDays_) external returns (uint256);
function redeemBond(uint256 bondId_) external;
function unaccountBonds(uint256[] memory bondIds_) external;
function buyTokens(uint256 underlyingAmount_, uint256 minTokens_, uint256 deadline_) external;
/**
* sell all tokens instantly
*/
function sellTokens(uint256 tokens_, uint256 minUnderlying_, uint256 deadline_) external;
function buyJuniorBond(uint256 tokenAmount_, uint256 maxMaturesAt_, uint256 deadline_) external;
function redeemJuniorBond(uint256 jBondId_) external;
function liquidateJuniorBonds(uint256 upUntilTimestamp_) external;
/**
* token purchase price
*/
function price() external returns (uint256);
function abondPaid() external view returns (uint256);
function abondDebt() external view returns (uint256);
function abondGain() external view returns (uint256);
/**
* @notice current total underlying balance, without accruing interest
*/
function underlyingTotal() external returns (uint256);
/**
* @notice current underlying loanable, without accruing interest
*/
function underlyingLoanable() external returns (uint256);
function underlyingJuniors() external returns (uint256);
function bondGain(uint256 principalAmount_, uint16 forDays_) external returns (uint256);
function maxBondDailyRate() external returns (uint256);
function setController(address newController_) external;
}
|
deposit underlyingAmount_ into provider, add takeFees_ to fees withdraw underlyingAmount_ from provider, add takeFees_ to fees current total underlying balance as measured by the provider pool, without fees
|
interface IProvider {
function smartYield() external view returns (address);
function controller() external view returns (address);
function underlyingFees() external view returns (uint256);
function _depositProvider(uint256 underlyingAmount_, uint256 takeFees_) external;
function _withdrawProvider(uint256 underlyingAmount_, uint256 takeFees_) external;
function _takeUnderlying(address from_, uint256 amount_) external;
function _sendUnderlying(address to_, uint256 amount_) external;
function transferFees() external;
function underlyingBalance() external returns (uint256);
function setController(address newController_) external;
pragma solidity ^0.7.6;
}
| 60,147 |
// This contract is not supposed to be used in production
// It's strictly for testing purpose
pragma solidity ^0.8.4;
import {ERC1155Supply, ERC1155, IERC165, Context} from "@openzeppelin/contracts/token/ERC1155/extensions/ERC1155Supply.sol";
import {Pausable} from "@openzeppelin/contracts/security/Pausable.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {AccessControlMixin, AccessControl, Context} from "../../common/AccessControlMixin.sol";
import {NativeMetaTransaction} from "../../common/NativeMetaTransaction.sol";
import {IMintableERC1155, IERC1155} from "./IMintableERC1155.sol";
import {ContextMixin} from "../../common/ContextMixin.sol";
contract RootFactionArt is
ERC1155Supply,
Pausable,
Ownable,
AccessControlMixin,
NativeMetaTransaction,
ContextMixin,
IMintableERC1155
{
bytes32 public constant PREDICATE_ROLE = keccak256("PREDICATE_ROLE");
// Contract name
string public name;
// Contract symbol
string public symbol;
// Initial Contract URI
string private CONTRACT_URI;
// Max Token ID
uint256 public constant MAX_TOKEN_ID = 12;
constructor (
string memory name_,
string memory symbol_,
string memory uri_,
address mintableERC1155PredicateProxy
)
ERC1155(uri_)
{
_setupContractId("RootFactionArt");
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_setupRole(PREDICATE_ROLE, mintableERC1155PredicateProxy);
_initializeEIP712(uri_);
name = name_;
symbol = symbol_;
CONTRACT_URI = "https://api.cypherverse.io/os/collections/factionart";
}
function mint(
address account,
uint256 id,
uint256 amount,
bytes calldata data
) external override only(PREDICATE_ROLE) {
// Restrict minting of tokens to only the Predicate role
require(((id <= MAX_TOKEN_ID) && (id > uint(0))), "RootFactionArt: INVALID_TOKEN_ID");
require(((amount > uint(0)) && (amount == restTotalSupply(id, amount))) , "RootFactionArt: INVALID_TOKEN_AMOUNT");
_mint(account, id, amount, data);
}
function mintBatch(
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata data
) external override only(PREDICATE_ROLE) {
// Restrict minting of tokens to only the Predicate role
for (uint i = 0; i < ids.length; i++) {
require(((ids[i] <= MAX_TOKEN_ID) && (ids[i] > uint(0))), "RootFactionArt: INVALID_TOKEN_ID");
require(((amounts[i] > uint(0)) && (amounts[i] == restTotalSupply(ids[i], amounts[i]))), "RootFactionArt: INVALID_TOKEN_AMOUNT");
}
_mintBatch(to, ids, amounts, data);
}
function burn(
address account,
uint256 id,
uint256 value
) public virtual {
require(
account == _msgSender() || isApprovedForAll(account, _msgSender()),
"RootFactionArt: caller is not owner nor approved"
);
_burn(account, id, value);
}
function burnBatch(
address account,
uint256[] memory ids,
uint256[] memory values
) public virtual {
require(
account == _msgSender() || isApprovedForAll(account, _msgSender()),
"RootFactionArt: caller is not owner nor approved"
);
_burnBatch(account, ids, values);
}
// This is to support Native meta transactions
// never use msg.sender directly, use _msgSender() instead
function _msgSender()
internal
override (Context)
view
returns (address sender)
{
return ContextMixin.msgSender();
}
function _msgData()
internal
override (Context)
pure
returns (bytes calldata) {
return msg.data;
}
/**
* Override isApprovedForAll to auto-approve OS's proxy contract
*/
function isApprovedForAll(
address _owner,
address _operator
) public override(ERC1155, IERC1155) view returns (bool isOperator) {
// if OpenSea's ERC1155 Proxy Address is detected, auto-return true
if (_operator == address(0x207Fa8Df3a17D96Ca7EA4f2893fcdCb78a304101)) {
return true;
}
// otherwise, use the default ERC1155.isApprovedForAll()
return ERC1155.isApprovedForAll(_owner, _operator);
}
/**
* @notice Make the SetTokenURI method visible for future upgrade of metadata
* @dev Sets `_tokenURI` as the tokenURI for the `all` tokenId.
*/
function setURI(string memory _tokenURI) public virtual onlyOwner() {
_setURI(_tokenURI);
}
/**
* @notice Method for reduce the friction with openSea allows to map the `tokenId`
* @dev into our NFT Smart contract and handle some metadata offchain in OpenSea
*/
function contractURI() public view returns (string memory) {
return CONTRACT_URI;
}
/**
* @notice Method for reduce the friction with openSea allows update the Contract URI
* @dev This method is only available for the owner of the contract
* @param _contractURI The new contract URI
*/
function setContractURI(string memory _contractURI) public onlyOwner() {
CONTRACT_URI = _contractURI;
}
/**
* @notice Method for getting Max Supply for Token
* @dev This method is for getting the Max Supply by token id
* @param _id The token id
*/
function maxSupply(uint256 _id) public pure returns (uint256 _maxSupply) {
_maxSupply = 0;
if ((_id == 1) || (_id == 5) || (_id == 9)) {
_maxSupply = uint256(645);
} else if ((_id == 2) || (_id == 6) || (_id == 10)) {
_maxSupply = uint256(1263);
} else if ((_id == 3) || (_id == 7) || (_id == 11)) {
_maxSupply = uint256(1267);
} else if ((_id == 4) || (_id == 8) || (_id == 12)) {
_maxSupply = uint256(3141);
}
}
/**
* @notice Method for getting OpenSea Version we Operate
* @dev This method is for getting the Max Supply by token id
*/
function openSeaVersion() public pure returns (string memory) {
return "2.1.0";
}
/**
* Compat for factory interfaces on OpenSea
* Indicates that this contract can return balances for
* tokens that haven't been minted yet
*/
function supportsFactoryInterface() public pure returns (bool) {
return true;
}
/**
* @dev Implementation / Instance of paused methods() in the ERC1155.
* @param status Setting the status boolean (True for paused, or False for unpaused)
* See {ERC1155Pausable}.
*/
function pause(bool status) public onlyOwner() {
if (status) {
_pause();
} else {
_unpause();
}
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC1155, AccessControl, IERC165) returns (bool) {
return super.supportsInterface(interfaceId);
}
/**
* @dev Method, for verify the TotalSupply of the NFT, each time to mint a new NFT Token
* @param _id The id of the NFT Token
* @param _amount The amount of the NFT Token
* @return The amount of the NFT Token to mint
*/
function restTotalSupply(uint256 _id, uint256 _amount) private view returns (uint256) {
uint256 subtotal = totalSupply(_id)+_amount;
require(( subtotal <= maxSupply(_id) ), "RootFactionArt: EXCEED MAX_AMOUNT");
return _amount;
}
/**
* @dev See {ERC1155-_beforeTokenTransfer}.
*
* Requirements:
*
* - the contract must not be paused.
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual override {
super._beforeTokenTransfer(operator, from, to, ids, amounts, data);
require(!paused(), "RootFactionArt: token transfer while paused");
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC1155.sol";
/**
* @dev Extension of ERC1155 that adds tracking of total supply per id.
*
* Useful for scenarios where Fungible and Non-fungible tokens have to be
* clearly identified. Note: While a totalSupply of 1 might mean the
* corresponding is an NFT, there is no guarantees that no other token with the
* same id are not going to be minted.
*/
abstract contract ERC1155Supply is ERC1155 {
mapping(uint256 => uint256) private _totalSupply;
/**
* @dev Total amount of tokens in with a given id.
*/
function totalSupply(uint256 id) public view virtual returns (uint256) {
return _totalSupply[id];
}
/**
* @dev Indicates weither any token exist with a given id, or not.
*/
function exists(uint256 id) public view virtual returns (bool) {
return ERC1155Supply.totalSupply(id) > 0;
}
/**
* @dev See {ERC1155-_beforeTokenTransfer}.
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual override {
super._beforeTokenTransfer(operator, from, to, ids, amounts, data);
if (from == address(0)) {
for (uint256 i = 0; i < ids.length; ++i) {
_totalSupply[ids[i]] += amounts[i];
}
}
if (to == address(0)) {
for (uint256 i = 0; i < ids.length; ++i) {
_totalSupply[ids[i]] -= amounts[i];
}
}
}
}
// SPDX-License-Identifier: MIT
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
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);
}
}
pragma solidity ^0.8.0;
import {AccessControl, Context} from "@openzeppelin/contracts/access/AccessControl.sol";
contract AccessControlMixin is AccessControl {
string private _revertMsg;
function _setupContractId(string memory contractId) internal {
_revertMsg = string(abi.encodePacked(contractId, ": INSUFFICIENT_PERMISSIONS"));
}
modifier only(bytes32 role) {
require(
hasRole(role, _msgSender()),
_revertMsg
);
_;
}
}
pragma solidity ^0.8.0;
import {SafeMath} from "@openzeppelin/contracts/utils/math/SafeMath.sol";
import {EIP712Base} from "./EIP712Base.sol";
contract NativeMetaTransaction is EIP712Base {
using SafeMath for uint256;
bytes32 private constant META_TRANSACTION_TYPEHASH = keccak256(
bytes(
"MetaTransaction(uint256 nonce,address from,bytes functionSignature)"
)
);
event MetaTransactionExecuted(
address userAddress,
address payable relayerAddress,
bytes functionSignature
);
mapping(address => uint256) nonces;
/*
* Meta transaction structure.
* No point of including value field here as if user is doing value transfer then he has the funds to pay for gas
* He should call the desired function directly in that case.
*/
struct MetaTransaction {
uint256 nonce;
address from;
bytes functionSignature;
}
function executeMetaTransaction(
address userAddress,
bytes memory functionSignature,
bytes32 sigR,
bytes32 sigS,
uint8 sigV
) public payable returns (bytes memory) {
MetaTransaction memory metaTx = MetaTransaction({
nonce: nonces[userAddress],
from: userAddress,
functionSignature: functionSignature
});
require(
verify(userAddress, metaTx, sigR, sigS, sigV),
"Signer and signature do not match"
);
// increase nonce for user (to avoid re-use)
nonces[userAddress] = nonces[userAddress].add(1);
emit MetaTransactionExecuted(
userAddress,
payable(msg.sender),
functionSignature
);
// Append userAddress and relayer address at the end to extract it from calling context
(bool success, bytes memory returnData) = address(this).call(
abi.encodePacked(functionSignature, userAddress)
);
require(success, "Function call not successful");
return returnData;
}
function hashMetaTransaction(MetaTransaction memory metaTx)
internal
pure
returns (bytes32)
{
return
keccak256(
abi.encode(
META_TRANSACTION_TYPEHASH,
metaTx.nonce,
metaTx.from,
keccak256(metaTx.functionSignature)
)
);
}
function getNonce(address user) public view returns (uint256 nonce) {
nonce = nonces[user];
}
function verify(
address signer,
MetaTransaction memory metaTx,
bytes32 sigR,
bytes32 sigS,
uint8 sigV
) internal view returns (bool) {
require(signer != address(0), "NativeMetaTransaction: INVALID_SIGNER");
return
signer ==
ecrecover(
toTypedMessageHash(hashMetaTransaction(metaTx)),
sigV,
sigR,
sigS
);
}
}
import {IERC1155} from "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
pragma solidity ^0.8.0;
interface IMintableERC1155 is IERC1155 {
/**
* @notice Creates `amount` tokens of token type `id`, and assigns them to `account`.
* @dev Should be callable only by MintableERC1155Predicate
* Make sure minting is done only by this function
* @param account user address for whom token is being minted
* @param id token which is being minted
* @param amount amount of token being minted
* @param data extra byte data to be accompanied with minted tokens
*/
function mint(address account, uint256 id, uint256 amount, bytes calldata data) external;
/**
* @notice Batched version of singular token minting, where
* for each token in `ids` respective amount to be minted from `amounts`
* array, for address `to`.
* @dev Should be callable only by MintableERC1155Predicate
* Make sure minting is done only by this function
* @param to user address for whom token is being minted
* @param ids tokens which are being minted
* @param amounts amount of each token being minted
* @param data extra byte data to be accompanied with minted tokens
*/
function mintBatch(address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external;
}
pragma solidity ^0.8.0;
abstract contract ContextMixin {
function msgSender()
internal
view
virtual
returns (address sender)
{
if (msg.sender == address(this)) {
bytes memory array = msg.data;
uint256 index = msg.data.length;
assembly {
// Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those.
sender := and(
mload(add(array, index)),
0xffffffffffffffffffffffffffffffffffffffff
)
}
} else {
sender = msg.sender;
}
return sender;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC1155.sol";
import "./IERC1155Receiver.sol";
import "./extensions/IERC1155MetadataURI.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of the basic standard multi-token.
* See https://eips.ethereum.org/EIPS/eip-1155
* Originally based on code by Enjin: https://github.com/enjin/erc-1155
*
* _Available since v3.1._
*/
contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI {
using Address for address;
// Mapping from token ID to account balances
mapping(uint256 => mapping(address => uint256)) private _balances;
// Mapping from account to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
// Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json
string private _uri;
/**
* @dev See {_setURI}.
*/
constructor(string memory uri_) {
_setURI(uri_);
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC1155).interfaceId ||
interfaceId == type(IERC1155MetadataURI).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC1155MetadataURI-uri}.
*
* This implementation returns the same URI for *all* token types. It relies
* on the token type ID substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* Clients calling this function must replace the `\{id\}` substring with the
* actual token type ID.
*/
function uri(uint256) public view virtual override returns (string memory) {
return _uri;
}
/**
* @dev See {IERC1155-balanceOf}.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) public view virtual override returns (uint256) {
require(account != address(0), "ERC1155: balance query for the zero address");
return _balances[id][account];
}
/**
* @dev See {IERC1155-balanceOfBatch}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] memory accounts, uint256[] memory ids)
public
view
virtual
override
returns (uint256[] memory)
{
require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch");
uint256[] memory batchBalances = new uint256[](accounts.length);
for (uint256 i = 0; i < accounts.length; ++i) {
batchBalances[i] = balanceOf(accounts[i], ids[i]);
}
return batchBalances;
}
/**
* @dev See {IERC1155-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(_msgSender() != operator, "ERC1155: setting approval status for self");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC1155-isApprovedForAll}.
*/
function isApprovedForAll(address account, address operator) public view virtual override returns (bool) {
return _operatorApprovals[account][operator];
}
/**
* @dev See {IERC1155-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) public virtual override {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
_safeTransferFrom(from, to, id, amount, data);
}
/**
* @dev See {IERC1155-safeBatchTransferFrom}.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) public virtual override {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: transfer caller is not owner nor approved"
);
_safeBatchTransferFrom(from, to, ids, amounts, data);
}
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data);
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
emit TransferSingle(operator, from, to, id, amount);
_doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function _safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; ++i) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
}
emit TransferBatch(operator, from, to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data);
}
/**
* @dev Sets a new URI for all token types, by relying on the token type ID
* substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* By this mechanism, any occurrence of the `\{id\}` substring in either the
* URI or any of the amounts in the JSON file at said URI will be replaced by
* clients with the token type ID.
*
* For example, the `https://token-cdn-domain/\{id\}.json` URI would be
* interpreted by clients as
* `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json`
* for token type ID 0x4cce0.
*
* See {uri}.
*
* Because these URIs cannot be meaningfully represented by the {URI} event,
* this function emits no events.
*/
function _setURI(string memory newuri) internal virtual {
_uri = newuri;
}
/**
* @dev Creates `amount` tokens of token type `id`, and assigns them to `account`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _mint(
address account,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(account != address(0), "ERC1155: mint to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data);
_balances[id][account] += amount;
emit TransferSingle(operator, address(0), account, id, amount);
_doSafeTransferAcceptanceCheck(operator, address(0), account, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function _mintBatch(
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; i++) {
_balances[ids[i]][to] += amounts[i];
}
emit TransferBatch(operator, address(0), to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data);
}
/**
* @dev Destroys `amount` tokens of token type `id` from `account`
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens of token type `id`.
*/
function _burn(
address account,
uint256 id,
uint256 amount
) internal virtual {
require(account != address(0), "ERC1155: burn from the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), "");
uint256 accountBalance = _balances[id][account];
require(accountBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][account] = accountBalance - amount;
}
emit TransferSingle(operator, account, address(0), id, amount);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
*/
function _burnBatch(
address account,
uint256[] memory ids,
uint256[] memory amounts
) internal virtual {
require(account != address(0), "ERC1155: burn from the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, account, address(0), ids, amounts, "");
for (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 accountBalance = _balances[id][account];
require(accountBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][account] = accountBalance - amount;
}
}
emit TransferBatch(operator, account, address(0), ids, amounts);
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning, as well as batched variants.
*
* The same hook is called on both single and batched variants. For single
* transfers, the length of the `id` and `amount` arrays will be 1.
*
* Calling conditions (for each `id` and `amount` pair):
*
* - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* of token type `id` will be transferred to `to`.
* - When `from` is zero, `amount` tokens of token type `id` will be minted
* for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens of token type `id`
* will be burned.
* - `from` and `to` are never both zero.
* - `ids` and `amounts` have the same, non-zero length.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {}
function _doSafeTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) private {
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) {
if (response != IERC1155Receiver.onERC1155Received.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _doSafeBatchTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) private {
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (
bytes4 response
) {
if (response != IERC1155Receiver.onERC1155BatchReceived.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) {
uint256[] memory array = new uint256[](1);
array[0] = element;
return array;
}
}
// SPDX-License-Identifier: MIT
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 "../../utils/introspection/IERC165.sol";
/**
* @dev _Available since v3.1._
*/
interface IERC1155Receiver is IERC165 {
/**
@dev Handles the receipt of a single ERC1155 token type. This function is
called at the end of a `safeTransferFrom` after the balance has been updated.
To accept the transfer, this must return
`bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
(i.e. 0xf23a6e61, or its own function selector).
@param operator The address which initiated the transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param id The ID of the token being transferred
@param value The amount of tokens being transferred
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
) external returns (bytes4);
/**
@dev Handles the receipt of a multiple ERC1155 token types. This function
is called at the end of a `safeBatchTransferFrom` after the balances have
been updated. To accept the transfer(s), this must return
`bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
(i.e. 0xbc197c81, or its own function selector).
@param operator The address which initiated the batch transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param ids An array containing ids of each token being transferred (order and length must match values array)
@param values An array containing amounts of each token being transferred (order and length must match ids array)
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../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;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IAccessControl.sol";
import "../utils/Context.sol";
import "../utils/Strings.sol";
import "../utils/introspection/ERC165.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 AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev 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(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev 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 {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(uint160(account), 20),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
function _grantRole(bytes32 role, address account) private {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
/**
* @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
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;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
pragma solidity ^0.8.0;
import {Initializable} from "./Initializable.sol";
contract EIP712Base is Initializable {
struct EIP712Domain {
string name;
string version;
address verifyingContract;
bytes32 salt;
}
string constant public ERC712_VERSION = "1";
bytes32 internal constant EIP712_DOMAIN_TYPEHASH = keccak256(
bytes(
"EIP712Domain(string name,string version,address verifyingContract,bytes32 salt)"
)
);
bytes32 internal domainSeperator;
// supposed to be called once while initializing.
// one of the contractsa that inherits this contract follows proxy pattern
// so it is not possible to do this in a constructor
function _initializeEIP712(
string memory name
)
internal
initializer
{
_setDomainSeperator(name);
}
function _setDomainSeperator(string memory name) internal {
domainSeperator = keccak256(
abi.encode(
EIP712_DOMAIN_TYPEHASH,
keccak256(bytes(name)),
keccak256(bytes(ERC712_VERSION)),
address(this),
bytes32(getChainId())
)
);
}
function getDomainSeperator() public view returns (bytes32) {
return domainSeperator;
}
function getChainId() public view returns (uint256) {
uint256 id;
assembly {
id := chainid()
}
return id;
}
/**
* Accept message hash and returns hash message in EIP712 compatible form
* So that it can be used to recover signer from signature signed using EIP712 formatted data
* https://eips.ethereum.org/EIPS/eip-712
* "\\x19" makes the encoding deterministic
* "\\x01" is the version byte to make it compatible to EIP-191
*/
function toTypedMessageHash(bytes32 messageHash)
internal
view
returns (bytes32)
{
return
keccak256(
abi.encodePacked("\x19\x01", getDomainSeperator(), messageHash)
);
}
}
pragma solidity ^0.8.0;
contract Initializable {
bool inited = false;
modifier initializer() {
require(!inited, "already inited");
_;
inited = true;
}
}
|
See {ERC1155-_beforeTokenTransfer}. Requirements: - the contract must not be paused./
|
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual override {
super._beforeTokenTransfer(operator, from, to, ids, amounts, data);
require(!paused(), "RootFactionArt: token transfer while paused");
}
| 1,141,047 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.3;
import '@openzeppelin/contracts/math/SafeMath.sol';
import '@openzeppelin/contracts/utils/SafeCast.sol';
/// @title Ameso Token
/// @author Simon Liu & Donald Liu
/**
* @title Ameso contract
* @dev This is the implementation of the ERC20 Ameso Token.
* The implementation exposes a Permit() function to allow for a spender to send a signed message
* and approve funds to a spender following EIP2612 to make integration with other contracts easier.
* EIP2612 describes how to use EIP712 for the Permit() function.
*
*/
contract AmesoToken {
using SafeMath for uint256;
// The EIP-712 typehash for the contract's domain
bytes32 private constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyContract)");
/// The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// The EIP-712 typehash for the permit struct used by the contract
bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
// -- Events --
event MinterChanged(address minter, address newMinter);
// An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
// An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
// The standard EIP-20 transfer event
event Transfer(address indexed from, address indexed to, uint256 amount);
// The standard EIP-20 approval event
event Approval(address indexed owner, address indexed spender, uint256 amount);
// -- State --
// EIP-20 token name for this token
string public constant name = "Ameso";
// EIP-20 token symbol for this token
string public constant symbol = "AMS";
// EIP-20 token decimals for this token
uint8 public constant decimals = 18;
uint256 public totalSupply = 1_000_000_000e18; // 1 billion AMS
bytes32 private DOMAIN_SEPARATOR;
mapping(address => uint256) public nonces;
address minter;
uint256 public mintingAllowedAfter;
uint256 public minimumTimeBetweenMints = 30 days;
// A record of each accounts delegate
mapping (address => address) public delegates;
// Cap on the percentage of totalSupply that can be minted at each mint
uint8 public constant mintCap = 2;
// Allowance amounts on behalf of others
mapping (address => mapping (address => uint256)) internal allowances;
// Official record of token balances for each account
mapping (address => uint256) internal balances;
// A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint256 votes;
}
// A record of votes checkpoints for each account, by index
mapping (address => mapping (uint256 => Checkpoint)) public checkpoints;
// The number of checkpoints for each account
mapping (address => uint256) public numCheckpoints;
/**
* @dev Construct a new nWork token
* @param _account Developer account to initially mint tokens
* @param _minter The account with minting ability
* @param _initialSupplyDev Amount to give to the dev account
* @param _initialSupplyMinter Amount to give to the Treasury
* @param _mintingAllowedAfter The timestamp after which minting may occur
*/
constructor(address _account, address _minter, uint256 _initialSupplyDev, uint256 _initialSupplyMinter, uint256 _mintingAllowedAfter) {
require(_mintingAllowedAfter >= block.timestamp, "AMS::constructor: minting can only begin after deployment");
balances[_account] = _initialSupplyDev;
emit Transfer(address(0), _account, _initialSupplyDev);
balances[_minter] = _initialSupplyMinter;
emit Transfer(address(0), _minter, _initialSupplyMinter);
minter = _minter;
emit MinterChanged(address(0), minter);
mintingAllowedAfter = _mintingAllowedAfter;
}
/**
* @dev Change the minter address
* @param _minter The address of the new minter
*/
function setMinter(address _minter) external {
require(msg.sender == minter, "AMS::setMinter: only the minter can change the minter address");
emit MinterChanged(minter, _minter);
minter = _minter;
}
/**
* @dev Mint new tokens
* @param _dst The address of the destination accoutn
* @param _amount The number of tokens to be minted
*/
function mint(address _dst, uint256 _amount) external {
require(msg.sender == minter, "AMS::mint: only the treasury can mint");
require(block.timestamp >= mintingAllowedAfter, "AMS::mint: minting not allowed yet");
require(_dst != address(0), "AMS::mint: cannot transfer to the zero address");
// record the mint
mintingAllowedAfter = SafeMath.add(block.timestamp, minimumTimeBetweenMints);
// mint the amount
require(_amount <= SafeMath.div(SafeMath.mul(totalSupply, mintCap), 100), "AMS::mint: exceeded mint cap");
totalSupply = SafeMath.add(totalSupply, _amount);
// transfer the amount to the recipient
balances[_dst] = SafeMath.add(balances[_dst], _amount);
emit Transfer(address(0), _dst, _amount);
// move delegates
_moveDelegates(address(0), delegates[_dst], _amount);
}
/**
* @notice Get the number of tokens `spender` is approved to spend on behalf of `account`
* @param _account The address of the account holding the funds
* @param _spender The address of the account spending the funds
* @return The number of tokens approved
*/
function allowance(address _account, address _spender) external view returns (uint256) {
return allowances[_account][_spender];
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param _spender The address of the account which may transfer tokens
* @param _amount The number of tokens that are approved (2^256-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address _spender, uint256 _amount) external returns (bool) {
allowances[msg.sender][_spender] = _amount;
emit Approval(msg.sender, _spender, _amount);
return true;
}
/**
* @dev Approve token allowance by validating a message signed by the holder.
* @param _owner Address of the token holder
* @param _spender Address of the approved spender
* @param _value Amount of tokens to approve the spender
* @param _deadline Expiration time of the signed permit
* @param _v Signature version
* @param _r Signature r value
* @param _s Signature s value
*/
function permit(address _owner, address _spender, uint256 _value, uint256 _deadline, uint8 _v, bytes32 _r, bytes32 _s) external {
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), _getChainID(), address(this)));
bytes32 structHash = keccak256(abi.encode(PERMIT_TYPEHASH, _owner, _spender, _value, nonces[_owner]++, _deadline));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address recoveredAddress = ecrecover(digest, _v, _r, _s);
require(_owner != address(0), "AMS::permit: invalid signature");
require(_owner == recoveredAddress, "AMS::permit: unauthorized");
require(_deadline == 0 || block.timestamp <= _deadline, "AMS::permit: expired permit");
allowances[_owner][_spender] = _value;
emit Approval(_owner, _spender, _value);
}
/**
* @notice Get the number of tokens held by the `account`
* @param _account The address of the account to get the balance of
* @return The number of tokens held
*/
function balanceOf(address _account) external view returns (uint) {
return balances[_account];
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param _dst The address of the destination account
* @param _amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address _dst, uint256 _amount) external returns (bool) {
_transferTokens(msg.sender, _dst, _amount);
return true;
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param _src The address of the source account
* @param _dst The address of the destination account
* @param _amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address _src, address _dst, uint _amount) external returns (bool) {
address spender = msg.sender;
uint256 spenderAllowance = allowances[_src][spender];
if (spender != _src && spenderAllowance != uint256(-1)) {
uint256 newAllowance = SafeMath.sub(spenderAllowance, _amount);
allowances[_src][spender] = newAllowance;
emit Approval(_src, spender, newAllowance);
}
_transferTokens(_src, _dst, _amount);
return true;
}
/**
* @dev Delegate votes from `msg.sender` to `delegatee`
* @param _delegatee The address to delegate votes to
*/
function delegate(address _delegatee) public {
return _delegate(msg.sender, _delegatee);
}
/**
* @notice Determine the prior number of votes for an account as of a block number. Counts the delegated votes as voting power.
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param _account The address of the account to check
* @param _blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address _account, uint _blockNumber) public view returns (uint256) {
require(_blockNumber < block.number, "AMS::getPriorVotes: not yet determined");
uint256 nCheckpoints = numCheckpoints[_account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[_account][nCheckpoints - 1].fromBlock <= _blockNumber) {
return checkpoints[_account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[_account][0].fromBlock > _blockNumber) {
return 0;
}
uint256 lower = 0;
uint256 upper = nCheckpoints - 1;
while (upper > lower) {
uint256 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[_account][center];
if (cp.fromBlock == _blockNumber) {
return cp.votes;
} else if (cp.fromBlock < _blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[_account][lower].votes;
}
function _delegate(address delegator, address delegatee) internal {
address currentDelegate = delegates[delegator];
uint256 delegatorBalance = balances[delegator];
delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _transferTokens(address src, address dst, uint256 amount) internal {
require(src != address(0), "AMS::_transferTokens: cannot transfer from the zero address");
require(dst != address(0), "AMS::_transferTokens: cannot transfer to the zero address");
balances[src] = SafeMath.sub(balances[src], amount);
balances[dst] = SafeMath.add(balances[dst], amount);
emit Transfer(src, dst, amount);
_moveDelegates(delegates[src], delegates[dst], amount);
}
function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
uint256 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint256 srcRepNew = SafeMath.sub(srcRepOld, amount);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
uint256 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint256 dstRepNew = SafeMath.add(dstRepOld, amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(address delegatee, uint256 nCheckpoints, uint256 oldVotes, uint256 newVotes) internal {
uint32 blockNumber = SafeCast.toUint32(block.number);
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
/**
* @dev Get the running network chain ID.
* @return The chain ID
*/
function _getChainID() private pure returns (uint256) {
uint256 id;
assembly {
id := chainid()
}
return id;
}
}
|
Transfer `amount` tokens from `src` to `dst` _src The address of the source account _dst The address of the destination account _amount The number of tokens to transfer return Whether or not the transfer succeeded/
|
function transferFrom(address _src, address _dst, uint _amount) external returns (bool) {
address spender = msg.sender;
uint256 spenderAllowance = allowances[_src][spender];
if (spender != _src && spenderAllowance != uint256(-1)) {
uint256 newAllowance = SafeMath.sub(spenderAllowance, _amount);
allowances[_src][spender] = newAllowance;
emit Approval(_src, spender, newAllowance);
}
_transferTokens(_src, _dst, _amount);
return true;
}
| 984,729 |
pragma solidity ^0.4.15;
contract ETHLotteryManagerInterface {
function register();
}
contract ETHLotteryInterface {
function accumulate();
}
contract ETHLottery {
bytes32 public name = 'ETHLottery - Last 1 Byte Lottery';
address public manager_address;
address public owner;
bool public open;
uint256 public jackpot;
uint256 public fee;
uint256 public owner_fee;
uint256 public create_block;
uint256 public result_block;
uint256 public winners_count;
bytes32 public result_hash;
bytes1 public result;
address public accumulated_from;
address public accumulate_to;
mapping (bytes1 => address[]) bettings;
mapping (address => uint256) credits;
event Balance(uint256 _balance);
event Result(bytes1 _result);
event Open(bool _open);
event Play(address indexed _sender, bytes1 _byte, uint256 _time);
event Withdraw(address indexed _sender, uint256 _amount, uint256 _time);
event Destroy();
event Accumulate(address _accumulate_to, uint256 _amount);
function ETHLottery(address _manager, uint256 _fee, uint256 _jackpot, uint256 _owner_fee, address _accumulated_from) {
owner = msg.sender;
open = true;
create_block = block.number;
manager_address = _manager;
fee = _fee;
jackpot = _jackpot;
owner_fee = _owner_fee;
// accumulate
if (_accumulated_from != owner) {
accumulated_from = _accumulated_from;
ETHLotteryInterface lottery = ETHLotteryInterface(accumulated_from);
lottery.accumulate();
}
// register with manager
ETHLotteryManagerInterface manager = ETHLotteryManagerInterface(manager_address);
manager.register();
Open(open);
}
modifier isOwner() {
require(msg.sender == owner);
_;
}
modifier isOriginalOwner() {
// used tx.origin on purpose instead of
// msg.sender, as we want to get the original
// starter of the transaction to be owner
require(tx.origin == owner);
_;
}
modifier isOpen() {
require(open);
_;
}
modifier isClosed() {
require(!open);
_;
}
modifier isPaid() {
require(msg.value >= fee);
_;
}
modifier hasPrize() {
require(credits[msg.sender] > 0);
_;
}
modifier isAccumulated() {
require(result_hash != 0 && winners_count == 0);
_;
}
modifier hasResultHash() {
require(
block.number >= result_block &&
block.number <= result_block + 256 &&
block.blockhash(result_block) != result_hash
);
_;
}
function play(bytes1 _byte) payable isOpen isPaid returns (bool) {
bettings[_byte].push(msg.sender);
if (this.balance >= jackpot) {
uint256 owner_fee_amount = (this.balance * owner_fee) / 100;
// this is the transaction which
// will generate the block used
// to count until the 10th in order
// to get the lottery result.
if (!owner.send(owner_fee_amount)) {
return false;
}
open = false;
// block offset hardcoded to 10
result_block = block.number + 10;
Open(open);
}
Balance(this.balance);
Play(msg.sender, _byte, now);
return true;
}
// This method is only used if we miss the 256th block
// containing the result hash, lottery() should be used instead
// this method as this is duplicated from lottery()
function manual_lottery(bytes32 _result_hash) isClosed isOwner {
result_hash = _result_hash;
result = result_hash[31];
address[] storage winners = bettings[result];
winners_count = winners.length;
if (winners_count > 0) {
uint256 credit = this.balance / winners_count;
for (uint256 i = 0; i < winners_count; i++) {
credits[winners[i]] = credit;
}
}
Result(result);
}
function lottery() isClosed hasResultHash isOwner {
result_hash = block.blockhash(result_block);
// get last byte (31st) from block hash as result
result = result_hash[31];
address[] storage winners = bettings[result];
winners_count = winners.length;
if (winners_count > 0) {
uint256 credit = this.balance / winners_count;
for (uint256 i = 0; i < winners_count; i++) {
credits[winners[i]] = credit;
}
}
Result(result);
}
function withdraw() isClosed hasPrize returns (bool) {
uint256 credit = credits[msg.sender];
// zero credit before send preventing re-entrancy
// as msg.sender can be a contract and call us back
credits[msg.sender] = 0;
if (!msg.sender.send(credit)) {
// transfer failed, return credit for withdraw
credits[msg.sender] = credit;
return false;
}
Withdraw(msg.sender, credit, now);
return true;
}
function accumulate() isOriginalOwner isClosed isAccumulated {
accumulate_to = msg.sender;
if (msg.sender.send(this.balance)) {
Accumulate(msg.sender, this.balance);
}
}
function destruct() isClosed isOwner {
Destroy();
selfdestruct(owner);
}
}
|
This method is only used if we miss the 256th block containing the result hash, lottery() should be used instead this method as this is duplicated from lottery()
|
function manual_lottery(bytes32 _result_hash) isClosed isOwner {
result_hash = _result_hash;
result = result_hash[31];
address[] storage winners = bettings[result];
winners_count = winners.length;
if (winners_count > 0) {
uint256 credit = this.balance / winners_count;
for (uint256 i = 0; i < winners_count; i++) {
credits[winners[i]] = credit;
}
}
Result(result);
}
| 13,010,166 |
// 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.10;
import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import './interfaces/IBridgePool.sol';
contract BridgePool is IBridgePool {
address public owner;
/*
operator modes:
1 - contract:creator
2 - contract:withdrawer
4 - withdrawer
8 - taker
*/
mapping(address => uint8) public operator;
mapping(bytes32 => bool) public withdrawn;
bool private entered = false;
modifier nonReentrant() {
require(!entered, 'reentrant call');
entered = true;
_;
entered = false;
}
constructor () {
owner = tx.origin;
}
function setOwner(address newOwner) external {
require(msg.sender == owner, 'forbidden');
owner = newOwner;
}
function setOperatorMode(address account, uint8 mode) external {
require(msg.sender == owner, 'forbidden');
operator[account] = mode;
}
function deposit(IERC20 token, uint amount, uint8 to, bool bonus, bytes calldata recipient) override external payable nonReentrant() {
// allowed only direct call or 'contract:creator' or 'contract:withdrawer'
require(tx.origin == msg.sender || (operator[msg.sender] & (1 | 2) > 0), 'call from unauthorized contract');
require(address(token) != address(0) && amount > 0 && recipient.length > 0, 'invalid input');
if (address(token) == address(1)) {
require(amount == msg.value, 'value must equal amount');
} else {
safeTransferFrom(token, msg.sender, address(this), amount);
}
emit Deposited(msg.sender, address(token), to, amount, bonus, recipient);
}
function withdraw(Withdraw[] calldata ws) override external nonReentrant() {
// allowed only 'withdrawer' or 'withdrawer' through 'contract:withdrawer'
require(operator[msg.sender] == 4 || (operator[tx.origin] == 4 && operator[msg.sender] == 2), 'forbidden');
for (uint i = 0; i < ws.length; i++) {
Withdraw memory w = ws[i];
require(!withdrawn[w.id], 'already withdrawn');
withdrawn[w.id] = true;
if (address(w.token) == address(1)) {
require(address(this).balance >= w.amount + w.bonus, 'too low token balance');
(bool success, ) = w.recipient.call{value: w.amount}('');
require(success, 'native transfer error');
} else {
require(
w.token.balanceOf(address(this)) >= w.amount && address(this).balance >= w.bonus,
'too low token balance'
);
safeTransfer(w.token, w.recipient, w.amount);
}
if (w.bonus > 0) {
// may fail on contracts
w.recipient.call{value: w.bonus}('');
}
if (address(w.token) != address(1) && w.feeAmounts.length > 0) {
for (uint j = 0; j < w.feeAmounts.length; j++) {
require(w.token.balanceOf(address(this)) >= w.feeAmounts[i], 'too low token balance');
safeTransfer(w.token, w.feeTargets[i], w.feeAmounts[i]);
}
}
emit Withdrawn(w.id, address(w.token), w.recipient, w.amount);
}
}
function take(IERC20 token, uint amount, address payable to) external override nonReentrant() {
// allowed only 'taker'
require(operator[msg.sender] == 8, 'forbidden');
if (address(token) == address(1)) {
to.transfer(amount);
} else {
safeTransfer(token, to, amount);
}
}
receive() external payable {}
function safeTransfer(IERC20 token, address to, uint256 value) internal {
(bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(token.transfer.selector, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'transfer failed');
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
(bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'transfer failed');
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IBridgePool {
struct Withdraw {
bytes32 id;
IERC20 token;
uint amount;
uint bonus;
address payable recipient;
uint[] feeAmounts;
address[] feeTargets;
}
event Deposited(address indexed sender, address indexed token, uint8 indexed to, uint amount, bool bonus, bytes recipient);
event Withdrawn(bytes32 indexed id, address indexed token, address indexed recipient, uint amount);
function operator(address account) external view returns (uint8 mode);
function deposit(IERC20 token, uint amount, uint8 to, bool bonus, bytes calldata recipient) external payable;
function withdraw(Withdraw[] memory ws) external;
function take(IERC20 token, uint amount, address payable to) external;
}
|
allowed only 'taker'
|
function take(IERC20 token, uint amount, address payable to) external override nonReentrant() {
require(operator[msg.sender] == 8, 'forbidden');
if (address(token) == address(1)) {
to.transfer(amount);
safeTransfer(token, to, amount);
}
}
| 6,069,178 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/extensions/draft-ERC20Permit.sol";
contract DaiLikePermitMock is ERC20Permit {
// bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address holder,address spender,uint256 nonce,uint256 expiry,bool allowed)");
bytes32 public constant PERMIT_TYPEHASH = 0xea2aa0a1be11a07ed86d755c93467f4f82362b452371d1ba94d1715123511acb;
constructor(
string memory name,
string memory symbol,
address initialAccount,
uint256 initialBalance
) payable ERC20(name, symbol) ERC20Permit(name) {
_mint(initialAccount, initialBalance);
}
function permit(address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s) external
{
bytes32 digest =
keccak256(abi.encodePacked(
"\x19\x01",
this.DOMAIN_SEPARATOR(),
keccak256(abi.encode(PERMIT_TYPEHASH,
holder,
spender,
nonce,
expiry,
allowed))
));
require(holder != address(0), "Dai/invalid-address-0");
require(holder == ecrecover(digest, v, r, s), "Dai/invalid-permit");
// solhint-disable-next-line not-rely-on-time
require(expiry == 0 || block.timestamp <= expiry, "Dai/permit-expired");
require(nonce == nonces(holder), "Dai/invalid-nonce");
_useNonce(holder);
uint wad = allowed ? type(uint128).max : 0;
_approve(holder, spender, wad);
emit Approval(holder, spender, wad);
}
}
|
solhint-disable-next-line not-rely-on-time
|
function permit(address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s) external
{
bytes32 digest =
keccak256(abi.encodePacked(
"\x19\x01",
this.DOMAIN_SEPARATOR(),
keccak256(abi.encode(PERMIT_TYPEHASH,
holder,
spender,
nonce,
expiry,
allowed))
));
require(holder != address(0), "Dai/invalid-address-0");
require(holder == ecrecover(digest, v, r, s), "Dai/invalid-permit");
require(expiry == 0 || block.timestamp <= expiry, "Dai/permit-expired");
require(nonce == nonces(holder), "Dai/invalid-nonce");
_useNonce(holder);
uint wad = allowed ? type(uint128).max : 0;
_approve(holder, spender, wad);
emit Approval(holder, spender, wad);
}
| 12,979,845 |
/*
The MIT License (MIT)
Copyright 2017 - 2018, Alchemy Limited, LLC and Smart Contract Solutions.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
pragma solidity ^0.4.21;
/**
* Reference: https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/math/SafeMath.sol
*
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/* end SafeMath library */
/// @title Math operation when both numbers has decimal places.
/// @notice Use this contract when both numbers has 18 decimal places.
contract FixedMath {
using SafeMath for uint;
uint constant internal METDECIMALS = 18;
uint constant internal METDECMULT = 10 ** METDECIMALS;
uint constant internal DECIMALS = 18;
uint constant internal DECMULT = 10 ** DECIMALS;
/// @notice Multiplication.
function fMul(uint x, uint y) internal pure returns (uint) {
return (x.mul(y)).div(DECMULT);
}
/// @notice Division.
function fDiv(uint numerator, uint divisor) internal pure returns (uint) {
return (numerator.mul(DECMULT)).div(divisor);
}
/// @notice Square root.
/// @dev Reference: https://stackoverflow.com/questions/3766020/binary-search-to-compute-square-root-java
function fSqrt(uint n) internal pure returns (uint) {
if (n == 0) {
return 0;
}
uint z = n * n;
require(z / n == n);
uint high = fAdd(n, DECMULT);
uint low = 0;
while (fSub(high, low) > 1) {
uint mid = fAdd(low, high) / 2;
if (fSqr(mid) <= n) {
low = mid;
} else {
high = mid;
}
}
return low;
}
/// @notice Square.
function fSqr(uint n) internal pure returns (uint) {
return fMul(n, n);
}
/// @notice Add.
function fAdd(uint x, uint y) internal pure returns (uint) {
return x.add(y);
}
/// @notice Sub.
function fSub(uint x, uint y) internal pure returns (uint) {
return x.sub(y);
}
}
/// @title A formula contract for converter
contract Formula is FixedMath {
/// @notice Trade in reserve(ETH/MET) and mint new smart tokens
/// @param smartTokenSupply Total supply of smart token
/// @param reserveTokensSent Amount of token sent by caller
/// @param reserveTokenBalance Balance of reserve token in the contract
/// @return Smart token minted
function returnForMint(uint smartTokenSupply, uint reserveTokensSent, uint reserveTokenBalance)
internal pure returns (uint)
{
uint s = smartTokenSupply;
uint e = reserveTokensSent;
uint r = reserveTokenBalance;
/// smartToken for mint(T) = S * (sqrt(1 + E/R) - 1)
/// DECMULT is same as 1 for values with 18 decimal places
return ((fMul(s, (fSub(fSqrt(fAdd(DECMULT, fDiv(e, r))), DECMULT)))).mul(METDECMULT)).div(DECMULT);
}
/// @notice Redeem smart tokens, get back reserve(ETH/MET) token
/// @param smartTokenSupply Total supply of smart token
/// @param smartTokensSent Smart token sent
/// @param reserveTokenBalance Balance of reserve token in the contract
/// @return Reserve token redeemed
function returnForRedemption(uint smartTokenSupply, uint smartTokensSent, uint reserveTokenBalance)
internal pure returns (uint)
{
uint s = smartTokenSupply;
uint t = smartTokensSent;
uint r = reserveTokenBalance;
/// reserveToken (E) = R * (1 - (1 - T/S)**2)
/// DECMULT is same as 1 for values with 18 decimal places
return ((fMul(r, (fSub(DECMULT, fSqr(fSub(DECMULT, fDiv(t, s))))))).mul(METDECMULT)).div(DECMULT);
}
}
/// @title Pricer contract to calculate descending price during auction.
contract Pricer {
using SafeMath for uint;
uint constant internal METDECIMALS = 18;
uint constant internal METDECMULT = 10 ** METDECIMALS;
uint public minimumPrice = 33*10**11;
uint public minimumPriceInDailyAuction = 1;
uint public tentimes;
uint public hundredtimes;
uint public thousandtimes;
uint constant public MULTIPLIER = 1984320568*10**5;
/// @notice Pricer constructor, calculate 10, 100 and 1000 times of 0.99.
function initPricer() public {
uint x = METDECMULT;
uint i;
/// Calculate 10 times of 0.99
for (i = 0; i < 10; i++) {
x = x.mul(99).div(100);
}
tentimes = x;
x = METDECMULT;
/// Calculate 100 times of 0.99 using tentimes calculated above.
/// tentimes has 18 decimal places and due to this METDECMLT is
/// used as divisor.
for (i = 0; i < 10; i++) {
x = x.mul(tentimes).div(METDECMULT);
}
hundredtimes = x;
x = METDECMULT;
/// Calculate 1000 times of 0.99 using hundredtimes calculated above.
/// hundredtimes has 18 decimal places and due to this METDECMULT is
/// used as divisor.
for (i = 0; i < 10; i++) {
x = x.mul(hundredtimes).div(METDECMULT);
}
thousandtimes = x;
}
/// @notice Price of MET at nth minute out during operational auction
/// @param initialPrice The starting price ie last purchase price
/// @param _n The number of minutes passed since last purchase
/// @return The resulting price
function priceAt(uint initialPrice, uint _n) public view returns (uint price) {
uint mult = METDECMULT;
uint i;
uint n = _n;
/// If quotient of n/1000 is greater than 0 then calculate multiplier by
/// multiplying thousandtimes and mult in a loop which runs quotient times.
/// Also assign new value to n which is remainder of n/1000.
if (n / 1000 > 0) {
for (i = 0; i < n / 1000; i++) {
mult = mult.mul(thousandtimes).div(METDECMULT);
}
n = n % 1000;
}
/// If quotient of n/100 is greater than 0 then calculate multiplier by
/// multiplying hundredtimes and mult in a loop which runs quotient times.
/// Also assign new value to n which is remainder of n/100.
if (n / 100 > 0) {
for (i = 0; i < n / 100; i++) {
mult = mult.mul(hundredtimes).div(METDECMULT);
}
n = n % 100;
}
/// If quotient of n/10 is greater than 0 then calculate multiplier by
/// multiplying tentimes and mult in a loop which runs quotient times.
/// Also assign new value to n which is remainder of n/10.
if (n / 10 > 0) {
for (i = 0; i < n / 10; i++) {
mult = mult.mul(tentimes).div(METDECMULT);
}
n = n % 10;
}
/// Calculate multiplier by multiplying 0.99 and mult, repeat it n times.
for (i = 0; i < n; i++) {
mult = mult.mul(99).div(100);
}
/// price is calculated as initialPrice multiplied by 0.99 and that too _n times.
/// Here mult is METDECMULT multiplied by 0.99 and that too _n times.
price = initialPrice.mul(mult).div(METDECMULT);
if (price < minimumPriceInDailyAuction) {
price = minimumPriceInDailyAuction;
}
}
/// @notice Price of MET at nth minute during initial auction.
/// @param lastPurchasePrice The price of MET in last transaction
/// @param numTicks The number of minutes passed since last purchase
/// @return The resulting price
function priceAtInitialAuction(uint lastPurchasePrice, uint numTicks) public view returns (uint price) {
/// Price will decrease linearly every minute by the factor of MULTIPLIER.
/// If lastPurchasePrice is greater than decrease in price then calculated the price.
/// Return minimumPrice, if calculated price is less than minimumPrice.
/// If decrease in price is more than lastPurchasePrice then simply return the minimumPrice.
if (lastPurchasePrice > MULTIPLIER.mul(numTicks)) {
price = lastPurchasePrice.sub(MULTIPLIER.mul(numTicks));
}
if (price < minimumPrice) {
price = minimumPrice;
}
}
}
/// @dev Reference: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md
/// @notice ERC20 standard interface
interface ERC20 {
function totalSupply() public constant returns (uint256);
function balanceOf(address _owner) public constant returns (uint256);
function allowance(address _owner, address _spender) public constant returns (uint256);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
function transfer(address _to, uint256 _value) public returns (bool);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
function approve(address _spender, uint256 _value) public returns (bool);
}
/// @title Ownable
contract Ownable {
address public owner;
event OwnershipChanged(address indexed prevOwner, address indexed newOwner);
function Ownable() public {
owner = msg.sender;
}
/// @dev Throws if called by any account other than the owner.
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/// @notice Allows the current owner to transfer control of the contract to a newOwner.
/// @param _newOwner
/// @return true/false
function changeOwnership(address _newOwner) public onlyOwner returns (bool) {
require(_newOwner != address(0));
require(_newOwner != owner);
emit OwnershipChanged(owner, _newOwner);
owner = _newOwner;
return true;
}
}
/// @title Owned
contract Owned is Ownable {
address public newOwner;
/// @notice Allows the current owner to transfer control of the contract to a newOwner.
/// @param _newOwner
/// @return true/false
function changeOwnership(address _newOwner) public onlyOwner returns (bool) {
require(_newOwner != owner);
newOwner = _newOwner;
return true;
}
/// @notice Allows the new owner to accept ownership of the contract.
/// @return true/false
function acceptOwnership() public returns (bool) {
require(msg.sender == newOwner);
emit OwnershipChanged(owner, newOwner);
owner = newOwner;
return true;
}
}
/// @title Mintable contract to allow minting and destroy.
contract Mintable is Owned {
using SafeMath for uint256;
event Mint(address indexed _to, uint _value);
event Destroy(address indexed _from, uint _value);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
uint256 internal _totalSupply;
mapping(address => uint256) internal _balanceOf;
address public autonomousConverter;
address public minter;
ITokenPorter public tokenPorter;
/// @notice init reference of other contract and initial supply
/// @param _autonomousConverter
/// @param _minter
/// @param _initialSupply
/// @param _decmult Decimal places
function initMintable(address _autonomousConverter, address _minter, uint _initialSupply,
uint _decmult) public onlyOwner {
require(autonomousConverter == 0x0 && _autonomousConverter != 0x0);
require(minter == 0x0 && _minter != 0x0);
autonomousConverter = _autonomousConverter;
minter = _minter;
_totalSupply = _initialSupply.mul(_decmult);
_balanceOf[_autonomousConverter] = _totalSupply;
}
function totalSupply() public constant returns (uint256) {
return _totalSupply;
}
function balanceOf(address _owner) public constant returns (uint256) {
return _balanceOf[_owner];
}
/// @notice set address of token porter
/// @param _tokenPorter address of token porter
function setTokenPorter(address _tokenPorter) public onlyOwner returns (bool) {
require(_tokenPorter != 0x0);
tokenPorter = ITokenPorter(_tokenPorter);
return true;
}
/// @notice allow minter and tokenPorter to mint token and assign to address
/// @param _to
/// @param _value Amount to be minted
function mint(address _to, uint _value) public returns (bool) {
require(msg.sender == minter || msg.sender == address(tokenPorter));
_balanceOf[_to] = _balanceOf[_to].add(_value);
_totalSupply = _totalSupply.add(_value);
emit Mint(_to, _value);
emit Transfer(0x0, _to, _value);
return true;
}
/// @notice allow autonomousConverter and tokenPorter to mint token and assign to address
/// @param _from
/// @param _value Amount to be destroyed
function destroy(address _from, uint _value) public returns (bool) {
require(msg.sender == autonomousConverter || msg.sender == address(tokenPorter));
_balanceOf[_from] = _balanceOf[_from].sub(_value);
_totalSupply = _totalSupply.sub(_value);
emit Destroy(_from, _value);
emit Transfer(_from, 0x0, _value);
return true;
}
}
/// @title Token contract
contract Token is ERC20, Mintable {
mapping(address => mapping(address => uint256)) internal _allowance;
function initToken(address _autonomousConverter, address _minter,
uint _initialSupply, uint _decmult) public onlyOwner {
initMintable(_autonomousConverter, _minter, _initialSupply, _decmult);
}
/// @notice Provide allowance information
function allowance(address _owner, address _spender) public constant returns (uint256) {
return _allowance[_owner][_spender];
}
/// @notice Transfer tokens from sender to the provided address.
/// @param _to Receiver of the tokens
/// @param _value Amount of token
/// @return true/false
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_to != minter);
require(_to != address(this));
require(_to != autonomousConverter);
Proceeds proceeds = Auctions(minter).proceeds();
require((_to != address(proceeds)));
_balanceOf[msg.sender] = _balanceOf[msg.sender].sub(_value);
_balanceOf[_to] = _balanceOf[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/// @notice Transfer tokens based on allowance.
/// msg.sender must have allowance for spending the tokens from owner ie _from
/// @param _from Owner of the tokens
/// @param _to Receiver of the tokens
/// @param _value Amount of tokens to transfer
/// @return true/false
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_to != minter && _from != minter);
require(_to != address(this) && _from != address(this));
Proceeds proceeds = Auctions(minter).proceeds();
require(_to != address(proceeds) && _from != address(proceeds));
//AC can accept MET via this function, needed for MetToEth conversion
require(_from != autonomousConverter);
require(_allowance[_from][msg.sender] >= _value);
_balanceOf[_from] = _balanceOf[_from].sub(_value);
_balanceOf[_to] = _balanceOf[_to].add(_value);
_allowance[_from][msg.sender] = _allowance[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/// @notice Approve spender to spend the tokens ie approve allowance
/// @param _spender Spender of the tokens
/// @param _value Amount of tokens that can be spent by spender
/// @return true/false
function approve(address _spender, uint256 _value) public returns (bool) {
require(_spender != address(this));
_allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/// @notice Transfer the tokens from sender to all the address provided in the array.
/// @dev Left 160 bits are the recipient address and the right 96 bits are the token amount.
/// @param bits array of uint
/// @return true/false
function multiTransfer(uint[] bits) public returns (bool) {
for (uint i = 0; i < bits.length; i++) {
address a = address(bits[i] >> 96);
uint amount = bits[i] & ((1 << 96) - 1);
if (!transfer(a, amount)) revert();
}
return true;
}
/// @notice Increase allowance of spender
/// @param _spender Spender of the tokens
/// @param _value Amount of tokens that can be spent by spender
/// @return true/false
function approveMore(address _spender, uint256 _value) public returns (bool) {
uint previous = _allowance[msg.sender][_spender];
uint newAllowance = previous.add(_value);
_allowance[msg.sender][_spender] = newAllowance;
emit Approval(msg.sender, _spender, newAllowance);
return true;
}
/// @notice Decrease allowance of spender
/// @param _spender Spender of the tokens
/// @param _value Amount of tokens that can be spent by spender
/// @return true/false
function approveLess(address _spender, uint256 _value) public returns (bool) {
uint previous = _allowance[msg.sender][_spender];
uint newAllowance = previous.sub(_value);
_allowance[msg.sender][_spender] = newAllowance;
emit Approval(msg.sender, _spender, newAllowance);
return true;
}
}
/// @title Smart tokens are an intermediate token generated during conversion of MET-ETH
contract SmartToken is Mintable {
uint constant internal METDECIMALS = 18;
uint constant internal METDECMULT = 10 ** METDECIMALS;
function initSmartToken(address _autonomousConverter, address _minter, uint _initialSupply) public onlyOwner {
initMintable(_autonomousConverter, _minter, _initialSupply, METDECMULT);
}
}
/// @title ERC20 token. Metronome token
contract METToken is Token {
string public constant name = "Metronome";
string public constant symbol = "MET";
uint8 public constant decimals = 18;
bool public transferAllowed;
function initMETToken(address _autonomousConverter, address _minter,
uint _initialSupply, uint _decmult) public onlyOwner {
initToken(_autonomousConverter, _minter, _initialSupply, _decmult);
}
/// @notice Transferable modifier to allow transfer only after initial auction ended.
modifier transferable() {
require(transferAllowed);
_;
}
function enableMETTransfers() public returns (bool) {
require(!transferAllowed && Auctions(minter).isInitialAuctionEnded());
transferAllowed = true;
return true;
}
/// @notice Transfer tokens from caller to another address
/// @param _to address The address which you want to transfer to
/// @param _value uint256 the amout of tokens to be transfered
function transfer(address _to, uint256 _value) public transferable returns (bool) {
return super.transfer(_to, _value);
}
/// @notice Transfer tokens from one address to another
/// @param _from address The address from which you want to transfer
/// @param _to address The address which you want to transfer to
/// @param _value uint256 the amout of tokens to be transfered
function transferFrom(address _from, address _to, uint256 _value) public transferable returns (bool) {
return super.transferFrom(_from, _to, _value);
}
/// @notice Transfer the token from sender to all the addresses provided in array.
/// @dev Left 160 bits are the recipient address and the right 96 bits are the token amount.
/// @param bits array of uint
/// @return true/false
function multiTransfer(uint[] bits) public transferable returns (bool) {
return super.multiTransfer(bits);
}
mapping (address => bytes32) public roots;
function setRoot(bytes32 data) public {
roots[msg.sender] = data;
}
function getRoot(address addr) public view returns (bytes32) {
return roots[addr];
}
function rootsMatch(address a, address b) public view returns (bool) {
return roots[a] == roots[b];
}
/// @notice import MET tokens from another chain to this chain.
/// @param _destinationChain destination chain name
/// @param _addresses _addresses[0] is destMetronomeAddr and _addresses[1] is recipientAddr
/// @param _extraData extra information for import
/// @param _burnHashes _burnHashes[0] is previous burnHash, _burnHashes[1] is current burnHash
/// @param _supplyOnAllChains MET supply on all supported chains
/// @param _importData _importData[0] is _blockTimestamp, _importData[1] is _amount, _importData[2] is _fee
/// _importData[3] is _burnedAtTick, _importData[4] is _genesisTime, _importData[5] is _dailyMintable
/// _importData[6] is _burnSequence, _importData[7] is _dailyAuctionStartTime
/// @param _proof proof
/// @return true/false
function importMET(bytes8 _originChain, bytes8 _destinationChain, address[] _addresses, bytes _extraData,
bytes32[] _burnHashes, uint[] _supplyOnAllChains, uint[] _importData, bytes _proof) public returns (bool)
{
require(address(tokenPorter) != 0x0);
return tokenPorter.importMET(_originChain, _destinationChain, _addresses, _extraData,
_burnHashes, _supplyOnAllChains, _importData, _proof);
}
/// @notice export MET tokens from this chain to another chain.
/// @param _destChain destination chain address
/// @param _destMetronomeAddr address of Metronome contract on the destination chain
/// where this MET will be imported.
/// @param _destRecipAddr address of account on destination chain
/// @param _amount amount
/// @param _extraData extra information for future expansion
/// @return true/false
function export(bytes8 _destChain, address _destMetronomeAddr, address _destRecipAddr, uint _amount, uint _fee,
bytes _extraData) public returns (bool)
{
require(address(tokenPorter) != 0x0);
return tokenPorter.export(msg.sender, _destChain, _destMetronomeAddr,
_destRecipAddr, _amount, _fee, _extraData);
}
struct Sub {
uint startTime;
uint payPerWeek;
uint lastWithdrawTime;
}
event LogSubscription(address indexed subscriber, address indexed subscribesTo);
event LogCancelSubscription(address indexed subscriber, address indexed subscribesTo);
mapping (address => mapping (address => Sub)) public subs;
/// @notice subscribe for a weekly recurring payment
/// @param _startTime Subscription start time.
/// @param _payPerWeek weekly payment
/// @param _recipient address of beneficiary
/// @return true/false
function subscribe(uint _startTime, uint _payPerWeek, address _recipient) public returns (bool) {
require(_startTime >= block.timestamp);
require(_payPerWeek != 0);
require(_recipient != 0);
subs[msg.sender][_recipient] = Sub(_startTime, _payPerWeek, _startTime);
emit LogSubscription(msg.sender, _recipient);
return true;
}
/// @notice cancel a subcription.
/// @param _recipient address of beneficiary
/// @return true/false
function cancelSubscription(address _recipient) public returns (bool) {
require(subs[msg.sender][_recipient].startTime != 0);
require(subs[msg.sender][_recipient].payPerWeek != 0);
subs[msg.sender][_recipient].startTime = 0;
subs[msg.sender][_recipient].payPerWeek = 0;
subs[msg.sender][_recipient].lastWithdrawTime = 0;
emit LogCancelSubscription(msg.sender, _recipient);
return true;
}
/// @notice get subcription details
/// @param _owner
/// @param _recipient
/// @return startTime, payPerWeek, lastWithdrawTime
function getSubscription(address _owner, address _recipient) public constant
returns (uint startTime, uint payPerWeek, uint lastWithdrawTime)
{
Sub storage sub = subs[_owner][_recipient];
return (
sub.startTime,
sub.payPerWeek,
sub.lastWithdrawTime
);
}
/// @notice caller can withdraw the token from subscribers.
/// @param _owner subcriber
/// @return true/false
function subWithdraw(address _owner) public transferable returns (bool) {
require(subWithdrawFor(_owner, msg.sender));
return true;
}
/// @notice Allow callers to withdraw token in one go from all of its subscribers
/// @param _owners array of address of subscribers
/// @return number of successful transfer done
function multiSubWithdraw(address[] _owners) public returns (uint) {
uint n = 0;
for (uint i=0; i < _owners.length; i++) {
if (subWithdrawFor(_owners[i], msg.sender)) {
n++;
}
}
return n;
}
/// @notice Trigger MET token transfers for all pairs of subscribers and beneficiaries
/// @dev address at i index in owners and recipients array is subcriber-beneficiary pair.
/// @param _owners
/// @param _recipients
/// @return number of successful transfer done
function multiSubWithdrawFor(address[] _owners, address[] _recipients) public returns (uint) {
// owners and recipients need 1-to-1 mapping, must be same length
require(_owners.length == _recipients.length);
uint n = 0;
for (uint i = 0; i < _owners.length; i++) {
if (subWithdrawFor(_owners[i], _recipients[i])) {
n++;
}
}
return n;
}
function subWithdrawFor(address _from, address _to) internal returns (bool) {
Sub storage sub = subs[_from][_to];
if (sub.startTime > 0 && sub.startTime < block.timestamp && sub.payPerWeek > 0) {
uint weekElapsed = (now.sub(sub.lastWithdrawTime)).div(7 days);
uint amount = weekElapsed.mul(sub.payPerWeek);
if (weekElapsed > 0 && _balanceOf[_from] >= amount) {
subs[_from][_to].lastWithdrawTime = block.timestamp;
_balanceOf[_from] = _balanceOf[_from].sub(amount);
_balanceOf[_to] = _balanceOf[_to].add(amount);
emit Transfer(_from, _to, amount);
return true;
}
}
return false;
}
}
/// @title Autonomous Converter contract for MET <=> ETH exchange
contract AutonomousConverter is Formula, Owned {
SmartToken public smartToken;
METToken public reserveToken;
Auctions public auctions;
enum WhichToken { Eth, Met }
bool internal initialized = false;
event LogFundsIn(address indexed from, uint value);
event ConvertEthToMet(address indexed from, uint eth, uint met);
event ConvertMetToEth(address indexed from, uint eth, uint met);
function init(address _reserveToken, address _smartToken, address _auctions)
public onlyOwner payable
{
require(!initialized);
auctions = Auctions(_auctions);
reserveToken = METToken(_reserveToken);
smartToken = SmartToken(_smartToken);
initialized = true;
}
function handleFund() public payable {
require(msg.sender == address(auctions.proceeds()));
emit LogFundsIn(msg.sender, msg.value);
}
function getMetBalance() public view returns (uint) {
return balanceOf(WhichToken.Met);
}
function getEthBalance() public view returns (uint) {
return balanceOf(WhichToken.Eth);
}
/// @notice return the expected MET for ETH
/// @param _depositAmount ETH.
/// @return expected MET value for ETH
function getMetForEthResult(uint _depositAmount) public view returns (uint256) {
return convertingReturn(WhichToken.Eth, _depositAmount);
}
/// @notice return the expected ETH for MET
/// @param _depositAmount MET.
/// @return expected ETH value for MET
function getEthForMetResult(uint _depositAmount) public view returns (uint256) {
return convertingReturn(WhichToken.Met, _depositAmount);
}
/// @notice send ETH and get MET
/// @param _mintReturn execute conversion only if return is equal or more than _mintReturn
/// @return returnedMet MET retured after conversion
function convertEthToMet(uint _mintReturn) public payable returns (uint returnedMet) {
returnedMet = convert(WhichToken.Eth, _mintReturn, msg.value);
emit ConvertEthToMet(msg.sender, msg.value, returnedMet);
}
/// @notice send MET and get ETH
/// @dev Caller will be required to approve the AutonomousConverter to initiate the transfer
/// @param _amount MET amount
/// @param _mintReturn execute conversion only if return is equal or more than _mintReturn
/// @return returnedEth ETh returned after conversion
function convertMetToEth(uint _amount, uint _mintReturn) public returns (uint returnedEth) {
returnedEth = convert(WhichToken.Met, _mintReturn, _amount);
emit ConvertMetToEth(msg.sender, returnedEth, _amount);
}
function balanceOf(WhichToken which) internal view returns (uint) {
if (which == WhichToken.Eth) return address(this).balance;
if (which == WhichToken.Met) return reserveToken.balanceOf(this);
revert();
}
function convertingReturn(WhichToken whichFrom, uint _depositAmount) internal view returns (uint256) {
WhichToken to = WhichToken.Met;
if (whichFrom == WhichToken.Met) {
to = WhichToken.Eth;
}
uint reserveTokenBalanceFrom = balanceOf(whichFrom).add(_depositAmount);
uint mintRet = returnForMint(smartToken.totalSupply(), _depositAmount, reserveTokenBalanceFrom);
uint newSmartTokenSupply = smartToken.totalSupply().add(mintRet);
uint reserveTokenBalanceTo = balanceOf(to);
return returnForRedemption(
newSmartTokenSupply,
mintRet,
reserveTokenBalanceTo);
}
function convert(WhichToken whichFrom, uint _minReturn, uint amnt) internal returns (uint) {
WhichToken to = WhichToken.Met;
if (whichFrom == WhichToken.Met) {
to = WhichToken.Eth;
require(reserveToken.transferFrom(msg.sender, this, amnt));
}
uint mintRet = mint(whichFrom, amnt, 1);
return redeem(to, mintRet, _minReturn);
}
function mint(WhichToken which, uint _depositAmount, uint _minReturn) internal returns (uint256 amount) {
require(_minReturn > 0);
amount = mintingReturn(which, _depositAmount);
require(amount >= _minReturn);
require(smartToken.mint(msg.sender, amount));
}
function mintingReturn(WhichToken which, uint _depositAmount) internal view returns (uint256) {
uint256 smartTokenSupply = smartToken.totalSupply();
uint256 reserveBalance = balanceOf(which);
return returnForMint(smartTokenSupply, _depositAmount, reserveBalance);
}
function redeem(WhichToken which, uint _amount, uint _minReturn) internal returns (uint redeemable) {
require(_amount <= smartToken.balanceOf(msg.sender));
require(_minReturn > 0);
redeemable = redemptionReturn(which, _amount);
require(redeemable >= _minReturn);
uint256 reserveBalance = balanceOf(which);
require(reserveBalance >= redeemable);
uint256 tokenSupply = smartToken.totalSupply();
require(_amount < tokenSupply);
smartToken.destroy(msg.sender, _amount);
if (which == WhichToken.Eth) {
msg.sender.transfer(redeemable);
} else {
require(reserveToken.transfer(msg.sender, redeemable));
}
}
function redemptionReturn(WhichToken which, uint smartTokensSent) internal view returns (uint256) {
uint smartTokenSupply = smartToken.totalSupply();
uint reserveTokenBalance = balanceOf(which);
return returnForRedemption(
smartTokenSupply,
smartTokensSent,
reserveTokenBalance);
}
}
/// @title Proceeds contract
contract Proceeds is Owned {
using SafeMath for uint256;
AutonomousConverter public autonomousConverter;
Auctions public auctions;
event LogProceedsIn(address indexed from, uint value);
event LogClosedAuction(address indexed from, uint value);
uint latestAuctionClosed;
function initProceeds(address _autonomousConverter, address _auctions) public onlyOwner {
require(address(auctions) == 0x0 && _auctions != 0x0);
require(address(autonomousConverter) == 0x0 && _autonomousConverter != 0x0);
autonomousConverter = AutonomousConverter(_autonomousConverter);
auctions = Auctions(_auctions);
}
function handleFund() public payable {
require(msg.sender == address(auctions));
emit LogProceedsIn(msg.sender, msg.value);
}
/// @notice Forward 0.25% of total ETH balance of proceeds to AutonomousConverter contract
function closeAuction() public {
uint lastPurchaseTick = auctions.lastPurchaseTick();
uint currentAuction = auctions.currentAuction();
uint val = ((address(this).balance).mul(25)).div(10000);
if (val > 0 && (currentAuction > auctions.whichAuction(lastPurchaseTick))
&& (latestAuctionClosed < currentAuction)) {
latestAuctionClosed = currentAuction;
autonomousConverter.handleFund.value(val)();
emit LogClosedAuction(msg.sender, val);
}
}
}
/// @title Auction contract. Send ETH to the contract address and buy MET.
contract Auctions is Pricer, Owned {
using SafeMath for uint256;
METToken public token;
Proceeds public proceeds;
address[] public founders;
mapping(address => TokenLocker) public tokenLockers;
uint internal constant DAY_IN_SECONDS = 86400;
uint internal constant DAY_IN_MINUTES = 1440;
uint public genesisTime;
uint public lastPurchaseTick;
uint public lastPurchasePrice;
uint public constant INITIAL_GLOBAL_DAILY_SUPPLY = 2880 * METDECMULT;
uint public INITIAL_FOUNDER_SUPPLY = 1999999 * METDECMULT;
uint public INITIAL_AC_SUPPLY = 1 * METDECMULT;
uint public totalMigratedOut = 0;
uint public totalMigratedIn = 0;
uint public timeScale = 1;
uint public constant INITIAL_SUPPLY = 10000000 * METDECMULT;
uint public mintable = INITIAL_SUPPLY;
uint public initialAuctionDuration = 7 days;
uint public initialAuctionEndTime;
uint public dailyAuctionStartTime;
uint public constant DAILY_PURCHASE_LIMIT = 1000 ether;
mapping (address => uint) internal purchaseInTheAuction;
mapping (address => uint) internal lastPurchaseAuction;
bool public minted;
bool public initialized;
uint public globalSupplyAfterPercentageLogic = 52598080 * METDECMULT;
uint public constant AUCTION_WHEN_PERCENTAGE_LOGIC_STARTS = 14791;
bytes8 public chain = "ETH";
event LogAuctionFundsIn(address indexed sender, uint amount, uint tokens, uint purchasePrice, uint refund);
function Auctions() public {
mintable = INITIAL_SUPPLY - 2000000 * METDECMULT;
}
/// @notice Payable function to buy MET in descending price auction
function () public payable running {
require(msg.value > 0);
uint amountForPurchase = msg.value;
uint excessAmount;
if (currentAuction() > whichAuction(lastPurchaseTick)) {
proceeds.closeAuction();
restartAuction();
}
if (isInitialAuctionEnded()) {
require(now >= dailyAuctionStartTime);
if (lastPurchaseAuction[msg.sender] < currentAuction()) {
if (amountForPurchase > DAILY_PURCHASE_LIMIT) {
excessAmount = amountForPurchase.sub(DAILY_PURCHASE_LIMIT);
amountForPurchase = DAILY_PURCHASE_LIMIT;
}
purchaseInTheAuction[msg.sender] = msg.value;
lastPurchaseAuction[msg.sender] = currentAuction();
} else {
require(purchaseInTheAuction[msg.sender] < DAILY_PURCHASE_LIMIT);
if (purchaseInTheAuction[msg.sender].add(amountForPurchase) > DAILY_PURCHASE_LIMIT) {
excessAmount = (purchaseInTheAuction[msg.sender].add(amountForPurchase)).sub(DAILY_PURCHASE_LIMIT);
amountForPurchase = amountForPurchase.sub(excessAmount);
}
purchaseInTheAuction[msg.sender] = purchaseInTheAuction[msg.sender].add(msg.value);
}
}
uint _currentTick = currentTick();
uint weiPerToken;
uint tokens;
uint refund;
(weiPerToken, tokens, refund) = calcPurchase(amountForPurchase, _currentTick);
require(tokens > 0);
if (now < initialAuctionEndTime && (token.totalSupply()).add(tokens) >= INITIAL_SUPPLY) {
initialAuctionEndTime = now;
dailyAuctionStartTime = ((initialAuctionEndTime / 1 days) + 1) * 1 days;
}
lastPurchaseTick = _currentTick;
lastPurchasePrice = weiPerToken;
assert(tokens <= mintable);
mintable = mintable.sub(tokens);
assert(refund <= amountForPurchase);
uint ethForProceeds = amountForPurchase.sub(refund);
proceeds.handleFund.value(ethForProceeds)();
require(token.mint(msg.sender, tokens));
refund = refund.add(excessAmount);
if (refund > 0) {
if (purchaseInTheAuction[msg.sender] > 0) {
purchaseInTheAuction[msg.sender] = purchaseInTheAuction[msg.sender].sub(refund);
}
msg.sender.transfer(refund);
}
emit LogAuctionFundsIn(msg.sender, ethForProceeds, tokens, lastPurchasePrice, refund);
}
modifier running() {
require(isRunning());
_;
}
function isRunning() public constant returns (bool) {
return (block.timestamp >= genesisTime && genesisTime > 0);
}
/// @notice current tick(minute) of the metronome clock
/// @return tick count
function currentTick() public view returns(uint) {
return whichTick(block.timestamp);
}
/// @notice current auction
/// @return auction count
function currentAuction() public view returns(uint) {
return whichAuction(currentTick());
}
/// @notice tick count at the timestamp t.
/// @param t timestamp
/// @return tick count
function whichTick(uint t) public view returns(uint) {
if (genesisTime > t) {
revert();
}
return (t - genesisTime) * timeScale / 1 minutes;
}
/// @notice Auction count at given the timestamp t
/// @param t timestamp
/// @return Auction count
function whichAuction(uint t) public view returns(uint) {
if (whichTick(dailyAuctionStartTime) > t) {
return 0;
} else {
return ((t - whichTick(dailyAuctionStartTime)) / DAY_IN_MINUTES) + 1;
}
}
/// @notice one single function telling everything about Metronome Auction
function heartbeat() public view returns (
bytes8 _chain,
address auctionAddr,
address convertAddr,
address tokenAddr,
uint minting,
uint totalMET,
uint proceedsBal,
uint currTick,
uint currAuction,
uint nextAuctionGMT,
uint genesisGMT,
uint currentAuctionPrice,
uint _dailyMintable,
uint _lastPurchasePrice) {
_chain = chain;
convertAddr = proceeds.autonomousConverter();
tokenAddr = token;
auctionAddr = this;
totalMET = token.totalSupply();
proceedsBal = address(proceeds).balance;
currTick = currentTick();
currAuction = currentAuction();
if (currAuction == 0) {
nextAuctionGMT = dailyAuctionStartTime;
} else {
nextAuctionGMT = (currAuction * DAY_IN_SECONDS) / timeScale + dailyAuctionStartTime;
}
genesisGMT = genesisTime;
currentAuctionPrice = currentPrice();
_dailyMintable = dailyMintable();
minting = currentMintable();
_lastPurchasePrice = lastPurchasePrice;
}
/// @notice Skip Initialization and minting if we're not the OG Metronome
/// @param _token MET token contract address
/// @param _proceeds Address of Proceeds contract
/// @param _genesisTime The block.timestamp when first auction started on OG chain
/// @param _minimumPrice Nobody can buy tokens for less than this price
/// @param _startingPrice Start price of MET when first auction starts
/// @param _timeScale time scale factor for auction. will be always 1 in live environment
/// @param _chain chain where this contract is being deployed
/// @param _initialAuctionEndTime Initial Auction end time in ETH chain.
function skipInitBecauseIAmNotOg(address _token, address _proceeds, uint _genesisTime,
uint _minimumPrice, uint _startingPrice, uint _timeScale, bytes8 _chain,
uint _initialAuctionEndTime) public onlyOwner returns (bool) {
require(!minted);
require(!initialized);
require(_timeScale != 0);
require(address(token) == 0x0 && _token != 0x0);
require(address(proceeds) == 0x0 && _proceeds != 0x0);
initPricer();
// minting substitute section
token = METToken(_token);
proceeds = Proceeds(_proceeds);
INITIAL_FOUNDER_SUPPLY = 0;
INITIAL_AC_SUPPLY = 0;
mintable = 0; //
// initial auction substitute section
genesisTime = _genesisTime;
initialAuctionEndTime = _initialAuctionEndTime;
// if initialAuctionEndTime is midnight, then daily auction will start immediately
// after initial auction.
if (initialAuctionEndTime == (initialAuctionEndTime / 1 days) * 1 days) {
dailyAuctionStartTime = initialAuctionEndTime;
} else {
dailyAuctionStartTime = ((initialAuctionEndTime / 1 days) + 1) * 1 days;
}
lastPurchaseTick = 0;
if (_minimumPrice > 0) {
minimumPrice = _minimumPrice;
}
timeScale = _timeScale;
if (_startingPrice > 0) {
lastPurchasePrice = _startingPrice * 1 ether;
} else {
lastPurchasePrice = 2 ether;
}
chain = _chain;
minted = true;
initialized = true;
return true;
}
/// @notice Initialize Auctions parameters
/// @param _startTime The block.timestamp when first auction starts
/// @param _minimumPrice Nobody can buy tokens for less than this price
/// @param _startingPrice Start price of MET when first auction starts
/// @param _timeScale time scale factor for auction. will be always 1 in live environment
function initAuctions(uint _startTime, uint _minimumPrice, uint _startingPrice, uint _timeScale)
public onlyOwner returns (bool)
{
require(minted);
require(!initialized);
require(_timeScale != 0);
initPricer();
if (_startTime > 0) {
genesisTime = (_startTime / (1 minutes)) * (1 minutes) + 60;
} else {
genesisTime = block.timestamp + 60 - (block.timestamp % 60);
}
initialAuctionEndTime = genesisTime + initialAuctionDuration;
// if initialAuctionEndTime is midnight, then daily auction will start immediately
// after initial auction.
if (initialAuctionEndTime == (initialAuctionEndTime / 1 days) * 1 days) {
dailyAuctionStartTime = initialAuctionEndTime;
} else {
dailyAuctionStartTime = ((initialAuctionEndTime / 1 days) + 1) * 1 days;
}
lastPurchaseTick = 0;
if (_minimumPrice > 0) {
minimumPrice = _minimumPrice;
}
timeScale = _timeScale;
if (_startingPrice > 0) {
lastPurchasePrice = _startingPrice * 1 ether;
} else {
lastPurchasePrice = 2 ether;
}
for (uint i = 0; i < founders.length; i++) {
TokenLocker tokenLocker = tokenLockers[founders[i]];
tokenLocker.lockTokenLocker();
}
initialized = true;
return true;
}
function createTokenLocker(address _founder, address _token) public onlyOwner {
require(_token != 0x0);
require(_founder != 0x0);
founders.push(_founder);
TokenLocker tokenLocker = new TokenLocker(address(this), _token);
tokenLockers[_founder] = tokenLocker;
tokenLocker.changeOwnership(_founder);
}
/// @notice Mint initial supply for founder and move to token locker
/// @param _founders Left 160 bits are the founder address and the right 96 bits are the token amount.
/// @param _token MET token contract address
/// @param _proceeds Address of Proceeds contract
function mintInitialSupply(uint[] _founders, address _token,
address _proceeds, address _autonomousConverter) public onlyOwner returns (bool)
{
require(!minted);
require(_founders.length != 0);
require(address(token) == 0x0 && _token != 0x0);
require(address(proceeds) == 0x0 && _proceeds != 0x0);
require(_autonomousConverter != 0x0);
token = METToken(_token);
proceeds = Proceeds(_proceeds);
// _founders will be minted into individual token lockers
uint foundersTotal;
for (uint i = 0; i < _founders.length; i++) {
address addr = address(_founders[i] >> 96);
require(addr != 0x0);
uint amount = _founders[i] & ((1 << 96) - 1);
require(amount > 0);
TokenLocker tokenLocker = tokenLockers[addr];
require(token.mint(address(tokenLocker), amount));
tokenLocker.deposit(addr, amount);
foundersTotal = foundersTotal.add(amount);
}
// reconcile minted total for founders
require(foundersTotal == INITIAL_FOUNDER_SUPPLY);
// mint a small amount to the AC
require(token.mint(_autonomousConverter, INITIAL_AC_SUPPLY));
minted = true;
return true;
}
/// @notice Suspend auction if not started yet
function stopEverything() public onlyOwner {
if (genesisTime < block.timestamp) {
revert();
}
genesisTime = genesisTime + 1000 years;
initialAuctionEndTime = genesisTime;
dailyAuctionStartTime = genesisTime;
}
/// @notice Return information about initial auction status.
function isInitialAuctionEnded() public view returns (bool) {
return (initialAuctionEndTime != 0 &&
(now >= initialAuctionEndTime || token.totalSupply() >= INITIAL_SUPPLY));
}
/// @notice Global MET supply
function globalMetSupply() public view returns (uint) {
uint currAuc = currentAuction();
if (currAuc > AUCTION_WHEN_PERCENTAGE_LOGIC_STARTS) {
return globalSupplyAfterPercentageLogic;
} else {
return INITIAL_SUPPLY.add(INITIAL_GLOBAL_DAILY_SUPPLY.mul(currAuc));
}
}
/// @notice Global MET daily supply. Daily supply is greater of 1) 2880 2)2% of then outstanding supply per year.
/// @dev 2% logic will kicks in at 14792th auction.
function globalDailySupply() public view returns (uint) {
uint dailySupply = INITIAL_GLOBAL_DAILY_SUPPLY;
uint thisAuction = currentAuction();
if (thisAuction > AUCTION_WHEN_PERCENTAGE_LOGIC_STARTS) {
uint lastAuctionPurchase = whichAuction(lastPurchaseTick);
uint recentAuction = AUCTION_WHEN_PERCENTAGE_LOGIC_STARTS + 1;
if (lastAuctionPurchase > recentAuction) {
recentAuction = lastAuctionPurchase;
}
uint totalAuctions = thisAuction - recentAuction;
if (totalAuctions > 1) {
// derived formula to find close to accurate daily supply when some auction missed.
uint factor = 36525 + ((totalAuctions - 1) * 2);
dailySupply = (globalSupplyAfterPercentageLogic.mul(2).mul(factor)).div(36525 ** 2);
} else {
dailySupply = globalSupplyAfterPercentageLogic.mul(2).div(36525);
}
if (dailySupply < INITIAL_GLOBAL_DAILY_SUPPLY) {
dailySupply = INITIAL_GLOBAL_DAILY_SUPPLY;
}
}
return dailySupply;
}
/// @notice Current price of MET in current auction
/// @return weiPerToken
function currentPrice() public constant returns (uint weiPerToken) {
weiPerToken = calcPriceAt(currentTick());
}
/// @notice Daily mintable MET in current auction
function dailyMintable() public constant returns (uint) {
return nextAuctionSupply(0);
}
/// @notice Total tokens on this chain
function tokensOnThisChain() public view returns (uint) {
uint totalSupply = token.totalSupply();
uint currMintable = currentMintable();
return totalSupply.add(currMintable);
}
/// @notice Current mintable MET in auction
function currentMintable() public view returns (uint) {
uint currMintable = mintable;
uint currAuction = currentAuction();
uint totalAuctions = currAuction.sub(whichAuction(lastPurchaseTick));
if (totalAuctions > 0) {
currMintable = mintable.add(nextAuctionSupply(totalAuctions));
}
return currMintable;
}
/// @notice prepare auction when first import is done on a non ETH chain
function prepareAuctionForNonOGChain() public {
require(msg.sender == address(token.tokenPorter()) || msg.sender == address(token));
require(token.totalSupply() == 0);
require(chain != "ETH");
lastPurchaseTick = currentTick();
}
/// @notice Find out what the results would be of a prospective purchase
/// @param _wei Amount of wei the purchaser will pay
/// @param _timestamp Prospective purchase timestamp
/// @return weiPerToken expected MET token rate
/// @return tokens Expected token for a prospective purchase
/// @return refund Wei refund the purchaser will get if amount is excess and MET supply is less
function whatWouldPurchaseDo(uint _wei, uint _timestamp) public constant
returns (uint weiPerToken, uint tokens, uint refund)
{
weiPerToken = calcPriceAt(whichTick(_timestamp));
uint calctokens = METDECMULT.mul(_wei).div(weiPerToken);
tokens = calctokens;
if (calctokens > mintable) {
tokens = mintable;
uint weiPaying = mintable.mul(weiPerToken).div(METDECMULT);
refund = _wei.sub(weiPaying);
}
}
/// @notice Return the information about the next auction
/// @return _startTime Start time of next auction
/// @return _startPrice Start price of MET in next auction
/// @return _auctionTokens MET supply in next auction
function nextAuction() internal constant returns(uint _startTime, uint _startPrice, uint _auctionTokens) {
if (block.timestamp < genesisTime) {
_startTime = genesisTime;
_startPrice = lastPurchasePrice;
_auctionTokens = mintable;
return;
}
uint recentAuction = whichAuction(lastPurchaseTick);
uint currAuc = currentAuction();
uint totalAuctions = currAuc - recentAuction;
_startTime = dailyAuctionStartTime;
if (currAuc > 1) {
_startTime = auctionStartTime(currentTick());
}
_auctionTokens = nextAuctionSupply(totalAuctions);
if (totalAuctions > 1) {
_startPrice = lastPurchasePrice / 100 + 1;
} else {
if (mintable == 0 || totalAuctions == 0) {
// Sold out scenario or someone querying projected start price of next auction
_startPrice = (lastPurchasePrice * 2) + 1;
} else {
// Timed out and all tokens not sold.
if (currAuc == 1) {
// If initial auction timed out then price before start of new auction will touch floor price
_startPrice = minimumPrice * 2;
} else {
// Descending price till end of auction and then multiply by 2
uint tickWhenAuctionEnded = whichTick(_startTime);
uint numTick = 0;
if (tickWhenAuctionEnded > lastPurchaseTick) {
numTick = tickWhenAuctionEnded - lastPurchaseTick;
}
_startPrice = priceAt(lastPurchasePrice, numTick) * 2;
}
}
}
}
/// @notice Calculate results of a purchase
/// @param _wei Amount of wei the purchaser will pay
/// @param _t Prospective purchase tick
/// @return weiPerToken expected MET token rate
/// @return tokens Expected token for a prospective purchase
/// @return refund Wei refund the purchaser will get if amount is excess and MET supply is less
function calcPurchase(uint _wei, uint _t) internal view returns (uint weiPerToken, uint tokens, uint refund)
{
require(_t >= lastPurchaseTick);
uint numTicks = _t - lastPurchaseTick;
if (isInitialAuctionEnded()) {
weiPerToken = priceAt(lastPurchasePrice, numTicks);
} else {
weiPerToken = priceAtInitialAuction(lastPurchasePrice, numTicks);
}
uint calctokens = METDECMULT.mul(_wei).div(weiPerToken);
tokens = calctokens;
if (calctokens > mintable) {
tokens = mintable;
uint ethPaying = mintable.mul(weiPerToken).div(METDECMULT);
refund = _wei.sub(ethPaying);
}
}
/// @notice MET supply for next Auction also considering carry forward met.
/// @param totalAuctionMissed auction count when no purchase done.
function nextAuctionSupply(uint totalAuctionMissed) internal view returns (uint supply) {
uint thisAuction = currentAuction();
uint tokensHere = token.totalSupply().add(mintable);
supply = INITIAL_GLOBAL_DAILY_SUPPLY;
uint dailySupplyAtLastPurchase;
if (thisAuction > AUCTION_WHEN_PERCENTAGE_LOGIC_STARTS) {
supply = globalDailySupply();
if (totalAuctionMissed > 1) {
dailySupplyAtLastPurchase = globalSupplyAfterPercentageLogic.mul(2).div(36525);
supply = dailySupplyAtLastPurchase.add(supply).mul(totalAuctionMissed).div(2);
}
supply = (supply.mul(tokensHere)).div(globalSupplyAfterPercentageLogic);
} else {
if (totalAuctionMissed > 1) {
supply = supply.mul(totalAuctionMissed);
}
uint previousGlobalMetSupply =
INITIAL_SUPPLY.add(INITIAL_GLOBAL_DAILY_SUPPLY.mul(whichAuction(lastPurchaseTick)));
supply = (supply.mul(tokensHere)).div(previousGlobalMetSupply);
}
}
/// @notice price at a number of minutes out in Initial auction and daily auction
/// @param _tick Metronome tick
/// @return weiPerToken
function calcPriceAt(uint _tick) internal constant returns (uint weiPerToken) {
uint recentAuction = whichAuction(lastPurchaseTick);
uint totalAuctions = whichAuction(_tick).sub(recentAuction);
uint prevPrice;
uint numTicks = 0;
// Auction is sold out and metronome clock is in same auction
if (mintable == 0 && totalAuctions == 0) {
return lastPurchasePrice;
}
// Metronome has missed one auction ie no purchase in last auction
if (totalAuctions > 1) {
prevPrice = lastPurchasePrice / 100 + 1;
numTicks = numTicksSinceAuctionStart(_tick);
} else if (totalAuctions == 1) {
// Metronome clock is in new auction, next auction
// previous auction sold out
if (mintable == 0) {
prevPrice = lastPurchasePrice * 2;
} else {
// previous auctions timed out
// first daily auction
if (whichAuction(_tick) == 1) {
prevPrice = minimumPrice * 2;
} else {
prevPrice = priceAt(lastPurchasePrice, numTicksTillAuctionStart(_tick)) * 2;
}
}
numTicks = numTicksSinceAuctionStart(_tick);
} else {
//Auction is running
prevPrice = lastPurchasePrice;
numTicks = _tick - lastPurchaseTick;
}
require(numTicks >= 0);
if (isInitialAuctionEnded()) {
weiPerToken = priceAt(prevPrice, numTicks);
} else {
weiPerToken = priceAtInitialAuction(prevPrice, numTicks);
}
}
/// @notice Calculate number of ticks elapsed between auction start time and given tick.
/// @param _tick Given metronome tick
function numTicksSinceAuctionStart(uint _tick) private view returns (uint ) {
uint currentAuctionStartTime = auctionStartTime(_tick);
return _tick - whichTick(currentAuctionStartTime);
}
/// @notice Calculate number of ticks elapsed between lastPurchaseTick and auctions start time of given tick.
/// @param _tick Given metronome tick
function numTicksTillAuctionStart(uint _tick) private view returns (uint) {
uint currentAuctionStartTime = auctionStartTime(_tick);
return whichTick(currentAuctionStartTime) - lastPurchaseTick;
}
/// @notice First calculate the auction which contains the given tick and then calculate
/// auction start time of given tick.
/// @param _tick Metronome tick
function auctionStartTime(uint _tick) private view returns (uint) {
return ((whichAuction(_tick)) * 1 days) / timeScale + dailyAuctionStartTime - 1 days;
}
/// @notice start the next day's auction
function restartAuction() private {
uint time;
uint price;
uint auctionTokens;
(time, price, auctionTokens) = nextAuction();
uint thisAuction = currentAuction();
if (thisAuction > AUCTION_WHEN_PERCENTAGE_LOGIC_STARTS) {
globalSupplyAfterPercentageLogic = globalSupplyAfterPercentageLogic.add(globalDailySupply());
}
mintable = mintable.add(auctionTokens);
lastPurchasePrice = price;
lastPurchaseTick = whichTick(time);
}
}
/// @title This contract serves as a locker for a founder's tokens
contract TokenLocker is Ownable {
using SafeMath for uint;
uint internal constant QUARTER = 91 days + 450 minutes;
Auctions public auctions;
METToken public token;
bool public locked = false;
uint public deposited;
uint public lastWithdrawTime;
uint public quarterlyWithdrawable;
event Withdrawn(address indexed who, uint amount);
event Deposited(address indexed who, uint amount);
modifier onlyAuction() {
require(msg.sender == address(auctions));
_;
}
modifier preLock() {
require(!locked);
_;
}
modifier postLock() {
require(locked);
_;
}
/// @notice Constructor to initialize TokenLocker contract.
/// @param _auctions Address of auctions contract
/// @param _token Address of METToken contract
function TokenLocker(address _auctions, address _token) public {
require(_auctions != 0x0);
require(_token != 0x0);
auctions = Auctions(_auctions);
token = METToken(_token);
}
/// @notice If auctions is initialized, call to this function will result in
/// locking of deposited tokens and further deposit of tokens will not be allowed.
function lockTokenLocker() public onlyAuction {
require(auctions.initialAuctionEndTime() != 0);
require(auctions.initialAuctionEndTime() >= auctions.genesisTime());
locked = true;
}
/// @notice It will deposit tokens into the locker for given beneficiary.
/// @param beneficiary Address of the beneficiary, whose tokens are being locked.
/// @param amount Amount of tokens being locked
function deposit (address beneficiary, uint amount ) public onlyAuction preLock {
uint totalBalance = token.balanceOf(this);
require(totalBalance.sub(deposited) >= amount);
deposited = deposited.add(amount);
emit Deposited(beneficiary, amount);
}
/// @notice This function will allow token withdraw from locker.
/// 25% of total deposited tokens can be withdrawn after initial auction end.
/// Remaining 75% can be withdrawn in equal amount over 12 quarters.
function withdraw() public onlyOwner postLock {
require(deposited > 0);
uint withdrawable = 0;
uint withdrawTime = auctions.initialAuctionEndTime();
if (lastWithdrawTime == 0 && auctions.isInitialAuctionEnded()) {
withdrawable = withdrawable.add((deposited.mul(25)).div(100));
quarterlyWithdrawable = (deposited.sub(withdrawable)).div(12);
lastWithdrawTime = withdrawTime;
}
require(lastWithdrawTime != 0);
if (now >= lastWithdrawTime.add(QUARTER)) {
uint daysSinceLastWithdraw = now.sub(lastWithdrawTime);
uint totalQuarters = daysSinceLastWithdraw.div(QUARTER);
require(totalQuarters > 0);
withdrawable = withdrawable.add(quarterlyWithdrawable.mul(totalQuarters));
if (now >= withdrawTime.add(QUARTER.mul(12))) {
withdrawable = deposited;
}
lastWithdrawTime = lastWithdrawTime.add(totalQuarters.mul(QUARTER));
}
if (withdrawable > 0) {
deposited = deposited.sub(withdrawable);
token.transfer(msg.sender, withdrawable);
emit Withdrawn(msg.sender, withdrawable);
}
}
}
/// @title Interface for TokenPorter contract.
/// Define events and functions for TokenPorter contract
interface ITokenPorter {
event ExportOnChainClaimedReceiptLog(address indexed destinationMetronomeAddr,
address indexed destinationRecipientAddr, uint amount);
event ExportReceiptLog(bytes8 destinationChain, address destinationMetronomeAddr,
address indexed destinationRecipientAddr, uint amountToBurn, uint fee, bytes extraData, uint currentTick,
uint indexed burnSequence, bytes32 indexed currentBurnHash, bytes32 prevBurnHash, uint dailyMintable,
uint[] supplyOnAllChains, uint genesisTime, uint blockTimestamp, uint dailyAuctionStartTime);
event ImportReceiptLog(address indexed destinationRecipientAddr, uint amountImported,
uint fee, bytes extraData, uint currentTick, uint indexed importSequence,
bytes32 indexed currentHash, bytes32 prevHash, uint dailyMintable, uint blockTimestamp, address caller);
function export(address tokenOwner, bytes8 _destChain, address _destMetronomeAddr,
address _destRecipAddr, uint _amount, uint _fee, bytes _extraData) public returns (bool);
function importMET(bytes8 _originChain, bytes8 _destinationChain, address[] _addresses, bytes _extraData,
bytes32[] _burnHashes, uint[] _supplyOnAllChains, uint[] _importData, bytes _proof) public returns (bool);
}
/// @title This contract will provide export functionality for tokens.
contract TokenPorter is ITokenPorter, Owned {
using SafeMath for uint;
Auctions public auctions;
METToken public token;
Validator public validator;
ChainLedger public chainLedger;
uint public burnSequence = 1;
uint public importSequence = 1;
bytes32[] public exportedBurns;
uint[] public supplyOnAllChains = new uint[](6);
/// @notice mapping that tracks valid destination chains for export
mapping(bytes8 => address) public destinationChains;
/// @notice Initialize TokenPorter contract.
/// @param _tokenAddr Address of metToken contract
/// @param _auctionsAddr Address of auctions contract
function initTokenPorter(address _tokenAddr, address _auctionsAddr) public onlyOwner {
require(_tokenAddr != 0x0);
require(_auctionsAddr != 0x0);
auctions = Auctions(_auctionsAddr);
token = METToken(_tokenAddr);
}
/// @notice set address of validator contract
/// @param _validator address of validator contract
function setValidator(address _validator) public onlyOwner returns (bool) {
require(_validator != 0x0);
validator = Validator(_validator);
return true;
}
/// @notice set address of chainLedger contract
/// @param _chainLedger address of chainLedger contract
function setChainLedger(address _chainLedger) public onlyOwner returns (bool) {
require(_chainLedger != 0x0);
chainLedger = ChainLedger(_chainLedger);
return true;
}
/// @notice only owner can add destination chains
/// @param _chainName string of destination blockchain name
/// @param _contractAddress address of destination MET token to import to
function addDestinationChain(bytes8 _chainName, address _contractAddress)
public onlyOwner returns (bool)
{
require(_chainName != 0 && _contractAddress != address(0));
destinationChains[_chainName] = _contractAddress;
return true;
}
/// @notice only owner can remove destination chains
/// @param _chainName string of destination blockchain name
function removeDestinationChain(bytes8 _chainName) public onlyOwner returns (bool) {
require(_chainName != 0);
require(destinationChains[_chainName] != address(0));
destinationChains[_chainName] = address(0);
return true;
}
/// @notice holds claims from users that have exported on-chain
/// @param key is address of destination MET token contract
/// @param subKey is address of users account that burned their original MET token
mapping (address => mapping(address => uint)) public claimables;
/// @notice destination MET token contract calls claimReceivables to record burned
/// tokens have been minted in new chain
/// @param recipients array of addresses of each user that has exported from
/// original chain. These can be generated by ExportReceiptLog
function claimReceivables(address[] recipients) public returns (uint) {
require(recipients.length > 0);
uint total;
for (uint i = 0; i < recipients.length; i++) {
address recipient = recipients[i];
uint amountBurned = claimables[msg.sender][recipient];
if (amountBurned > 0) {
claimables[msg.sender][recipient] = 0;
emit ExportOnChainClaimedReceiptLog(msg.sender, recipient, amountBurned);
total = total.add(1);
}
}
return total;
}
/// @notice import MET tokens from another chain to this chain.
/// @param _destinationChain destination chain name
/// @param _addresses _addresses[0] is destMetronomeAddr and _addresses[1] is recipientAddr
/// @param _extraData extra information for import
/// @param _burnHashes _burnHashes[0] is previous burnHash, _burnHashes[1] is current burnHash
/// @param _supplyOnAllChains MET supply on all supported chains
/// @param _importData _importData[0] is _blockTimestamp, _importData[1] is _amount, _importData[2] is _fee
/// _importData[3] is _burnedAtTick, _importData[4] is _genesisTime, _importData[5] is _dailyMintable
/// _importData[6] is _burnSequence, _importData[7] is _dailyAuctionStartTime
/// @param _proof proof
/// @return true/false
function importMET(bytes8 _originChain, bytes8 _destinationChain, address[] _addresses, bytes _extraData,
bytes32[] _burnHashes, uint[] _supplyOnAllChains, uint[] _importData, bytes _proof) public returns (bool)
{
require(msg.sender == address(token));
require(_importData.length == 8);
require(_addresses.length == 2);
require(_burnHashes.length == 2);
require(validator.isReceiptClaimable(_originChain, _destinationChain, _addresses, _extraData, _burnHashes,
_supplyOnAllChains, _importData, _proof));
validator.claimHash(_burnHashes[1]);
require(_destinationChain == auctions.chain());
uint amountToImport = _importData[1].add(_importData[2]);
require(amountToImport.add(token.totalSupply()) <= auctions.globalMetSupply());
require(_addresses[0] == address(token));
if (_importData[1] == 0) {
return false;
}
if (importSequence == 1 && token.totalSupply() == 0) {
auctions.prepareAuctionForNonOGChain();
}
token.mint(_addresses[1], _importData[1]);
emit ImportReceiptLog(_addresses[1], _importData[1], _importData[2], _extraData,
auctions.currentTick(), importSequence, _burnHashes[1],
_burnHashes[0], auctions.dailyMintable(), now, msg.sender);
importSequence++;
chainLedger.registerImport(_originChain, _destinationChain, _importData[1]);
return true;
}
/// @notice Export MET tokens from this chain to another chain.
/// @param tokenOwner Owner of the token, whose tokens are being exported.
/// @param _destChain Destination chain for exported tokens
/// @param _destMetronomeAddr Metronome address on destination chain
/// @param _destRecipAddr Recipient address on the destination chain
/// @param _amount Amount of token being exported
/// @param _extraData Extra data for this export
/// @return boolean true/false based on the outcome of export
function export(address tokenOwner, bytes8 _destChain, address _destMetronomeAddr,
address _destRecipAddr, uint _amount, uint _fee, bytes _extraData) public returns (bool)
{
require(msg.sender == address(token));
require(_destChain != 0x0 && _destMetronomeAddr != 0x0 && _destRecipAddr != 0x0 && _amount != 0);
require(destinationChains[_destChain] == _destMetronomeAddr);
require(token.balanceOf(tokenOwner) >= _amount.add(_fee));
token.destroy(tokenOwner, _amount.add(_fee));
uint dailyMintable = auctions.dailyMintable();
uint currentTick = auctions.currentTick();
if (burnSequence == 1) {
exportedBurns.push(keccak256(uint8(0)));
}
if (_destChain == auctions.chain()) {
claimables[_destMetronomeAddr][_destRecipAddr] =
claimables[_destMetronomeAddr][_destRecipAddr].add(_amount);
}
uint blockTime = block.timestamp;
bytes32 currentBurn = keccak256(
blockTime,
auctions.chain(),
_destChain,
_destMetronomeAddr,
_destRecipAddr,
_amount,
currentTick,
auctions.genesisTime(),
dailyMintable,
token.totalSupply(),
_extraData,
exportedBurns[burnSequence - 1]);
exportedBurns.push(currentBurn);
supplyOnAllChains[0] = token.totalSupply();
emit ExportReceiptLog(_destChain, _destMetronomeAddr, _destRecipAddr, _amount, _fee, _extraData,
currentTick, burnSequence, currentBurn, exportedBurns[burnSequence - 1], dailyMintable,
supplyOnAllChains, auctions.genesisTime(), blockTime, auctions.dailyAuctionStartTime());
burnSequence = burnSequence + 1;
chainLedger.registerExport(auctions.chain(), _destChain, _amount);
return true;
}
}
contract ChainLedger is Owned {
using SafeMath for uint;
mapping (bytes8 => uint) public balance;
mapping (bytes8 => bool) public validChain;
bytes8[] public chains;
address public tokenPorter;
Auctions public auctions;
event LogRegisterChain(address indexed caller, bytes8 indexed chain, uint supply, bool outcome);
event LogRegisterExport(address indexed caller, bytes8 indexed originChain, bytes8 indexed destChain, uint amount);
event LogRegisterImport(address indexed caller, bytes8 indexed originChain, bytes8 indexed destChain, uint amount);
function initChainLedger(address _tokenPorter, address _auctionsAddr) public onlyOwner returns (bool) {
require(_tokenPorter != 0x0);
require(_auctionsAddr != 0x0);
tokenPorter = _tokenPorter;
auctions = Auctions(_auctionsAddr);
return true;
}
function registerChain(bytes8 chain, uint supply) public onlyOwner returns (bool) {
require(!validChain[chain]);
validChain[chain] = true;
chains.push(chain);
balance[chain] = supply;
emit LogRegisterChain(msg.sender, chain, supply, true);
}
function registerExport(bytes8 originChain, bytes8 destChain, uint amount) public {
require(msg.sender == tokenPorter || msg.sender == owner);
require(validChain[originChain] && validChain[destChain]);
require(balance[originChain] >= amount);
balance[originChain] = balance[originChain].sub(amount);
balance[destChain] = balance[destChain].add(amount);
emit LogRegisterExport(msg.sender, originChain, destChain, amount);
}
function registerImport(bytes8 originChain, bytes8 destChain, uint amount) public {
require(msg.sender == tokenPorter || msg.sender == owner);
require(validChain[originChain] && validChain[destChain]);
balance[originChain] = balance[originChain].sub(amount);
balance[destChain] = balance[destChain].add(amount);
emit LogRegisterImport(msg.sender, originChain, destChain, amount);
}
}
contract Validator is Owned {
mapping (bytes32 => mapping (address => bool)) public hashAttestations;
mapping (address => bool) public isValidator;
mapping (address => uint8) public validatorNum;
address[] public validators;
address public metToken;
address public tokenPorter;
mapping (bytes32 => bool) public hashClaimed;
uint8 public threshold = 2;
event LogAttestation(bytes32 indexed hash, address indexed who, bool isValid);
/// @param _validator1 first validator
/// @param _validator2 second validator
/// @param _validator3 third validator
function initValidator(address _validator1, address _validator2, address _validator3) public onlyOwner {
// Clear old validators. Validators can be updated multiple times
for (uint8 i = 0; i < validators.length; i++) {
delete isValidator[validators[i]];
delete validatorNum[validators[i]];
}
delete validators;
validators.push(_validator1);
validators.push(_validator2);
validators.push(_validator3);
// TODO: This will be NA, Bloq and a third party (escrow or company) at launch,
// and should be scripted into deploy
isValidator[_validator1] = true;
isValidator[_validator2] = true;
isValidator[_validator3] = true;
validatorNum[_validator1] = 0;
validatorNum[_validator2] = 1;
validatorNum[_validator3] = 2;
}
/// @notice set address of token porter
/// @param _tokenPorter address of token porter
function setTokenPorter(address _tokenPorter) public onlyOwner returns (bool) {
require(_tokenPorter != 0x0);
tokenPorter = _tokenPorter;
return true;
}
function validateHash(bytes32 hash) public {
require(isValidator[msg.sender]);
hashAttestations[hash][msg.sender] = true;
emit LogAttestation(hash, msg.sender, true);
}
function invalidateHash(bytes32 hash) public {
require(isValidator[msg.sender]);
hashAttestations[hash][msg.sender] = false;
emit LogAttestation(hash, msg.sender, false);
}
function hashClaimable(bytes32 hash) public view returns(bool) {
if (hashClaimed[hash]) { return false; }
uint8 count = 0;
for (uint8 i = 0; i < validators.length; i++) {
if (hashAttestations[hash][validators[i]]) { count++;}
}
if (count >= threshold) { return true; }
return false;
}
function claimHash(bytes32 hash) public {
require(msg.sender == tokenPorter);
require(hashClaimable(hash));
hashClaimed[hash] = true;
}
function isReceiptClaimable(bytes8 _originChain, bytes8 _destinationChain, address[] _addresses, bytes _extraData,
bytes32[] _burnHashes, uint[] _supplyOnAllChain, uint[] _importData, bytes _proof) public view returns(bool) {
// We want to validate that these hash to the provided hash as a safety check,
// then we want to know if the hash is Claimable.
// Due to stack too deep error and limitation in using number of local
// variables we have to use uint array here.
// _importData[0] is _blockTimestamp, _importData[1] is _amount, _importData[2] is _fee,
// _importData[3] is _burnedAtTick, _importData[4] is _genesisTime,
// _importData[5] is _dailyMintable, _importData[6] is _burnSequence,
// _addresses[0] is _destMetronomeAddr and _addresses[1] is _recipAddr
require(_burnHashes[1] == keccak256(_importData[0], _originChain, _destinationChain, _addresses[0],
_addresses[1], _importData[1], _importData[3], _importData[4], _importData[5], _supplyOnAllChain[0],
_extraData, _burnHashes[0]));
if (hashClaimable(_burnHashes[1])) {
return true;
}
return false;
}
}
|
set address of token porter _tokenPorter address of token porter
|
function setTokenPorter(address _tokenPorter) public onlyOwner returns (bool) {
require(_tokenPorter != 0x0);
tokenPorter = ITokenPorter(_tokenPorter);
return true;
}
| 624,275 |
./full_match/1/0x1111306F3d849B133f533D6E9F7341d40De0cB4b/sources/src/RPVault.sol
|
change AUM cap _aumCap new AUM cap
|
function updateAumCap(uint256 _aumCap) public requiresAuth {
if (aumCap < getEffectiveAssets()) {
revert AumCapInvalid();
}
aumCap = _aumCap;
}
| 8,293,611 |
./full_match/5/0xcB8AD068b5c8399DF5933D15B5e4E8AFa08d4Ad1/sources/contracts/VideoNFT.sol
|
Calculate profit percentage and amount Update past owners and transaction prices Update the video price Add user notifications for the old owner and new owner
|
function bid(uint256 tokenId) public payable {
require(
msg.value >= videos[tokenId].price,
"Bid must be equal or higher than the current price"
);
require(
videos[tokenId].biddingEndTime > block.timestamp,
"Bidding has ended"
);
address oldOwner = ownerOf(tokenId);
uint256 oldPrice = videos[tokenId].price;
_transfer(oldOwner, msg.sender, tokenId);
uint256 profit = msg.value - oldPrice;
uint256 profitPercentage = (profit * 100) / oldPrice;
profitPercentages[oldOwner] += profitPercentage;
profitAmounts[oldOwner] += profit;
pastOwners[tokenId].push(msg.sender);
pastTransactionPrices[tokenId].push(msg.value);
videos[tokenId].price = msg.value;
notifications[oldOwner].push(
string(
abi.encodePacked(
"You sold video ",
uint2str(tokenId),
" for ",
uint2str(msg.value),
" ETH"
)
)
);
notifications[msg.sender].push(
string(
abi.encodePacked(
"You bought video ",
uint2str(tokenId),
" for ",
uint2str(msg.value),
" ETH"
)
)
);
emit OwnershipTransferred(tokenId, oldOwner, msg.sender, msg.value);
}
| 1,938,951 |
./full_match/288/0x45989245c949C4320E7f16B91E5964076ED9cB71/sources/contracts/MiniChefV2.sol
|
Update the given pool's ZENC allocation point and `IRewarder` contract. Can only be called by the owner. _pid The index of the pool. See `poolInfo`. _allocPoint New AP of the pool. _rewarder Address of the rewarder delegate. overwrite True if _rewarder should be `set`. Otherwise `_rewarder` is ignored.
|
function set(
uint256 _pid,
uint256 _allocPoint,
IRewarder _rewarder,
bool overwrite
) public onlyOwner {
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint.to64();
if (overwrite) {
rewarder[_pid] = _rewarder;
}
emit LogSetPool(_pid, _allocPoint, overwrite ? _rewarder : rewarder[_pid], overwrite);
}
| 7,103,572 |
/*
https://mycryptochamp.io/
<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e088858c8c8fa08d9983929990948f8388818d90ce898f">[email protected]</a>
*/
pragma solidity 0.4.24;
contract Controller{
function getChampReward(uint _position) public view returns(uint);
function changeChampsName(uint _champId, string _name, address _msgsender) external;
function withdrawChamp(uint _id, address _msgsender) external;
function attack(uint _champId, uint _targetId, address _msgsender) external;
function transferToken(address _from, address _to, uint _id, bool _isTokenChamp) external;
function cancelTokenSale(uint _id, address _msgsender, bool _isTokenChamp) public;
function giveToken(address _to, uint _id, address _msgsender, bool _isTokenChamp) external;
function setTokenForSale(uint _id, uint _price, address _msgsender, bool _isTokenChamp) external;
function getTokenURIs(uint _id, bool _isTokenChamp) public pure returns(string);
function takeOffItem(uint _champId, uint8 _type, address _msgsender) public;
function putOn(uint _champId, uint _itemId, address _msgsender) external;
function forgeItems(uint _parentItemID, uint _childItemID, address _msgsender) external;
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint a, uint b) internal pure returns (uint) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint a, uint b) internal pure returns (uint) {
uint c = a + b;
assert(c >= a);
return c;
}
}
/// @title MyCryptoChamp Core - Stores all of game data. Functions are stored in the replaceable contracts. This solution was required in order to avoid unexpected bugs and make game upgradeable.
/// @author Patrik Mojzis
contract MyCryptoChampCore {
using SafeMath for uint;
struct Champ {
uint id; //same as position in Champ[]
uint attackPower;
uint defencePower;
uint cooldownTime; //how long does it take to be able attack again
uint readyTime; //if is smaller than block.timestamp champ is ready to fight
uint winCount;
uint lossCount;
uint position; //subtract 1 and you get position in leaderboard[]
uint price; //sale price
uint withdrawCooldown; //if you one of the 800 best champs and withdrawCooldown is less as block.timestamp then you get ETH reward
uint eq_sword;
uint eq_shield;
uint eq_helmet;
bool forSale; //is champ for sale?
}
struct AddressInfo {
uint withdrawal;
uint champsCount;
uint itemsCount;
string name;
}
//Item struct
struct Item {
uint id;
uint8 itemType; // 1 - Sword | 2 - Shield | 3 - Helmet
uint8 itemRarity; // 1 - Common | 2 - Uncommon | 3 - Rare | 4 - Epic | 5 - Legendery | 6 - Forged
uint attackPower;
uint defencePower;
uint cooldownReduction;
uint price;
uint onChampId; //can not be used to decide if item is on champ, because champ's id can be 0, 'bool onChamp' solves it.
bool onChamp;
bool forSale; //is item for sale?
}
Champ[] public champs;
Item[] public items;
mapping (uint => uint) public leaderboard;
mapping (address => bool) private trusted;
mapping (address => AddressInfo) public addressInfo;
mapping (bool => mapping(address => mapping (address => bool))) public tokenOperatorApprovals;
mapping (bool => mapping(uint => address)) public tokenApprovals;
mapping (bool => mapping(uint => address)) public tokenToOwner;
mapping (uint => string) public champToName;
mapping (bool => uint) public tokensForSaleCount;
uint public pendingWithdrawal = 0;
address private contractOwner;
Controller internal controller;
constructor () public
{
trusted[msg.sender] = true;
contractOwner = msg.sender;
}
/*============== MODIFIERS ==============*/
modifier onlyTrusted(){
require(trusted[msg.sender]);
_;
}
modifier isPaid(uint _price)
{
require(msg.value >= _price);
_;
}
modifier onlyNotOwnerOfItem(uint _itemId) {
require(_itemId != 0);
require(msg.sender != tokenToOwner[false][_itemId]);
_;
}
modifier isItemForSale(uint _id){
require(items[_id].forSale);
_;
}
modifier onlyNotOwnerOfChamp(uint _champId)
{
require(msg.sender != tokenToOwner[true][_champId]);
_;
}
modifier isChampForSale(uint _id)
{
require(champs[_id].forSale);
_;
}
/*============== CONTROL COTRACT ==============*/
function loadController(address _address) external onlyTrusted {
controller = Controller(_address);
}
function setTrusted(address _address, bool _trusted) external onlyTrusted {
trusted[_address] = _trusted;
}
function transferOwnership(address newOwner) public onlyTrusted {
require(newOwner != address(0));
contractOwner = newOwner;
}
/*============== PRIVATE FUNCTIONS ==============*/
function _addWithdrawal(address _address, uint _amount) private
{
addressInfo[_address].withdrawal += _amount;
pendingWithdrawal += _amount;
}
/// @notice Distribute input funds between contract owner and players
function _distributeNewSaleInput(address _affiliateAddress) private
{
//contract owner
_addWithdrawal(contractOwner, ((msg.value / 100) * 60)); // 60%
//affiliate
//checks if _affiliateAddress is set & if affiliate address is not buying player
if(_affiliateAddress != address(0) && _affiliateAddress != msg.sender){
_addWithdrawal(_affiliateAddress, ((msg.value / 100) * 25)); //provision is 25%
}
}
/*============== ONLY TRUSTED ==============*/
function addWithdrawal(address _address, uint _amount) public onlyTrusted
{
_addWithdrawal(_address, _amount);
}
function clearTokenApproval(address _from, uint _tokenId, bool _isTokenChamp) public onlyTrusted
{
require(tokenToOwner[_isTokenChamp][_tokenId] == _from);
if (tokenApprovals[_isTokenChamp][_tokenId] != address(0)) {
tokenApprovals[_isTokenChamp][_tokenId] = address(0);
}
}
function emergencyWithdraw() external onlyTrusted
{
contractOwner.transfer(address(this).balance);
}
function setChampsName(uint _champId, string _name) public onlyTrusted
{
champToName[_champId] = _name;
}
function setLeaderboard(uint _x, uint _value) public onlyTrusted
{
leaderboard[_x] = _value;
}
function setTokenApproval(uint _id, address _to, bool _isTokenChamp) public onlyTrusted
{
tokenApprovals[_isTokenChamp][_id] = _to;
}
function setTokenOperatorApprovals(address _from, address _to, bool _approved, bool _isTokenChamp) public onlyTrusted
{
tokenOperatorApprovals[_isTokenChamp][_from][_to] = _approved;
}
function setTokenToOwner(uint _id, address _owner, bool _isTokenChamp) public onlyTrusted
{
tokenToOwner[_isTokenChamp][_id] = _owner;
}
function setTokensForSaleCount(uint _value, bool _isTokenChamp) public onlyTrusted
{
tokensForSaleCount[_isTokenChamp] = _value;
}
function transferToken(address _from, address _to, uint _id, bool _isTokenChamp) public onlyTrusted
{
controller.transferToken(_from, _to, _id, _isTokenChamp);
}
function updateAddressInfo(address _address, uint _withdrawal, bool _updatePendingWithdrawal, uint _champsCount, bool _updateChampsCount, uint _itemsCount, bool _updateItemsCount, string _name, bool _updateName) public onlyTrusted {
AddressInfo storage ai = addressInfo[_address];
if(_updatePendingWithdrawal){ ai.withdrawal = _withdrawal; }
if(_updateChampsCount){ ai.champsCount = _champsCount; }
if(_updateItemsCount){ ai.itemsCount = _itemsCount; }
if(_updateName){ ai.name = _name; }
}
function newChamp(
uint _attackPower,
uint _defencePower,
uint _cooldownTime,
uint _winCount,
uint _lossCount,
uint _position,
uint _price,
uint _eq_sword,
uint _eq_shield,
uint _eq_helmet,
bool _forSale,
address _owner
) public onlyTrusted returns (uint){
Champ memory champ = Champ({
id: 0,
attackPower: 0, //CompilerError: Stack too deep, try removing local variables.
defencePower: _defencePower,
cooldownTime: _cooldownTime,
readyTime: 0,
winCount: _winCount,
lossCount: _lossCount,
position: _position,
price: _price,
withdrawCooldown: 0,
eq_sword: _eq_sword,
eq_shield: _eq_shield,
eq_helmet: _eq_helmet,
forSale: _forSale
});
champ.attackPower = _attackPower;
uint id = champs.push(champ) - 1;
champs[id].id = id;
leaderboard[_position] = id;
addressInfo[_owner].champsCount++;
tokenToOwner[true][id] = _owner;
if(_forSale){
tokensForSaleCount[true]++;
}
return id;
}
function newItem(
uint8 _itemType,
uint8 _itemRarity,
uint _attackPower,
uint _defencePower,
uint _cooldownReduction,
uint _price,
uint _onChampId,
bool _onChamp,
bool _forSale,
address _owner
) public onlyTrusted returns (uint)
{
//create that struct
Item memory item = Item({
id: 0,
itemType: _itemType,
itemRarity: _itemRarity,
attackPower: _attackPower,
defencePower: _defencePower,
cooldownReduction: _cooldownReduction,
price: _price,
onChampId: _onChampId,
onChamp: _onChamp,
forSale: _forSale
});
uint id = items.push(item) - 1;
items[id].id = id;
addressInfo[_owner].itemsCount++;
tokenToOwner[false][id] = _owner;
if(_forSale){
tokensForSaleCount[false]++;
}
return id;
}
function updateChamp(
uint _champId,
uint _attackPower,
uint _defencePower,
uint _cooldownTime,
uint _readyTime,
uint _winCount,
uint _lossCount,
uint _position,
uint _price,
uint _withdrawCooldown,
uint _eq_sword,
uint _eq_shield,
uint _eq_helmet,
bool _forSale
) public onlyTrusted {
Champ storage champ = champs[_champId];
if(champ.attackPower != _attackPower){champ.attackPower = _attackPower;}
if(champ.defencePower != _defencePower){champ.defencePower = _defencePower;}
if(champ.cooldownTime != _cooldownTime){champ.cooldownTime = _cooldownTime;}
if(champ.readyTime != _readyTime){champ.readyTime = _readyTime;}
if(champ.winCount != _winCount){champ.winCount = _winCount;}
if(champ.lossCount != _lossCount){champ.lossCount = _lossCount;}
if(champ.position != _position){
champ.position = _position;
leaderboard[_position] = _champId;
}
if(champ.price != _price){champ.price = _price;}
if(champ.withdrawCooldown != _withdrawCooldown){champ.withdrawCooldown = _withdrawCooldown;}
if(champ.eq_sword != _eq_sword){champ.eq_sword = _eq_sword;}
if(champ.eq_shield != _eq_shield){champ.eq_shield = _eq_shield;}
if(champ.eq_helmet != _eq_helmet){champ.eq_helmet = _eq_helmet;}
if(champ.forSale != _forSale){
champ.forSale = _forSale;
if(_forSale){
tokensForSaleCount[true]++;
}else{
tokensForSaleCount[true]--;
}
}
}
function updateItem(
uint _id,
uint8 _itemType,
uint8 _itemRarity,
uint _attackPower,
uint _defencePower,
uint _cooldownReduction,
uint _price,
uint _onChampId,
bool _onChamp,
bool _forSale
) public onlyTrusted
{
Item storage item = items[_id];
if(item.itemType != _itemType){item.itemType = _itemType;}
if(item.itemRarity != _itemRarity){item.itemRarity = _itemRarity;}
if(item.attackPower != _attackPower){item.attackPower = _attackPower;}
if(item.defencePower != _defencePower){item.defencePower = _defencePower;}
if(item.cooldownReduction != _cooldownReduction){item.cooldownReduction = _cooldownReduction;}
if(item.price != _price){item.price = _price;}
if(item.onChampId != _onChampId){item.onChampId = _onChampId;}
if(item.onChamp != _onChamp){item.onChamp = _onChamp;}
if(item.forSale != _forSale){
item.forSale = _forSale;
if(_forSale){
tokensForSaleCount[false]++;
}else{
tokensForSaleCount[false]--;
}
}
}
/*============== CALLABLE BY PLAYER ==============*/
function buyItem(uint _id, address _affiliateAddress) external payable
onlyNotOwnerOfItem(_id)
isItemForSale(_id)
isPaid(items[_id].price)
{
if(tokenToOwner[false][_id] == address(this)){
_distributeNewSaleInput(_affiliateAddress);
}else{
_addWithdrawal(tokenToOwner[false][_id], msg.value);
}
controller.transferToken(tokenToOwner[false][_id], msg.sender, _id, false);
}
function buyChamp(uint _id, address _affiliateAddress) external payable
onlyNotOwnerOfChamp(_id)
isChampForSale(_id)
isPaid(champs[_id].price)
{
if(tokenToOwner[true][_id] == address(this)){
_distributeNewSaleInput(_affiliateAddress);
}else{
_addWithdrawal(tokenToOwner[true][_id], msg.value);
}
controller.transferToken(tokenToOwner[true][_id], msg.sender, _id, true);
}
function changePlayersName(string _name) external {
addressInfo[msg.sender].name = _name;
}
function withdrawToAddress(address _address) external
{
address playerAddress = _address;
if(playerAddress == address(0)){ playerAddress = msg.sender; }
uint share = addressInfo[playerAddress].withdrawal; //gets pending funds
require(share > 0); //is it more than 0?
addressInfo[playerAddress].withdrawal = 0; //set player's withdrawal pendings to 0
pendingWithdrawal = pendingWithdrawal.sub(share); //subtract share from total pendings
playerAddress.transfer(share); //transfer
}
/*============== VIEW FUNCTIONS ==============*/
function getChampsByOwner(address _owner) external view returns(uint256[]) {
uint256[] memory result = new uint256[](addressInfo[_owner].champsCount);
uint256 counter = 0;
for (uint256 i = 0; i < champs.length; i++) {
if (tokenToOwner[true][i] == _owner) {
result[counter] = i;
counter++;
}
}
return result;
}
function getTokensForSale(bool _isTokenChamp) view external returns(uint256[]){
uint256[] memory result = new uint256[](tokensForSaleCount[_isTokenChamp]);
if(tokensForSaleCount[_isTokenChamp] > 0){
uint256 counter = 0;
if(_isTokenChamp){
for (uint256 i = 0; i < champs.length; i++) {
if (champs[i].forSale == true) {
result[counter]=i;
counter++;
}
}
}else{
for (uint256 n = 0; n < items.length; n++) {
if (items[n].forSale == true) {
result[counter]=n;
counter++;
}
}
}
}
return result;
}
function getChampStats(uint256 _champId) public view returns(uint256,uint256,uint256){
Champ storage champ = champs[_champId];
Item storage sword = items[champ.eq_sword];
Item storage shield = items[champ.eq_shield];
Item storage helmet = items[champ.eq_helmet];
uint totalAttackPower = champ.attackPower + sword.attackPower + shield.attackPower + helmet.attackPower; //Gets champs AP
uint totalDefencePower = champ.defencePower + sword.defencePower + shield.defencePower + helmet.defencePower; //Gets champs DP
uint totalCooldownReduction = sword.cooldownReduction + shield.cooldownReduction + helmet.cooldownReduction; //Gets CR
return (totalAttackPower, totalDefencePower, totalCooldownReduction);
}
function getItemsByOwner(address _owner) external view returns(uint256[]) {
uint256[] memory result = new uint256[](addressInfo[_owner].itemsCount);
uint256 counter = 0;
for (uint256 i = 0; i < items.length; i++) {
if (tokenToOwner[false][i] == _owner) {
result[counter] = i;
counter++;
}
}
return result;
}
function getTokenCount(bool _isTokenChamp) external view returns(uint)
{
if(_isTokenChamp){
return champs.length - addressInfo[address(0)].champsCount;
}else{
return items.length - 1 - addressInfo[address(0)].itemsCount;
}
}
function getTokenURIs(uint _tokenId, bool _isTokenChamp) public view returns(string)
{
return controller.getTokenURIs(_tokenId,_isTokenChamp);
}
function onlyApprovedOrOwnerOfToken(uint _id, address _msgsender, bool _isTokenChamp) external view returns(bool)
{
if(!_isTokenChamp){
require(_id != 0);
}
address owner = tokenToOwner[_isTokenChamp][_id];
return(_msgsender == owner || _msgsender == tokenApprovals[_isTokenChamp][_id] || tokenOperatorApprovals[_isTokenChamp][owner][_msgsender]);
}
/*============== DELEGATE ==============*/
function attack(uint _champId, uint _targetId) external{
controller.attack(_champId, _targetId, msg.sender);
}
function cancelTokenSale(uint _id, bool _isTokenChamp) public{
controller.cancelTokenSale(_id, msg.sender, _isTokenChamp);
}
function changeChampsName(uint _champId, string _name) external{
controller.changeChampsName(_champId, _name, msg.sender);
}
function forgeItems(uint _parentItemID, uint _childItemID) external{
controller.forgeItems(_parentItemID, _childItemID, msg.sender);
}
function giveToken(address _to, uint _champId, bool _isTokenChamp) external{
controller.giveToken(_to, _champId, msg.sender, _isTokenChamp);
}
function setTokenForSale(uint _id, uint _price, bool _isTokenChamp) external{
controller.setTokenForSale(_id, _price, msg.sender, _isTokenChamp);
}
function putOn(uint _champId, uint _itemId) external{
controller.putOn(_champId, _itemId, msg.sender);
}
function takeOffItem(uint _champId, uint8 _type) public{
controller.takeOffItem(_champId, _type, msg.sender);
}
function withdrawChamp(uint _id) external{
controller.withdrawChamp(_id, msg.sender);
}
function getChampReward(uint _position) public view returns(uint){
return controller.getChampReward(_position);
}
}
|
============== CONTROL COTRACT ==============/
|
function loadController(address _address) external onlyTrusted {
controller = Controller(_address);
}
| 2,359,663 |
pragma solidity ^0.6.1;
contract HashStore {
/*
* Events
*/
event OwnershipTransferred(address indexed _previousOwner, address indexed _newOwner);
event NewHashStored(address indexed _hashSender, uint _hashId, string _hashContent, uint timestamp);
event Withdrawn(address indexed _hashSender, uint amount);
/*
* Storage
*/
struct Hash {
// sender address
address sender;
// hash text
string content;
// creation timestamp
uint timestamp;
// previous hash text
string old;
}
// Hashes mapping
mapping(uint => Hash) public hashes;
// Contract owner
address public owner;
// Last stored Hash Id
uint public lastHashId;
// Service price in Wei
uint public price;
/*
* Modifiers
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/*
* Public functions
*/
/**
* @dev Contract constructor
* @param _price Service price
* renamed HashStore{} to StoreHash{}
*/
function StoreHash(uint _price) public {
// check price valid
require(_price > 0);
// assign owner
owner = msg.sender;
// assign price
price = _price;
// init ids
lastHashId = 0;
}
/**
* @dev Transfer contract ownership
* @param _newOwner New owner address
*/
function transferOwnership(address _newOwner) onlyOwner public {
// check address not null
require(_newOwner != address(0));
// assign new owner
owner = _newOwner;
// Log event
emit OwnershipTransferred(owner, _newOwner);
}
/**
* @dev Withdraw contract accumulated Eth balance
*/
/*function withdrawBalance() onlyOwner public */
/**
* @dev save new hash
* @param _hashContent Hash Content
*/
function save(string memory _hashContent, string memory _lastHashContent) payable public {
// only save if service price paid
require(msg.value >= price);
// create Hash
uint hashId = ++lastHashId;
hashes[hashId].sender = msg.sender;
hashes[hashId].content = _hashContent;
hashes[hashId].old = _lastHashContent;
hashes[hashId].timestamp = block.timestamp;
// Log event
emit NewHashStored(hashes[hashId].sender, hashId, hashes[hashId].content, hashes[hashId].timestamp);
}
/**
* @dev find hash by id
* @param _hashId Hash Id
*/
function find(uint _hashId) view public returns (address hashSender, string memory hashContent, string memory _lastHashContent, uint hashTimestamp) {
return (hashes[_hashId].sender, hashes[_hashId].content, hashes[_hashId].old, hashes[_hashId].timestamp);
}
}
|
find hash by id _hashId Hash Id/
|
function find(uint _hashId) view public returns (address hashSender, string memory hashContent, string memory _lastHashContent, uint hashTimestamp) {
return (hashes[_hashId].sender, hashes[_hashId].content, hashes[_hashId].old, hashes[_hashId].timestamp);
}
| 5,525,576 |
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
// Global Enums and Structs
struct StrategyParams {
uint256 performanceFee;
uint256 activation;
uint256 debtRatio;
uint256 minDebtPerHarvest;
uint256 maxDebtPerHarvest;
uint256 lastReport;
uint256 totalDebt;
uint256 totalGain;
uint256 totalLoss;
}
// Part: IBaseFee
interface IBaseFee {
function isCurrentBaseFeeAcceptable() external view returns (bool);
}
// Part: ICurveFi
interface ICurveFi {
function get_virtual_price() external view returns (uint256);
function add_liquidity(
// EURt
uint256[2] calldata amounts,
uint256 min_mint_amount
) external payable;
function add_liquidity(
// Compound, sAave
uint256[2] calldata amounts,
uint256 min_mint_amount,
bool _use_underlying
) external payable returns (uint256);
function add_liquidity(
// Iron Bank, Aave
uint256[3] calldata amounts,
uint256 min_mint_amount,
bool _use_underlying
) external payable returns (uint256);
function add_liquidity(
// 3Crv Metapools
address pool,
uint256[4] calldata amounts,
uint256 min_mint_amount
) external;
function add_liquidity(
// Y and yBUSD
uint256[4] calldata amounts,
uint256 min_mint_amount,
bool _use_underlying
) external payable returns (uint256);
function add_liquidity(
// 3pool
uint256[3] calldata amounts,
uint256 min_mint_amount
) external payable;
function add_liquidity(
// sUSD
uint256[4] calldata amounts,
uint256 min_mint_amount
) external payable;
function remove_liquidity_imbalance(
uint256[2] calldata amounts,
uint256 max_burn_amount
) external;
function remove_liquidity(uint256 _amount, uint256[2] calldata amounts)
external;
function remove_liquidity_one_coin(
uint256 _token_amount,
int128 i,
uint256 min_amount
) external;
function exchange(
int128 from,
int128 to,
uint256 _from_amount,
uint256 _min_to_amount
) external;
function balances(uint256) external view returns (uint256);
function get_dy(
int128 from,
int128 to,
uint256 _from_amount
) external view returns (uint256);
// EURt
function calc_token_amount(uint256[2] calldata _amounts, bool _is_deposit)
external
view
returns (uint256);
// 3Crv Metapools
function calc_token_amount(
address _pool,
uint256[4] calldata _amounts,
bool _is_deposit
) external view returns (uint256);
// sUSD, Y pool, etc
function calc_token_amount(uint256[4] calldata _amounts, bool _is_deposit)
external
view
returns (uint256);
// 3pool, Iron Bank, etc
function calc_token_amount(uint256[3] calldata _amounts, bool _is_deposit)
external
view
returns (uint256);
function calc_withdraw_one_coin(uint256 amount, int128 i)
external
view
returns (uint256);
}
// Part: ICurveStrategyProxy
interface ICurveStrategyProxy {
function proxy() external returns (address);
function balanceOf(address _gauge) external view returns (uint256);
function deposit(address _gauge, address _token) external;
function withdraw(
address _gauge,
address _token,
uint256 _amount
) external returns (uint256);
function withdrawAll(address _gauge, address _token)
external
returns (uint256);
function harvest(address _gauge) external;
function lock() external;
function approveStrategy(address) external;
function revokeStrategy(address) external;
function claimRewards(address _gauge, address _token) external;
}
// Part: IUniV3
interface IUniV3 {
struct ExactInputParams {
bytes path;
address recipient;
uint256 deadline;
uint256 amountIn;
uint256 amountOutMinimum;
}
function exactInput(ExactInputParams calldata params)
external
payable
returns (uint256 amountOut);
}
// Part: OpenZeppelin/[email protected]/Address
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// Part: OpenZeppelin/[email protected]/IERC20
/**
* @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);
}
// Part: OpenZeppelin/[email protected]/Math
/**
* @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);
}
}
// Part: OpenZeppelin/[email protected]/SafeMath
/**
* @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;
}
}
// Part: yearn/[email protected]/HealthCheck
interface HealthCheck {
function check(
uint256 profit,
uint256 loss,
uint256 debtPayment,
uint256 debtOutstanding,
uint256 totalDebt
) external view returns (bool);
}
// Part: OpenZeppelin/[email protected]/SafeERC20
/**
* @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");
}
}
}
// Part: yearn/[email protected]/VaultAPI
interface VaultAPI is IERC20 {
function name() external view returns (string calldata);
function symbol() external view returns (string calldata);
function decimals() external view returns (uint256);
function apiVersion() external pure returns (string memory);
function permit(
address owner,
address spender,
uint256 amount,
uint256 expiry,
bytes calldata signature
) external returns (bool);
// NOTE: Vyper produces multiple signatures for a given function with "default" args
function deposit() external returns (uint256);
function deposit(uint256 amount) external returns (uint256);
function deposit(uint256 amount, address recipient) external returns (uint256);
// NOTE: Vyper produces multiple signatures for a given function with "default" args
function withdraw() external returns (uint256);
function withdraw(uint256 maxShares) external returns (uint256);
function withdraw(uint256 maxShares, address recipient) external returns (uint256);
function token() external view returns (address);
function strategies(address _strategy) external view returns (StrategyParams memory);
function pricePerShare() external view returns (uint256);
function totalAssets() external view returns (uint256);
function depositLimit() external view returns (uint256);
function maxAvailableShares() external view returns (uint256);
/**
* View how much the Vault would increase this Strategy's borrow limit,
* based on its present performance (since its last report). Can be used to
* determine expectedReturn in your Strategy.
*/
function creditAvailable() external view returns (uint256);
/**
* View how much the Vault would like to pull back from the Strategy,
* based on its present performance (since its last report). Can be used to
* determine expectedReturn in your Strategy.
*/
function debtOutstanding() external view returns (uint256);
/**
* View how much the Vault expect this Strategy to return at the current
* block, based on its present performance (since its last report). Can be
* used to determine expectedReturn in your Strategy.
*/
function expectedReturn() external view returns (uint256);
/**
* This is the main contact point where the Strategy interacts with the
* Vault. It is critical that this call is handled as intended by the
* Strategy. Therefore, this function will be called by BaseStrategy to
* make sure the integration is correct.
*/
function report(
uint256 _gain,
uint256 _loss,
uint256 _debtPayment
) external returns (uint256);
/**
* This function should only be used in the scenario where the Strategy is
* being retired but no migration of the positions are possible, or in the
* extreme scenario that the Strategy needs to be put into "Emergency Exit"
* mode in order for it to exit as quickly as possible. The latter scenario
* could be for any reason that is considered "critical" that the Strategy
* exits its position as fast as possible, such as a sudden change in
* market conditions leading to losses, or an imminent failure in an
* external dependency.
*/
function revokeStrategy() external;
/**
* View the governance address of the Vault to assert privileged functions
* can only be called by governance. The Strategy serves the Vault, so it
* is subject to governance defined by the Vault.
*/
function governance() external view returns (address);
/**
* View the management address of the Vault to assert privileged functions
* can only be called by management. The Strategy serves the Vault, so it
* is subject to management defined by the Vault.
*/
function management() external view returns (address);
/**
* View the guardian address of the Vault to assert privileged functions
* can only be called by guardian. The Strategy serves the Vault, so it
* is subject to guardian defined by the Vault.
*/
function guardian() external view returns (address);
}
// Part: yearn/[email protected]/BaseStrategy
/**
* @title Yearn Base Strategy
* @author yearn.finance
* @notice
* BaseStrategy implements all of the required functionality to interoperate
* closely with the Vault contract. This contract should be inherited and the
* abstract methods implemented to adapt the Strategy to the particular needs
* it has to create a return.
*
* Of special interest is the relationship between `harvest()` and
* `vault.report()'. `harvest()` may be called simply because enough time has
* elapsed since the last report, and not because any funds need to be moved
* or positions adjusted. This is critical so that the Vault may maintain an
* accurate picture of the Strategy's performance. See `vault.report()`,
* `harvest()`, and `harvestTrigger()` for further details.
*/
abstract contract BaseStrategy {
using SafeMath for uint256;
using SafeERC20 for IERC20;
string public metadataURI;
// health checks
bool public doHealthCheck;
address public healthCheck;
/**
* @notice
* Used to track which version of `StrategyAPI` this Strategy
* implements.
* @dev The Strategy's version must match the Vault's `API_VERSION`.
* @return A string which holds the current API version of this contract.
*/
function apiVersion() public pure returns (string memory) {
return "0.4.3";
}
/**
* @notice This Strategy's name.
* @dev
* You can use this field to manage the "version" of this Strategy, e.g.
* `StrategySomethingOrOtherV1`. However, "API Version" is managed by
* `apiVersion()` function above.
* @return This Strategy's name.
*/
function name() external view virtual returns (string memory);
/**
* @notice
* The amount (priced in want) of the total assets managed by this strategy should not count
* towards Yearn's TVL calculations.
* @dev
* You can override this field to set it to a non-zero value if some of the assets of this
* Strategy is somehow delegated inside another part of of Yearn's ecosystem e.g. another Vault.
* Note that this value must be strictly less than or equal to the amount provided by
* `estimatedTotalAssets()` below, as the TVL calc will be total assets minus delegated assets.
* Also note that this value is used to determine the total assets under management by this
* strategy, for the purposes of computing the management fee in `Vault`
* @return
* The amount of assets this strategy manages that should not be included in Yearn's Total Value
* Locked (TVL) calculation across it's ecosystem.
*/
function delegatedAssets() external view virtual returns (uint256) {
return 0;
}
VaultAPI public vault;
address public strategist;
address public rewards;
address public keeper;
IERC20 public want;
// So indexers can keep track of this
event Harvested(uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding);
event UpdatedStrategist(address newStrategist);
event UpdatedKeeper(address newKeeper);
event UpdatedRewards(address rewards);
event UpdatedMinReportDelay(uint256 delay);
event UpdatedMaxReportDelay(uint256 delay);
event UpdatedProfitFactor(uint256 profitFactor);
event UpdatedDebtThreshold(uint256 debtThreshold);
event EmergencyExitEnabled();
event UpdatedMetadataURI(string metadataURI);
// The minimum number of seconds between harvest calls. See
// `setMinReportDelay()` for more details.
uint256 public minReportDelay;
// The maximum number of seconds between harvest calls. See
// `setMaxReportDelay()` for more details.
uint256 public maxReportDelay;
// The minimum multiple that `callCost` must be above the credit/profit to
// be "justifiable". See `setProfitFactor()` for more details.
uint256 public profitFactor;
// Use this to adjust the threshold at which running a debt causes a
// harvest trigger. See `setDebtThreshold()` for more details.
uint256 public debtThreshold;
// See note on `setEmergencyExit()`.
bool public emergencyExit;
// modifiers
modifier onlyAuthorized() {
require(msg.sender == strategist || msg.sender == governance(), "!authorized");
_;
}
modifier onlyEmergencyAuthorized() {
require(
msg.sender == strategist || msg.sender == governance() || msg.sender == vault.guardian() || msg.sender == vault.management(),
"!authorized"
);
_;
}
modifier onlyStrategist() {
require(msg.sender == strategist, "!strategist");
_;
}
modifier onlyGovernance() {
require(msg.sender == governance(), "!authorized");
_;
}
modifier onlyKeepers() {
require(
msg.sender == keeper ||
msg.sender == strategist ||
msg.sender == governance() ||
msg.sender == vault.guardian() ||
msg.sender == vault.management(),
"!authorized"
);
_;
}
modifier onlyVaultManagers() {
require(msg.sender == vault.management() || msg.sender == governance(), "!authorized");
_;
}
constructor(address _vault) public {
_initialize(_vault, msg.sender, msg.sender, msg.sender);
}
/**
* @notice
* Initializes the Strategy, this is called only once, when the
* contract is deployed.
* @dev `_vault` should implement `VaultAPI`.
* @param _vault The address of the Vault responsible for this Strategy.
* @param _strategist The address to assign as `strategist`.
* The strategist is able to change the reward address
* @param _rewards The address to use for pulling rewards.
* @param _keeper The adddress of the _keeper. _keeper
* can harvest and tend a strategy.
*/
function _initialize(
address _vault,
address _strategist,
address _rewards,
address _keeper
) internal {
require(address(want) == address(0), "Strategy already initialized");
vault = VaultAPI(_vault);
want = IERC20(vault.token());
want.safeApprove(_vault, uint256(-1)); // Give Vault unlimited access (might save gas)
strategist = _strategist;
rewards = _rewards;
keeper = _keeper;
// initialize variables
minReportDelay = 0;
maxReportDelay = 86400;
profitFactor = 100;
debtThreshold = 0;
vault.approve(rewards, uint256(-1)); // Allow rewards to be pulled
}
function setHealthCheck(address _healthCheck) external onlyVaultManagers {
healthCheck = _healthCheck;
}
function setDoHealthCheck(bool _doHealthCheck) external onlyVaultManagers {
doHealthCheck = _doHealthCheck;
}
/**
* @notice
* Used to change `strategist`.
*
* This may only be called by governance or the existing strategist.
* @param _strategist The new address to assign as `strategist`.
*/
function setStrategist(address _strategist) external onlyAuthorized {
require(_strategist != address(0));
strategist = _strategist;
emit UpdatedStrategist(_strategist);
}
/**
* @notice
* Used to change `keeper`.
*
* `keeper` is the only address that may call `tend()` or `harvest()`,
* other than `governance()` or `strategist`. However, unlike
* `governance()` or `strategist`, `keeper` may *only* call `tend()`
* and `harvest()`, and no other authorized functions, following the
* principle of least privilege.
*
* This may only be called by governance or the strategist.
* @param _keeper The new address to assign as `keeper`.
*/
function setKeeper(address _keeper) external onlyAuthorized {
require(_keeper != address(0));
keeper = _keeper;
emit UpdatedKeeper(_keeper);
}
/**
* @notice
* Used to change `rewards`. EOA or smart contract which has the permission
* to pull rewards from the vault.
*
* This may only be called by the strategist.
* @param _rewards The address to use for pulling rewards.
*/
function setRewards(address _rewards) external onlyStrategist {
require(_rewards != address(0));
vault.approve(rewards, 0);
rewards = _rewards;
vault.approve(rewards, uint256(-1));
emit UpdatedRewards(_rewards);
}
/**
* @notice
* Used to change `minReportDelay`. `minReportDelay` is the minimum number
* of blocks that should pass for `harvest()` to be called.
*
* For external keepers (such as the Keep3r network), this is the minimum
* time between jobs to wait. (see `harvestTrigger()`
* for more details.)
*
* This may only be called by governance or the strategist.
* @param _delay The minimum number of seconds to wait between harvests.
*/
function setMinReportDelay(uint256 _delay) external onlyAuthorized {
minReportDelay = _delay;
emit UpdatedMinReportDelay(_delay);
}
/**
* @notice
* Used to change `maxReportDelay`. `maxReportDelay` is the maximum number
* of blocks that should pass for `harvest()` to be called.
*
* For external keepers (such as the Keep3r network), this is the maximum
* time between jobs to wait. (see `harvestTrigger()`
* for more details.)
*
* This may only be called by governance or the strategist.
* @param _delay The maximum number of seconds to wait between harvests.
*/
function setMaxReportDelay(uint256 _delay) external onlyAuthorized {
maxReportDelay = _delay;
emit UpdatedMaxReportDelay(_delay);
}
/**
* @notice
* Used to change `profitFactor`. `profitFactor` is used to determine
* if it's worthwhile to harvest, given gas costs. (See `harvestTrigger()`
* for more details.)
*
* This may only be called by governance or the strategist.
* @param _profitFactor A ratio to multiply anticipated
* `harvest()` gas cost against.
*/
function setProfitFactor(uint256 _profitFactor) external onlyAuthorized {
profitFactor = _profitFactor;
emit UpdatedProfitFactor(_profitFactor);
}
/**
* @notice
* Sets how far the Strategy can go into loss without a harvest and report
* being required.
*
* By default this is 0, meaning any losses would cause a harvest which
* will subsequently report the loss to the Vault for tracking. (See
* `harvestTrigger()` for more details.)
*
* This may only be called by governance or the strategist.
* @param _debtThreshold How big of a loss this Strategy may carry without
* being required to report to the Vault.
*/
function setDebtThreshold(uint256 _debtThreshold) external onlyAuthorized {
debtThreshold = _debtThreshold;
emit UpdatedDebtThreshold(_debtThreshold);
}
/**
* @notice
* Used to change `metadataURI`. `metadataURI` is used to store the URI
* of the file describing the strategy.
*
* This may only be called by governance or the strategist.
* @param _metadataURI The URI that describe the strategy.
*/
function setMetadataURI(string calldata _metadataURI) external onlyAuthorized {
metadataURI = _metadataURI;
emit UpdatedMetadataURI(_metadataURI);
}
/**
* Resolve governance address from Vault contract, used to make assertions
* on protected functions in the Strategy.
*/
function governance() internal view returns (address) {
return vault.governance();
}
/**
* @notice
* Provide an accurate conversion from `_amtInWei` (denominated in wei)
* to `want` (using the native decimal characteristics of `want`).
* @dev
* Care must be taken when working with decimals to assure that the conversion
* is compatible. As an example:
*
* given 1e17 wei (0.1 ETH) as input, and want is USDC (6 decimals),
* with USDC/ETH = 1800, this should give back 1800000000 (180 USDC)
*
* @param _amtInWei The amount (in wei/1e-18 ETH) to convert to `want`
* @return The amount in `want` of `_amtInEth` converted to `want`
**/
function ethToWant(uint256 _amtInWei) public view virtual returns (uint256);
/**
* @notice
* Provide an accurate estimate for the total amount of assets
* (principle + return) that this Strategy is currently managing,
* denominated in terms of `want` tokens.
*
* This total should be "realizable" e.g. the total value that could
* *actually* be obtained from this Strategy if it were to divest its
* entire position based on current on-chain conditions.
* @dev
* Care must be taken in using this function, since it relies on external
* systems, which could be manipulated by the attacker to give an inflated
* (or reduced) value produced by this function, based on current on-chain
* conditions (e.g. this function is possible to influence through
* flashloan attacks, oracle manipulations, or other DeFi attack
* mechanisms).
*
* It is up to governance to use this function to correctly order this
* Strategy relative to its peers in the withdrawal queue to minimize
* losses for the Vault based on sudden withdrawals. This value should be
* higher than the total debt of the Strategy and higher than its expected
* value to be "safe".
* @return The estimated total assets in this Strategy.
*/
function estimatedTotalAssets() public view virtual returns (uint256);
/*
* @notice
* Provide an indication of whether this strategy is currently "active"
* in that it is managing an active position, or will manage a position in
* the future. This should correlate to `harvest()` activity, so that Harvest
* events can be tracked externally by indexing agents.
* @return True if the strategy is actively managing a position.
*/
function isActive() public view returns (bool) {
return vault.strategies(address(this)).debtRatio > 0 || estimatedTotalAssets() > 0;
}
/**
* Perform any Strategy unwinding or other calls necessary to capture the
* "free return" this Strategy has generated since the last time its core
* position(s) were adjusted. Examples include unwrapping extra rewards.
* This call is only used during "normal operation" of a Strategy, and
* should be optimized to minimize losses as much as possible.
*
* This method returns any realized profits and/or realized losses
* incurred, and should return the total amounts of profits/losses/debt
* payments (in `want` tokens) for the Vault's accounting (e.g.
* `want.balanceOf(this) >= _debtPayment + _profit`).
*
* `_debtOutstanding` will be 0 if the Strategy is not past the configured
* debt limit, otherwise its value will be how far past the debt limit
* the Strategy is. The Strategy's debt limit is configured in the Vault.
*
* NOTE: `_debtPayment` should be less than or equal to `_debtOutstanding`.
* It is okay for it to be less than `_debtOutstanding`, as that
* should only used as a guide for how much is left to pay back.
* Payments should be made to minimize loss from slippage, debt,
* withdrawal fees, etc.
*
* See `vault.debtOutstanding()`.
*/
function prepareReturn(uint256 _debtOutstanding)
internal
virtual
returns (
uint256 _profit,
uint256 _loss,
uint256 _debtPayment
);
/**
* Perform any adjustments to the core position(s) of this Strategy given
* what change the Vault made in the "investable capital" available to the
* Strategy. Note that all "free capital" in the Strategy after the report
* was made is available for reinvestment. Also note that this number
* could be 0, and you should handle that scenario accordingly.
*
* See comments regarding `_debtOutstanding` on `prepareReturn()`.
*/
function adjustPosition(uint256 _debtOutstanding) internal virtual;
/**
* Liquidate up to `_amountNeeded` of `want` of this strategy's positions,
* irregardless of slippage. Any excess will be re-invested with `adjustPosition()`.
* This function should return the amount of `want` tokens made available by the
* liquidation. If there is a difference between them, `_loss` indicates whether the
* difference is due to a realized loss, or if there is some other sitution at play
* (e.g. locked funds) where the amount made available is less than what is needed.
*
* NOTE: The invariant `_liquidatedAmount + _loss <= _amountNeeded` should always be maintained
*/
function liquidatePosition(uint256 _amountNeeded) internal virtual returns (uint256 _liquidatedAmount, uint256 _loss);
/**
* Liquidate everything and returns the amount that got freed.
* This function is used during emergency exit instead of `prepareReturn()` to
* liquidate all of the Strategy's positions back to the Vault.
*/
function liquidateAllPositions() internal virtual returns (uint256 _amountFreed);
/**
* @notice
* Provide a signal to the keeper that `tend()` should be called. The
* keeper will provide the estimated gas cost that they would pay to call
* `tend()`, and this function should use that estimate to make a
* determination if calling it is "worth it" for the keeper. This is not
* the only consideration into issuing this trigger, for example if the
* position would be negatively affected if `tend()` is not called
* shortly, then this can return `true` even if the keeper might be
* "at a loss" (keepers are always reimbursed by Yearn).
* @dev
* `callCostInWei` must be priced in terms of `wei` (1e-18 ETH).
*
* This call and `harvestTrigger()` should never return `true` at the same
* time.
* @param callCostInWei The keeper's estimated gas cost to call `tend()` (in wei).
* @return `true` if `tend()` should be called, `false` otherwise.
*/
function tendTrigger(uint256 callCostInWei) public view virtual returns (bool) {
// We usually don't need tend, but if there are positions that need
// active maintainence, overriding this function is how you would
// signal for that.
// If your implementation uses the cost of the call in want, you can
// use uint256 callCost = ethToWant(callCostInWei);
return false;
}
/**
* @notice
* Adjust the Strategy's position. The purpose of tending isn't to
* realize gains, but to maximize yield by reinvesting any returns.
*
* See comments on `adjustPosition()`.
*
* This may only be called by governance, the strategist, or the keeper.
*/
function tend() external onlyKeepers {
// Don't take profits with this call, but adjust for better gains
adjustPosition(vault.debtOutstanding());
}
/**
* @notice
* Provide a signal to the keeper that `harvest()` should be called. The
* keeper will provide the estimated gas cost that they would pay to call
* `harvest()`, and this function should use that estimate to make a
* determination if calling it is "worth it" for the keeper. This is not
* the only consideration into issuing this trigger, for example if the
* position would be negatively affected if `harvest()` is not called
* shortly, then this can return `true` even if the keeper might be "at a
* loss" (keepers are always reimbursed by Yearn).
* @dev
* `callCostInWei` must be priced in terms of `wei` (1e-18 ETH).
*
* This call and `tendTrigger` should never return `true` at the
* same time.
*
* See `min/maxReportDelay`, `profitFactor`, `debtThreshold` to adjust the
* strategist-controlled parameters that will influence whether this call
* returns `true` or not. These parameters will be used in conjunction
* with the parameters reported to the Vault (see `params`) to determine
* if calling `harvest()` is merited.
*
* It is expected that an external system will check `harvestTrigger()`.
* This could be a script run off a desktop or cloud bot (e.g.
* https://github.com/iearn-finance/yearn-vaults/blob/main/scripts/keep.py),
* or via an integration with the Keep3r network (e.g.
* https://github.com/Macarse/GenericKeep3rV2/blob/master/contracts/keep3r/GenericKeep3rV2.sol).
* @param callCostInWei The keeper's estimated gas cost to call `harvest()` (in wei).
* @return `true` if `harvest()` should be called, `false` otherwise.
*/
function harvestTrigger(uint256 callCostInWei) public view virtual returns (bool) {
uint256 callCost = ethToWant(callCostInWei);
StrategyParams memory params = vault.strategies(address(this));
// Should not trigger if Strategy is not activated
if (params.activation == 0) return false;
// Should not trigger if we haven't waited long enough since previous harvest
if (block.timestamp.sub(params.lastReport) < minReportDelay) return false;
// Should trigger if hasn't been called in a while
if (block.timestamp.sub(params.lastReport) >= maxReportDelay) return true;
// If some amount is owed, pay it back
// NOTE: Since debt is based on deposits, it makes sense to guard against large
// changes to the value from triggering a harvest directly through user
// behavior. This should ensure reasonable resistance to manipulation
// from user-initiated withdrawals as the outstanding debt fluctuates.
uint256 outstanding = vault.debtOutstanding();
if (outstanding > debtThreshold) return true;
// Check for profits and losses
uint256 total = estimatedTotalAssets();
// Trigger if we have a loss to report
if (total.add(debtThreshold) < params.totalDebt) return true;
uint256 profit = 0;
if (total > params.totalDebt) profit = total.sub(params.totalDebt); // We've earned a profit!
// Otherwise, only trigger if it "makes sense" economically (gas cost
// is <N% of value moved)
uint256 credit = vault.creditAvailable();
return (profitFactor.mul(callCost) < credit.add(profit));
}
/**
* @notice
* Harvests the Strategy, recognizing any profits or losses and adjusting
* the Strategy's position.
*
* In the rare case the Strategy is in emergency shutdown, this will exit
* the Strategy's position.
*
* This may only be called by governance, the strategist, or the keeper.
* @dev
* When `harvest()` is called, the Strategy reports to the Vault (via
* `vault.report()`), so in some cases `harvest()` must be called in order
* to take in profits, to borrow newly available funds from the Vault, or
* otherwise adjust its position. In other cases `harvest()` must be
* called to report to the Vault on the Strategy's position, especially if
* any losses have occurred.
*/
function harvest() external onlyKeepers {
uint256 profit = 0;
uint256 loss = 0;
uint256 debtOutstanding = vault.debtOutstanding();
uint256 debtPayment = 0;
if (emergencyExit) {
// Free up as much capital as possible
uint256 amountFreed = liquidateAllPositions();
if (amountFreed < debtOutstanding) {
loss = debtOutstanding.sub(amountFreed);
} else if (amountFreed > debtOutstanding) {
profit = amountFreed.sub(debtOutstanding);
}
debtPayment = debtOutstanding.sub(loss);
} else {
// Free up returns for Vault to pull
(profit, loss, debtPayment) = prepareReturn(debtOutstanding);
}
// Allow Vault to take up to the "harvested" balance of this contract,
// which is the amount it has earned since the last time it reported to
// the Vault.
uint256 totalDebt = vault.strategies(address(this)).totalDebt;
debtOutstanding = vault.report(profit, loss, debtPayment);
// Check if free returns are left, and re-invest them
adjustPosition(debtOutstanding);
// call healthCheck contract
if (doHealthCheck && healthCheck != address(0)) {
require(HealthCheck(healthCheck).check(profit, loss, debtPayment, debtOutstanding, totalDebt), "!healthcheck");
} else {
doHealthCheck = true;
}
emit Harvested(profit, loss, debtPayment, debtOutstanding);
}
/**
* @notice
* Withdraws `_amountNeeded` to `vault`.
*
* This may only be called by the Vault.
* @param _amountNeeded How much `want` to withdraw.
* @return _loss Any realized losses
*/
function withdraw(uint256 _amountNeeded) external returns (uint256 _loss) {
require(msg.sender == address(vault), "!vault");
// Liquidate as much as possible to `want`, up to `_amountNeeded`
uint256 amountFreed;
(amountFreed, _loss) = liquidatePosition(_amountNeeded);
// Send it directly back (NOTE: Using `msg.sender` saves some gas here)
want.safeTransfer(msg.sender, amountFreed);
// NOTE: Reinvest anything leftover on next `tend`/`harvest`
}
/**
* Do anything necessary to prepare this Strategy for migration, such as
* transferring any reserve or LP tokens, CDPs, or other tokens or stores of
* value.
*/
function prepareMigration(address _newStrategy) internal virtual;
/**
* @notice
* Transfers all `want` from this Strategy to `_newStrategy`.
*
* This may only be called by the Vault.
* @dev
* The new Strategy's Vault must be the same as this Strategy's Vault.
* The migration process should be carefully performed to make sure all
* the assets are migrated to the new address, which should have never
* interacted with the vault before.
* @param _newStrategy The Strategy to migrate to.
*/
function migrate(address _newStrategy) external {
require(msg.sender == address(vault));
require(BaseStrategy(_newStrategy).vault() == vault);
prepareMigration(_newStrategy);
want.safeTransfer(_newStrategy, want.balanceOf(address(this)));
}
/**
* @notice
* Activates emergency exit. Once activated, the Strategy will exit its
* position upon the next harvest, depositing all funds into the Vault as
* quickly as is reasonable given on-chain conditions.
*
* This may only be called by governance or the strategist.
* @dev
* See `vault.setEmergencyShutdown()` and `harvest()` for further details.
*/
function setEmergencyExit() external onlyEmergencyAuthorized {
emergencyExit = true;
vault.revokeStrategy();
emit EmergencyExitEnabled();
}
/**
* Override this to add all tokens/tokenized positions this contract
* manages on a *persistent* basis (e.g. not just for swapping back to
* want ephemerally).
*
* NOTE: Do *not* include `want`, already included in `sweep` below.
*
* Example:
* ```
* function protectedTokens() internal override view returns (address[] memory) {
* address[] memory protected = new address[](3);
* protected[0] = tokenA;
* protected[1] = tokenB;
* protected[2] = tokenC;
* return protected;
* }
* ```
*/
function protectedTokens() internal view virtual returns (address[] memory);
/**
* @notice
* Removes tokens from this Strategy that are not the type of tokens
* managed by this Strategy. This may be used in case of accidentally
* sending the wrong kind of token to this Strategy.
*
* Tokens will be sent to `governance()`.
*
* This will fail if an attempt is made to sweep `want`, or any tokens
* that are protected by this Strategy.
*
* This may only be called by governance.
* @dev
* Implement `protectedTokens()` to specify any additional tokens that
* should be protected from sweeping in addition to `want`.
* @param _token The token to transfer out of this vault.
*/
function sweep(address _token) external onlyGovernance {
require(_token != address(want), "!want");
require(_token != address(vault), "!shares");
address[] memory _protectedTokens = protectedTokens();
for (uint256 i; i < _protectedTokens.length; i++) require(_token != _protectedTokens[i], "!protected");
IERC20(_token).safeTransfer(governance(), IERC20(_token).balanceOf(address(this)));
}
}
// Part: StrategyCurveBase
abstract contract StrategyCurveBase is BaseStrategy {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
/* ========== STATE VARIABLES ========== */
// these should stay the same across different wants.
// curve infrastructure contracts
ICurveStrategyProxy public proxy =
ICurveStrategyProxy(0xA420A63BbEFfbda3B147d0585F1852C358e2C152); // Yearn's Updated v4 StrategyProxy
address public constant gauge = 0x4Fd86Ce7Ecea88F7E0aA78DC12625996Fb3a04bC; // Curve gauge contract, most are tokenized, held by Yearn's voter
// keepCRV stuff
uint256 public keepCRV = 1000; // the percentage of CRV we re-lock for boost (in basis points)
uint256 internal constant FEE_DENOMINATOR = 10000; // this means all of our fee values are in basis points
address public constant voter = 0xF147b8125d2ef93FB6965Db97D6746952a133934; // Yearn's veCRV voter
// swap stuff
address internal constant sushiswap =
0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F; // default to sushiswap, more CRV liquidity there
IERC20 internal constant crv =
IERC20(0xD533a949740bb3306d119CC777fa900bA034cd52);
IERC20 internal constant weth =
IERC20(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
bool internal forceHarvestTriggerOnce; // only set this to true externally when we want to trigger our keepers to harvest for us
string internal stratName; // set our strategy name here
/* ========== CONSTRUCTOR ========== */
constructor(address _vault) public BaseStrategy(_vault) {}
/* ========== VIEWS ========== */
function name() external view override returns (string memory) {
return stratName;
}
function stakedBalance() public view returns (uint256) {
return proxy.balanceOf(gauge);
}
function balanceOfWant() public view returns (uint256) {
return want.balanceOf(address(this));
}
function estimatedTotalAssets() public view override returns (uint256) {
return balanceOfWant().add(stakedBalance());
}
/* ========== MUTATIVE FUNCTIONS ========== */
// these should stay the same across different wants.
function adjustPosition(uint256 _debtOutstanding) internal override {
if (emergencyExit) {
return;
}
// Send all of our LP tokens to the proxy and deposit to the gauge if we have any
uint256 _toInvest = balanceOfWant();
if (_toInvest > 0) {
want.safeTransfer(address(proxy), _toInvest);
proxy.deposit(gauge, address(want));
}
}
function liquidatePosition(uint256 _amountNeeded)
internal
override
returns (uint256 _liquidatedAmount, uint256 _loss)
{
uint256 _wantBal = balanceOfWant();
if (_amountNeeded > _wantBal) {
// check if we have enough free funds to cover the withdrawal
uint256 _stakedBal = stakedBalance();
if (_stakedBal > 0) {
proxy.withdraw(
gauge,
address(want),
Math.min(_stakedBal, _amountNeeded.sub(_wantBal))
);
}
uint256 _withdrawnBal = balanceOfWant();
_liquidatedAmount = Math.min(_amountNeeded, _withdrawnBal);
_loss = _amountNeeded.sub(_liquidatedAmount);
} else {
// we have enough balance to cover the liquidation available
return (_amountNeeded, 0);
}
}
// fire sale, get rid of it all!
function liquidateAllPositions() internal override returns (uint256) {
uint256 _stakedBal = stakedBalance();
if (_stakedBal > 0) {
// don't bother withdrawing zero
proxy.withdraw(gauge, address(want), _stakedBal);
}
return balanceOfWant();
}
function prepareMigration(address _newStrategy) internal override {
uint256 _stakedBal = stakedBalance();
if (_stakedBal > 0) {
proxy.withdraw(gauge, address(want), _stakedBal);
}
}
function protectedTokens()
internal
view
override
returns (address[] memory)
{}
/* ========== SETTERS ========== */
// These functions are useful for setting parameters of the strategy that may need to be adjusted.
// Use to update Yearn's StrategyProxy contract as needed in case of upgrades.
function setProxy(address _proxy) external onlyGovernance {
proxy = ICurveStrategyProxy(_proxy);
}
// Set the amount of CRV to be locked in Yearn's veCRV voter from each harvest. Default is 10%.
function setKeepCRV(uint256 _keepCRV) external onlyAuthorized {
require(_keepCRV <= 10_000);
keepCRV = _keepCRV;
}
// This allows us to manually harvest with our keeper as needed
function setForceHarvestTriggerOnce(bool _forceHarvestTriggerOnce)
external
onlyAuthorized
{
forceHarvestTriggerOnce = _forceHarvestTriggerOnce;
}
}
// File: StrategyCurveEURTUSD.sol
contract StrategyCurveEURTUSD is StrategyCurveBase {
/* ========== STATE VARIABLES ========== */
// these will likely change across different wants.
// Curve stuff
ICurveFi public constant curve =
ICurveFi(0x5D0F47B32fDd343BfA74cE221808e2abE4A53827); // This is our pool specific to this vault.
// we use these to deposit to our curve pool
uint256 internal optimal; // this is the optimal token to deposit back to our curve pool. 0 DAI, 1 USDC, 2 USDT, 3 EURT
address public targetStable;
address internal constant uniswapv3 =
address(0xE592427A0AEce92De3Edee1F18E0157C05861564);
IERC20 internal constant usdt =
IERC20(0xdAC17F958D2ee523a2206206994597C13D831ec7);
IERC20 internal constant usdc =
IERC20(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48);
IERC20 internal constant dai =
IERC20(0x6B175474E89094C44Da98b954EedeAC495271d0F);
IERC20 internal constant eurt =
IERC20(0xC581b735A1688071A1746c968e0798D642EDE491);
uint24 public uniCrvFee; // this is equal to 1%, can change this later if a different path becomes more optimal
uint24 public uniStableFee; // this is equal to 0.05%, can change this later if a different path becomes more optimal
uint24 public uniEurtFee; // this is equal to 0.05%, can change this later if a different path becomes more optimal
/* ========== CONSTRUCTOR ========== */
constructor(
address _vault,
string memory _name
) public StrategyCurveBase(_vault) {
// You can set these parameters on deployment to whatever you want
maxReportDelay = 7 days; // 7 days in seconds
minReportDelay = 3 days; // 3 days in seconds
healthCheck = 0xDDCea799fF1699e98EDF118e0629A974Df7DF012; // health.ychad.eth
// these are our standard approvals. want = Curve LP token
want.approve(address(proxy), type(uint256).max);
crv.approve(uniswapv3, type(uint256).max);
weth.approve(uniswapv3, type(uint256).max);
// set our keepCRV
keepCRV = 1000;
// set our strategy's name
stratName = _name;
// these are our approvals and path specific to this contract
dai.approve(address(curve), type(uint256).max);
usdt.safeApprove(address(curve), type(uint256).max); // USDT requires safeApprove(), funky token
eurt.safeApprove(address(curve), type(uint256).max); // EURT requires safeApprove(), funky token
usdc.approve(address(curve), type(uint256).max);
// set our uniswap pool fees
uniCrvFee = 10000;
uniStableFee = 500;
uniEurtFee = 500;
// start with dai as our target
targetStable = address(dai);
}
/* ========== MUTATIVE FUNCTIONS ========== */
// these will likely change across different wants.
function prepareReturn(uint256 _debtOutstanding)
internal
override
returns (
uint256 _profit,
uint256 _loss,
uint256 _debtPayment
)
{
// if we have anything in the gauge, then harvest CRV from the gauge
uint256 _stakedBal = stakedBalance();
if (_stakedBal > 0) {
proxy.harvest(gauge);
uint256 _crvBalance = crv.balanceOf(address(this));
// if we claimed any CRV, then sell it
if (_crvBalance > 0) {
// keep some of our CRV to increase our boost
uint256 _sendToVoter =
_crvBalance.mul(keepCRV).div(FEE_DENOMINATOR);
if (keepCRV > 0) {
crv.safeTransfer(voter, _sendToVoter);
}
uint256 _crvRemainder = _crvBalance.sub(_sendToVoter);
// sell the rest of our CRV
if (_crvRemainder > 0) {
_sellCrv(_crvRemainder);
}
// deposit our balance to Curve if we have any
if (optimal == 0) {
uint256 _daiBalance = dai.balanceOf(address(this));
if (_daiBalance > 0) {
curve.add_liquidity([0, _daiBalance, 0, 0], 0);
}
} else if (optimal == 1) {
uint256 _usdcBalance = usdc.balanceOf(address(this));
if (_usdcBalance > 0) {
curve.add_liquidity([0, 0, _usdcBalance, 0], 0);
}
} else if (optimal == 2) {
uint256 _usdtBalance = usdt.balanceOf(address(this));
if (_usdtBalance > 0) {
curve.add_liquidity([0, 0, 0, _usdtBalance], 0);
}
} else {
uint256 eurtBalance = eurt.balanceOf(address(this));
if (eurtBalance > 0) {
curve.add_liquidity([eurtBalance, 0, 0, 0], 0);
}
}
}
}
// debtOustanding will only be > 0 in the event of revoking or if we need to rebalance from a withdrawal or lowering the debtRatio
if (_debtOutstanding > 0) {
if (_stakedBal > 0) {
// don't bother withdrawing if we don't have staked funds
proxy.withdraw(
gauge,
address(want),
Math.min(_stakedBal, _debtOutstanding)
);
}
uint256 _withdrawnBal = balanceOfWant();
_debtPayment = Math.min(_debtOutstanding, _withdrawnBal);
}
// serious loss should never happen, but if it does (for instance, if Curve is hacked), let's record it accurately
uint256 assets = estimatedTotalAssets();
uint256 debt = vault.strategies(address(this)).totalDebt;
// if assets are greater than debt, things are working great!
if (assets > debt) {
_profit = assets.sub(debt);
uint256 _wantBal = balanceOfWant();
if (_profit.add(_debtPayment) > _wantBal) {
// this should only be hit following donations to strategy
liquidateAllPositions();
}
}
// if assets are less than debt, we are in trouble
else {
_loss = debt.sub(assets);
}
// we're done harvesting, so reset our trigger if we used it
forceHarvestTriggerOnce = false;
}
// Sells our CRV -> WETH -> stables together on UniV3
function _sellCrv(uint256 _crvAmount) internal {
IUniV3(uniswapv3).exactInput(
IUniV3.ExactInputParams(
abi.encodePacked(
address(crv),
uint24(uniCrvFee),
address(weth)
),
address(this),
block.timestamp,
_crvAmount,
uint256(1)
)
);
if (optimal != 3) {
uint256 _wethBalance = weth.balanceOf(address(this));
IUniV3(uniswapv3).exactInput(
IUniV3.ExactInputParams(
abi.encodePacked(
address(weth),
uint24(uniStableFee),
address(targetStable)
),
address(this),
block.timestamp,
_wethBalance,
uint256(1)
)
);
} else {
uint256 _wethBalance = weth.balanceOf(address(this));
IUniV3(uniswapv3).exactInput(
IUniV3.ExactInputParams(
abi.encodePacked(
address(weth),
uint24(uniStableFee),
address(usdt),
uint24(uniEurtFee),
address(eurt)
),
address(this),
block.timestamp,
_wethBalance,
uint256(1)
)
);
}
}
/* ========== KEEP3RS ========== */
function harvestTrigger(uint256 callCostinEth)
public
view
override
returns (bool)
{
StrategyParams memory params = vault.strategies(address(this));
// harvest no matter what once we reach our maxDelay
if (block.timestamp.sub(params.lastReport) > maxReportDelay) {
return true;
}
// check if the base fee gas price is higher than we allow. if it is, block harvests.
if (!isBaseFeeAcceptable()) {
return false;
}
// trigger if we want to manually harvest
if (forceHarvestTriggerOnce) {
return true;
}
// harvest if we hit our minDelay, but only if our gas price is acceptable
if (block.timestamp.sub(params.lastReport) > minReportDelay) {
return true;
}
// otherwise, we don't harvest
return false;
}
// convert our keeper's eth cost into want, we don't need this anymore since we don't use baseStrategy harvestTrigger
function ethToWant(uint256 _ethAmount)
public
view
override
returns (uint256)
{
return _ethAmount;
}
// check if the current baseFee is below our external target
function isBaseFeeAcceptable() internal view returns (bool) {
return
IBaseFee(0xb5e1CAcB567d98faaDB60a1fD4820720141f064F)
.isCurrentBaseFeeAcceptable();
}
/* ========== SETTERS ========== */
// These functions are useful for setting parameters of the strategy that may need to be adjusted.
// Set optimal token to sell harvested funds for depositing to Curve.
// Default is DAI, but can be set to USDC or USDT or EURT as needed by strategist or governance.
function setOptimal(uint256 _optimal) external onlyAuthorized {
if (_optimal == 0) {
targetStable = address(dai);
optimal = 0;
} else if (_optimal == 1) {
targetStable = address(usdc);
optimal = 1;
} else if (_optimal == 2) {
targetStable = address(usdt);
optimal = 2;
} else if (_optimal == 3) {
targetStable = address(eurt);
optimal = 3;
} else {
revert("incorrect token");
}
}
// set the fee pool we'd like to swap through for CRV on UniV3 (1% = 10_000)
function setUniFees(
uint24 _crvFee,
uint24 _stableFee,
uint24 _eurtFee
) external onlyAuthorized {
uniCrvFee = _crvFee;
uniStableFee = _stableFee;
uniEurtFee = _eurtFee;
}
}
|
Set optimal token to sell harvested funds for depositing to Curve. Default is DAI, but can be set to USDC or USDT or EURT as needed by strategist or governance.
|
function setOptimal(uint256 _optimal) external onlyAuthorized {
if (_optimal == 0) {
targetStable = address(dai);
optimal = 0;
targetStable = address(usdc);
optimal = 1;
targetStable = address(usdt);
optimal = 2;
targetStable = address(eurt);
optimal = 3;
revert("incorrect token");
}
}
| 1,126,766 |
pragma solidity ^0.4.13;
contract Owned {
modifier only_owner {
if (msg.sender != owner)
return;
_;
}
event NewOwner(address indexed old, address indexed current);
function setOwner(address _new) only_owner { NewOwner(owner, _new); owner = _new; }
address public owner = msg.sender;
}
library Math {
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;
}
}
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
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() {
require(!paused);
_;
}
/**
* @dev modifier to allow actions only when the contract IS NOT paused
*/
modifier whenPaused {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused returns (bool) {
paused = true;
Pause();
return true;
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused returns (bool) {
paused = false;
Unpause();
return true;
}
}
contract LegalLazyScheduler is Ownable {
uint64 public lastUpdate;
uint64 public intervalDuration;
bool schedulerEnabled = false;
function() internal callback;
event LogRegisteredInterval(uint64 date, uint64 duration);
event LogProcessedInterval(uint64 date, uint64 intervals);
/**
* Triggers the registered callback function for the number of periods passed since last update
*/
modifier intervalTrigger() {
uint64 currentTime = uint64(now);
uint64 requiredIntervals = (currentTime - lastUpdate) / intervalDuration;
if( schedulerEnabled && (requiredIntervals > 0)) {
LogProcessedInterval(lastUpdate, requiredIntervals);
while (requiredIntervals-- > 0) {
callback();
}
lastUpdate = currentTime;
}
_;
}
function LegalLazyScheduler() {
lastUpdate = uint64(now);
}
function enableScheduler() onlyOwner public {
schedulerEnabled = true;
}
function registerIntervalCall(uint64 _intervalDuration, function() internal _callback) internal {
lastUpdate = uint64(now);
intervalDuration = _intervalDuration;
callback = _callback;
LogRegisteredInterval(lastUpdate, intervalDuration);
}
}
contract RefundVault is Ownable {
using SafeMath for uint256;
enum State { Active, Refunding, Closed }
mapping (address => uint256) public deposited;
address public wallet;
State public state;
event Closed();
event RefundsEnabled();
event Refunded(address indexed beneficiary, uint256 weiAmount);
function RefundVault(address _wallet) {
require(_wallet != 0x0);
wallet = _wallet;
state = State.Active;
}
function deposit(address investor) onlyOwner public payable {
require(state == State.Active);
deposited[investor] = deposited[investor].add(msg.value);
}
function close() onlyOwner {
require(state == State.Active);
state = State.Closed;
Closed();
wallet.transfer(this.balance);
}
function enableRefunds() onlyOwner {
require(state == State.Active);
state = State.Refunding;
RefundsEnabled();
}
function refund(address investor) public {
require(state == State.Refunding);
uint256 depositedValue = deposited[investor];
deposited[investor] = 0;
investor.transfer(depositedValue);
Refunded(investor, depositedValue);
}
}
contract LegalTGE is Ownable, Pausable {
/**
* The safe math library for safety math opertations provided by Zeppelin
*/
using SafeMath for uint256;
/** State machine
* - PreparePreContribution: During this phase SmartOne adjust conversionRate and start/end date
* - PreContribution: During this phase only registered users can contribute to the TGE and therefore receive a bonus until cap or end date is reached
* - PrepareContribution: During this phase SmartOne adjusts conversionRate by the ETHUSD depreciation during PreContribution and change start and end date in case of an unforseen event
* - Contribution: During this all users can contribute until cap or end date is reached
* - Auditing: SmartOne awaits recommendation by auditor and board of foundation will then finalize contribution or enable refunding
* - Finalized: Token are released
* - Refunding: Refunds can be claimed
*/
enum States{PreparePreContribution, PreContribution, PrepareContribution, Contribution, Auditing, Finalized, Refunding}
enum VerificationLevel { None, SMSVerified, KYCVerified }
/**
* Whenever the state of the contract changes, this event will be fired.
*/
event LogStateChange(States _states);
/**
* This event is fired when a user has been successfully verified by the external KYC verification process
*/
event LogKYCConfirmation(address sender);
/**
* Whenever a legalToken is assigned to this contract, this event will be fired.
*/
event LogTokenAssigned(address sender, address newToken);
/**
* Every timed transition must be loged for auditing
*/
event LogTimedTransition(uint _now, States _newState);
/**
* This event is fired when PreContribution data is changed during the PreparePreContribution phase
*/
event LogPreparePreContribution(address sender, uint conversionRate, uint startDate, uint endDate);
/**
* A user has transfered Ether and received unreleasead tokens in return
*/
event LogContribution(address contributor, uint256 weiAmount, uint256 tokenAmount, VerificationLevel verificationLevel, States _state);
/**
* This event will be fired when SmartOne finalizes the TGE
*/
event LogFinalized(address sender);
/**
* This event will be fired when the auditor confirms the confirms regularity confirmity
*/
event LogRegularityConfirmation(address sender, bool _regularity, bytes32 _comment);
/**
* This event will be fired when refunding is enabled by the auditor
*/
event LogRefundsEnabled(address sender);
/**
* This event is fired when PreContribution data is changed during the PreparePreContribution phase
*/
event LogPrepareContribution(address sender, uint conversionRate, uint startDate, uint endDate);
/**
* This refund vault used to hold funds while TGE is running.
* Uses the default implementation provided by the OpenZeppelin community.
*/
RefundVault public vault;
/**
* Defines the state of the conotribution process
*/
States public state;
/**
* The token we are giving the contributors in return for their contributions
*/
LegalToken public token;
/**
* The contract provided by Parity Tech (Gav Woods) to verify the mobile number during user registration
*/
ProofOfSMS public proofOfSMS;
/**
* The contribution (wei) will be forwarded to this address after the token has been finalized by the foundation board
*/
address public multisigWallet;
/**
* Maximum amount of wei this TGE can raise.
*/
uint256 public tokenCap;
/**
* The amount of wei a contributor has contributed.
* Used to check whether the total of contributions per user exceeds the max limit (depending on his verification level)
*/
mapping (address => uint) public weiPerContributor;
/**
* Minimum amount of tokens a contributor is able to buy
*/
uint256 public minWeiPerContributor;
/**
* Maximum amount of tokens an SMS verified user can contribute.
*/
uint256 public maxWeiSMSVerified;
/**
* Maximum amount of tokens an none-verified user can contribute.
*/
uint256 public maxWeiUnverified;
/*
* The number of token units a contributor receives per ETHER during pre-contribtion phase
*/
uint public preSaleConversionRate;
/*
* The UNIX timestamp (in seconds) defining when the pre-contribution phase will start
*/
uint public preSaleStartDate;
/*
* The UNIX timestamp (in seconds) defining when the TGE will end
*/
uint public preSaleEndDate;
/*
* The number of token units a contributor receives per ETHER during contribution phase
*/
uint public saleConversionRate;
/*
* The UNIX timestamp (in seconds) defining when the TGE will start
*/
uint public saleStartDate;
/*
* The UNIX timestamp (in seconds) defining when the TGE would end if cap will not be reached
*/
uint public saleEndDate;
/*
* The bonus a sms verified user will receive for a contribution during pre-contribution phase in base points
*/
uint public smsVerifiedBonusBps;
/*
* The bonus a kyc verified user will receive for a contribution during pre-contribution phase in base points
*/
uint public kycVerifiedBonusBps;
/**
* Total percent of tokens minted to the team at the end of the sale as base points
* 1BP -> 0.01%
*/
uint public maxTeamBonusBps;
/**
* Only the foundation board is able to finalize the TGE.
* Two of four members have to confirm the finalization. Therefore a multisig contract is used.
*/
address public foundationBoard;
/**
* Only the KYC confirmation account is allowed to confirm a successfull KYC verification
*/
address public kycConfirmer;
/**
* Once the contribution has ended an auditor will verify whether all regulations have been fullfilled
*/
address public auditor;
/**
* The tokens for the insitutional investors will be allocated to this wallet
*/
address public instContWallet;
/**
* This flag ist set by auditor before finalizing the TGE to indicate whether all regualtions have been fulfilled
*/
bool public regulationsFulfilled;
/**
* The auditor can comment the confirmation (e.g. in case of deviations)
*/
bytes32 public auditorComment;
/**
* The total number of institutional and public tokens sold during pre- and contribution phase
*/
uint256 public tokensSold = 0;
/*
* The number of tokens pre allocated to insitutional contributors
*/
uint public instContAllocatedTokens;
/**
* The amount of wei totally raised by the public TGE
*/
uint256 public weiRaised = 0;
/*
* The amount of wei raised during the preContribution phase
*/
uint256 public preSaleWeiRaised = 0;
/*
* How much wei we have given back to contributors.
*/
uint256 public weiRefunded = 0;
/*
* The number of tokens allocated to the team when the TGE was finalized.
* The calculation is based on the predefined maxTeamBonusBps
*/
uint public teamBonusAllocatedTokens;
/**
* The number of contributors which have contributed to the TGE
*/
uint public numberOfContributors = 0;
/**
* dictionary that maps addresses to contributors which have sucessfully been verified by the external KYC process
*/
mapping (address => bool) public kycRegisteredContributors;
struct TeamBonus {
address toAddress;
uint64 tokenBps;
uint64 cliffDate;
uint64 vestingDate;
}
/*
* Defines the percentage (base points) distribution of the team-allocated bonus rewards among members which will be vested ..
* 1 Bp -> 0.01%
*/
TeamBonus[] public teamBonuses;
/**
* @dev Check whether the TGE is currently in the state provided
*/
function LegalTGE (address _foundationBoard, address _multisigWallet, address _instContWallet, uint256 _instContAllocatedTokens, uint256 _tokenCap, uint256 _smsVerifiedBonusBps, uint256 _kycVerifiedBonusBps, uint256 _maxTeamBonusBps, address _auditor, address _kycConfirmer, ProofOfSMS _proofOfSMS, RefundVault _vault) {
// --------------------------------------------------------------------------------
// -- Validate all variables which are not passed to the constructor first
// --------------------------------------------------------------------------------
// the address of the account used for auditing
require(_foundationBoard != 0x0);
// the address of the multisig must not be 'undefined'
require(_multisigWallet != 0x0);
// the address of the wallet for constitutional contributors must not be 'undefined'
require(_instContWallet != 0x0);
// the address of the account used for auditing
require(_auditor != 0x0);
// the address of the cap for this TGE must not be 'undefined'
require(_tokenCap > 0);
// pre-contribution and contribution phases must not overlap
// require(_preSaleStartDate <= _preSaleEndDate);
multisigWallet = _multisigWallet;
instContWallet = _instContWallet;
instContAllocatedTokens = _instContAllocatedTokens;
tokenCap = _tokenCap;
smsVerifiedBonusBps = _smsVerifiedBonusBps;
kycVerifiedBonusBps = _kycVerifiedBonusBps;
maxTeamBonusBps = _maxTeamBonusBps;
auditor = _auditor;
foundationBoard = _foundationBoard;
kycConfirmer = _kycConfirmer;
proofOfSMS = _proofOfSMS;
// --------------------------------------------------------------------------------
// -- Initialize all variables which are not passed to the constructor first
// --------------------------------------------------------------------------------
state = States.PreparePreContribution;
vault = _vault;
}
/** =============================================================================================================================
* All logic related to the TGE contribution is currently placed below.
* ============================================================================================================================= */
function setMaxWeiForVerificationLevels(uint _minWeiPerContributor, uint _maxWeiUnverified, uint _maxWeiSMSVerified) public onlyOwner inState(States.PreparePreContribution) {
require(_minWeiPerContributor >= 0);
require(_maxWeiUnverified > _minWeiPerContributor);
require(_maxWeiSMSVerified > _minWeiPerContributor);
// the minimum number of wei an unverified user can contribute
minWeiPerContributor = _minWeiPerContributor;
// the maximum number of wei an unverified user can contribute
maxWeiUnverified = _maxWeiUnverified;
// the maximum number of wei an SMS verified user can contribute
maxWeiSMSVerified = _maxWeiSMSVerified;
}
function setLegalToken(LegalToken _legalToken) public onlyOwner inState(States.PreparePreContribution) {
token = _legalToken;
if ( instContAllocatedTokens > 0 ) {
// mint the pre allocated tokens for the institutional investors
token.mint(instContWallet, instContAllocatedTokens);
tokensSold += instContAllocatedTokens;
}
LogTokenAssigned(msg.sender, _legalToken);
}
function validatePreContribution(uint _preSaleConversionRate, uint _preSaleStartDate, uint _preSaleEndDate) constant internal {
// the pre-contribution conversion rate must not be 'undefined'
require(_preSaleConversionRate >= 0);
// the pre-contribution start date must not be in the past
require(_preSaleStartDate >= now);
// the pre-contribution start date must not be in the past
require(_preSaleEndDate >= _preSaleStartDate);
}
function validateContribution(uint _saleConversionRate, uint _saleStartDate, uint _saleEndDate) constant internal {
// the contribution conversion rate must not be 'undefined'
require(_saleConversionRate >= 0);
// the contribution start date must not be in the past
require(_saleStartDate >= now);
// the contribution end date must not be before start date
require(_saleEndDate >= _saleStartDate);
}
function isNowBefore(uint _date) constant internal returns (bool) {
return ( now < _date );
}
function evalTransitionState() public returns (States) {
// once the TGE is in state finalized or refunding, there is now way to transit to another state!
if ( hasState(States.Finalized))
return States.Finalized;
if ( hasState(States.Refunding))
return States.Refunding;
if ( isCapReached())
return States.Auditing;
if ( isNowBefore(preSaleStartDate))
return States.PreparePreContribution;
if ( isNowBefore(preSaleEndDate))
return States.PreContribution;
if ( isNowBefore(saleStartDate))
return States.PrepareContribution;
if ( isNowBefore(saleEndDate))
return States.Contribution;
return States.Auditing;
}
modifier stateTransitions() {
States evaluatedState = evalTransitionState();
setState(evaluatedState);
_;
}
function hasState(States _state) constant private returns (bool) {
return (state == _state);
}
function setState(States _state) private {
if ( _state != state ) {
state = _state;
LogStateChange(state);
}
}
modifier inState(States _state) {
require(hasState(_state));
_;
}
function updateState() public stateTransitions {
}
/**
* @dev Checks whether contract is in a state in which contributions will be accepted
*/
modifier inPreOrContributionState() {
require(hasState(States.PreContribution) || (hasState(States.Contribution)));
_;
}
modifier inPrePrepareOrPreContributionState() {
require(hasState(States.PreparePreContribution) || (hasState(States.PreContribution)));
_;
}
modifier inPrepareState() {
// we can relay on state since modifer since already evaluated by stateTransitions modifier
require(hasState(States.PreparePreContribution) || (hasState(States.PrepareContribution)));
_;
}
/**
* This modifier makes sure that not more tokens as specified can be allocated
*/
modifier teamBonusLimit(uint64 _tokenBps) {
uint teamBonusBps = 0;
for ( uint i = 0; i < teamBonuses.length; i++ ) {
teamBonusBps = teamBonusBps.add(teamBonuses[i].tokenBps);
}
require(maxTeamBonusBps >= teamBonusBps);
_;
}
/**
* Allocates the team bonus with a specific vesting rule
*/
function allocateTeamBonus(address _toAddress, uint64 _tokenBps, uint64 _cliffDate, uint64 _vestingDate) public onlyOwner teamBonusLimit(_tokenBps) inState(States.PreparePreContribution) {
teamBonuses.push(TeamBonus(_toAddress, _tokenBps, _cliffDate, _vestingDate));
}
/**
* This method can optional be called by the owner to adjust the conversionRate, startDate and endDate before contribution phase starts.
* Pre-conditions:
* - Caller is owner (deployer)
* - TGE is in state PreContribution
* Post-conditions:
*/
function preparePreContribution(uint _preSaleConversionRate, uint _preSaleStartDate, uint _preSaleEndDate) public onlyOwner inState(States.PreparePreContribution) {
validatePreContribution(_preSaleConversionRate, _preSaleStartDate, _preSaleEndDate);
preSaleConversionRate = _preSaleConversionRate;
preSaleStartDate = _preSaleStartDate;
preSaleEndDate = _preSaleEndDate;
LogPreparePreContribution(msg.sender, preSaleConversionRate, preSaleStartDate, preSaleEndDate);
}
/**
* This method can optional be called by the owner to adjust the conversionRate, startDate and endDate before pre contribution phase starts.
* Pre-conditions:
* - Caller is owner (deployer)
* - Crowdsale is in state PreparePreContribution
* Post-conditions:
*/
function prepareContribution(uint _saleConversionRate, uint _saleStartDate, uint _saleEndDate) public onlyOwner inPrepareState {
validateContribution(_saleConversionRate, _saleStartDate, _saleEndDate);
saleConversionRate = _saleConversionRate;
saleStartDate = _saleStartDate;
saleEndDate = _saleEndDate;
LogPrepareContribution(msg.sender, saleConversionRate, saleStartDate, saleEndDate);
}
// fallback function can be used to buy tokens
function () payable public {
contribute();
}
function getWeiPerContributor(address _contributor) public constant returns (uint) {
return weiPerContributor[_contributor];
}
function contribute() whenNotPaused stateTransitions inPreOrContributionState public payable {
require(msg.sender != 0x0);
require(msg.value >= minWeiPerContributor);
VerificationLevel verificationLevel = getVerificationLevel();
// we only allow verified users to participate during pre-contribution phase
require(hasState(States.Contribution) || verificationLevel > VerificationLevel.None);
// we need to keep track of all contributions per user to limit total contributions
weiPerContributor[msg.sender] = weiPerContributor[msg.sender].add(msg.value);
// the total amount of ETH a KYC verified user can contribute is unlimited, so we do not need to check
if ( verificationLevel == VerificationLevel.SMSVerified ) {
// the total amount of ETH a non-KYC user can contribute is limited to maxWeiPerContributor
require(weiPerContributor[msg.sender] <= maxWeiSMSVerified);
}
if ( verificationLevel == VerificationLevel.None ) {
// the total amount of ETH a non-verified user can contribute is limited to maxWeiUnverified
require(weiPerContributor[msg.sender] <= maxWeiUnverified);
}
if (hasState(States.PreContribution)) {
preSaleWeiRaised = preSaleWeiRaised.add(msg.value);
}
weiRaised = weiRaised.add(msg.value);
// calculate the token amount to be created
uint256 tokenAmount = calculateTokenAmount(msg.value, verificationLevel);
tokensSold = tokensSold.add(tokenAmount);
if ( token.balanceOf(msg.sender) == 0 ) {
numberOfContributors++;
}
if ( isCapReached()) {
updateState();
}
token.mint(msg.sender, tokenAmount);
forwardFunds();
LogContribution(msg.sender, msg.value, tokenAmount, verificationLevel, state);
}
function calculateTokenAmount(uint256 _weiAmount, VerificationLevel _verificationLevel) public constant returns (uint256) {
uint256 conversionRate = saleConversionRate;
if ( state == States.PreContribution) {
conversionRate = preSaleConversionRate;
}
uint256 tokenAmount = _weiAmount.mul(conversionRate);
// an anonymous user (Level-0) gets no bonus
uint256 bonusTokenAmount = 0;
if ( _verificationLevel == VerificationLevel.SMSVerified ) {
// a SMS verified user (Level-1) gets a bonus
bonusTokenAmount = tokenAmount.mul(smsVerifiedBonusBps).div(10000);
} else if ( _verificationLevel == VerificationLevel.KYCVerified ) {
// a KYC verified user (Level-2) gets the highest bonus
bonusTokenAmount = tokenAmount.mul(kycVerifiedBonusBps).div(10000);
}
return tokenAmount.add(bonusTokenAmount);
}
function getVerificationLevel() constant public returns (VerificationLevel) {
if (kycRegisteredContributors[msg.sender]) {
return VerificationLevel.KYCVerified;
} else if (proofOfSMS.certified(msg.sender)) {
return VerificationLevel.SMSVerified;
}
return VerificationLevel.None;
}
modifier onlyKycConfirmer() {
require(msg.sender == kycConfirmer);
_;
}
function confirmKYC(address addressId) onlyKycConfirmer inPrePrepareOrPreContributionState() public returns (bool) {
LogKYCConfirmation(msg.sender);
return kycRegisteredContributors[addressId] = true;
}
// =============================================================================================================================
// All functions related to the TGE cap come here
// =============================================================================================================================
function isCapReached() constant internal returns (bool) {
if (tokensSold >= tokenCap) {
return true;
}
return false;
}
// =============================================================================================================================
// Everything which is related tof the auditing process comes here.
// =============================================================================================================================
/**
* @dev Throws if called by any account other than the foundation board
*/
modifier onlyFoundationBoard() {
require(msg.sender == foundationBoard);
_;
}
/**
* @dev Throws if called by any account other than the auditor.
*/
modifier onlyAuditor() {
require(msg.sender == auditor);
_;
}
/**
* @dev Throws if auditor has not yet confirmed TGE
*/
modifier auditorConfirmed() {
require(auditorComment != 0x0);
_;
}
/*
* After the TGE reaches state 'auditing', the auditor will verify the legal and regulatory obligations
*/
function confirmLawfulness(bool _regulationsFulfilled, bytes32 _auditorComment) public onlyAuditor stateTransitions inState ( States.Auditing ) {
regulationsFulfilled = _regulationsFulfilled;
auditorComment = _auditorComment;
LogRegularityConfirmation(msg.sender, _regulationsFulfilled, _auditorComment);
}
/**
* After the auditor has verified the the legal and regulatory obligations of the TGE, the foundation board is able to finalize the TGE.
* The finalization consists of the following steps:
* - Transit state
* - close the RefundVault and transfer funds to the foundation wallet
* - release tokens (make transferable)
* - enable scheduler for the inflation compensation
* - Min the defined amount of token per team and make them vestable
*/
function finalize() public onlyFoundationBoard stateTransitions inState ( States.Auditing ) auditorConfirmed {
setState(States.Finalized);
// Make token transferable otherwise the transfer call used when granting vesting to teams will be rejected.
token.releaseTokenTransfer();
// mint bonusus for
allocateTeamBonusTokens();
// the funds can now be transfered to the multisig wallet of the foundation
vault.close();
// disable minting for the TGE (though tokens will still be minted to compensate an inflation period)
token.finishMinting();
// now we can safely enable the shceduler for inflation compensation
token.enableScheduler();
// pass ownership from contract to SmartOne
token.transferOwnership(owner);
LogFinalized(msg.sender);
}
function enableRefunds() public onlyFoundationBoard stateTransitions inState ( States.Auditing ) auditorConfirmed {
setState(States.Refunding);
LogRefundsEnabled(msg.sender);
// no need to trigger event here since this allready done in RefundVault (see event RefundsEnabled)
vault.enableRefunds();
}
// =============================================================================================================================
// Postallocation Reward Tokens
// =============================================================================================================================
/**
* Called once by TGE finalize() if the sale was success.
*/
function allocateTeamBonusTokens() private {
for (uint i = 0; i < teamBonuses.length; i++) {
// How many % of tokens the team member receive as rewards
uint _teamBonusTokens = (tokensSold.mul(teamBonuses[i].tokenBps)).div(10000);
// mint new tokens for contributors
token.mint(this, _teamBonusTokens);
token.grantVestedTokens(teamBonuses[i].toAddress, _teamBonusTokens, uint64(now), teamBonuses[i].cliffDate, teamBonuses[i].vestingDate, false, false);
teamBonusAllocatedTokens = teamBonusAllocatedTokens.add(_teamBonusTokens);
}
}
// =============================================================================================================================
// All functions related to Refunding can be found here.
// Uses some slightly modifed logic from https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/crowdsale/RefundableTGE.sol
// =============================================================================================================================
/** We're overriding the fund forwarding from TGE.
* In addition to sending the funds, we want to call
* the RefundVault deposit function
*/
function forwardFunds() internal {
vault.deposit.value(msg.value)(msg.sender);
}
/**
* If TGE was not successfull refunding process will be released by SmartOne
*/
function claimRefund() public stateTransitions inState ( States.Refunding ) {
// workaround since vault refund does not return refund value
weiRefunded = weiRefunded.add(vault.deposited(msg.sender));
vault.refund(msg.sender);
}
}
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public constant returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public constant returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
// 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 constant returns (uint256 balance) {
return balances[_owner];
}
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) 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));
uint256 _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
// require (_value <= _allowance);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = _allowance.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 constant returns (uint256 remaining) {
return allowed[_owner][_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
*/
function increaseApproval (address _spender, uint _addedValue)
returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval (address _spender, uint _subtractedValue)
returns (bool success) {
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 MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
Transfer(0x0, _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner public returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
}
contract LimitedTransferToken is ERC20 {
/**
* @dev Checks whether it can transfer or otherwise throws.
*/
modifier canTransfer(address _sender, uint256 _value) {
require(_value <= transferableTokens(_sender, uint64(now)));
_;
}
/**
* @dev Checks modifier and allows transfer if tokens are not locked.
* @param _to The address that will receive the tokens.
* @param _value The amount of tokens to be transferred.
*/
function transfer(address _to, uint256 _value) canTransfer(msg.sender, _value) public returns (bool) {
return super.transfer(_to, _value);
}
/**
* @dev Checks modifier and allows transfer if tokens are not locked.
* @param _from The address that will send the tokens.
* @param _to The address that will receive the tokens.
* @param _value The amount of tokens to be transferred.
*/
function transferFrom(address _from, address _to, uint256 _value) canTransfer(_from, _value) public returns (bool) {
return super.transferFrom(_from, _to, _value);
}
/**
* @dev Default transferable tokens function returns all tokens for a holder (no limit).
* @dev Overwriting transferableTokens(address holder, uint64 time) is the way to provide the
* specific logic for limiting token transferability for a holder over time.
*/
function transferableTokens(address holder, uint64 time) public constant returns (uint256) {
return balanceOf(holder);
}
}
contract VestedToken is StandardToken, LimitedTransferToken, Ownable {
uint256 MAX_GRANTS_PER_ADDRESS = 20;
struct TokenGrant {
address granter; // 20 bytes
uint256 value; // 32 bytes
uint64 cliff;
uint64 vesting;
uint64 start; // 3 * 8 = 24 bytes
bool revokable;
bool burnsOnRevoke; // 2 * 1 = 2 bits? or 2 bytes?
} // total 78 bytes = 3 sstore per operation (32 per sstore)
mapping (address => TokenGrant[]) public grants;
event NewTokenGrant(address indexed from, address indexed to, uint256 value, uint256 grantId);
/**
* @dev Grant tokens to a specified address
* @param _to address The address which the tokens will be granted to.
* @param _value uint256 The amount of tokens to be granted.
* @param _start uint64 Time of the beginning of the grant.
* @param _cliff uint64 Time of the cliff period.
* @param _vesting uint64 The vesting period.
*/
function grantVestedTokens(
address _to,
uint256 _value,
uint64 _start,
uint64 _cliff,
uint64 _vesting,
bool _revokable,
bool _burnsOnRevoke
) onlyOwner public {
// Check for date inconsistencies that may cause unexpected behavior
require(_cliff >= _start && _vesting >= _cliff);
require(tokenGrantsCount(_to) < MAX_GRANTS_PER_ADDRESS); // To prevent a user being spammed and have his balance locked (out of gas attack when calculating vesting).
uint256 count = grants[_to].push(
TokenGrant(
_revokable ? msg.sender : 0, // avoid storing an extra 20 bytes when it is non-revokable
_value,
_cliff,
_vesting,
_start,
_revokable,
_burnsOnRevoke
)
);
transfer(_to, _value);
NewTokenGrant(msg.sender, _to, _value, count - 1);
}
/**
* @dev Revoke the grant of tokens of a specifed address.
* @param _holder The address which will have its tokens revoked.
* @param _grantId The id of the token grant.
*/
function revokeTokenGrant(address _holder, uint256 _grantId) public {
TokenGrant storage grant = grants[_holder][_grantId];
require(grant.revokable);
require(grant.granter == msg.sender); // Only granter can revoke it
address receiver = grant.burnsOnRevoke ? 0xdead : msg.sender;
uint256 nonVested = nonVestedTokens(grant, uint64(now));
// remove grant from array
delete grants[_holder][_grantId];
grants[_holder][_grantId] = grants[_holder][grants[_holder].length.sub(1)];
grants[_holder].length -= 1;
balances[receiver] = balances[receiver].add(nonVested);
balances[_holder] = balances[_holder].sub(nonVested);
Transfer(_holder, receiver, nonVested);
}
/**
* @dev Calculate the total amount of transferable tokens of a holder at a given time
* @param holder address The address of the holder
* @param time uint64 The specific time.
* @return An uint256 representing a holder's total amount of transferable tokens.
*/
function transferableTokens(address holder, uint64 time) public constant returns (uint256) {
uint256 grantIndex = tokenGrantsCount(holder);
if (grantIndex == 0)
return super.transferableTokens(holder, time); // shortcut for holder without grants
// Iterate through all the grants the holder has, and add all non-vested tokens
uint256 nonVested = 0;
for (uint256 i = 0; i < grantIndex; i++) {
nonVested = SafeMath.add(nonVested, nonVestedTokens(grants[holder][i], time));
}
// Balance - totalNonVested is the amount of tokens a holder can transfer at any given time
uint256 vestedTransferable = SafeMath.sub(balanceOf(holder), nonVested);
// Return the minimum of how many vested can transfer and other value
// in case there are other limiting transferability factors (default is balanceOf)
return Math.min256(vestedTransferable, super.transferableTokens(holder, time));
}
/**
* @dev Check the amount of grants that an address has.
* @param _holder The holder of the grants.
* @return A uint256 representing the total amount of grants.
*/
function tokenGrantsCount(address _holder) public constant returns (uint256 index) {
return grants[_holder].length;
}
/**
* @dev Calculate amount of vested tokens at a specific time
* @param tokens uint256 The amount of tokens granted
* @param time uint64 The time to be checked
* @param start uint64 The time representing the beginning of the grant
* @param cliff uint64 The cliff period, the period before nothing can be paid out
* @param vesting uint64 The vesting period
* @return An uint256 representing the amount of vested tokens of a specific grant
* transferableTokens
* | _/-------- vestedTokens rect
* | _/
* | _/
* | _/
* | _/
* | /
* | .|
* | . |
* | . |
* | . |
* | . |
* | . |
* +===+===========+---------+----------> time
* Start Cliff Vesting
*/
function calculateVestedTokens(
uint256 tokens,
uint256 time,
uint256 start,
uint256 cliff,
uint256 vesting) public constant returns (uint256)
{
// Shortcuts for before cliff and after vesting cases.
if (time < cliff) return 0;
if (time >= vesting) return tokens;
// Interpolate all vested tokens.
// As before cliff the shortcut returns 0, we can use just calculate a value
// in the vesting rect (as shown in above's figure)
// vestedTokens = (tokens * (time - start)) / (vesting - start)
uint256 vestedTokens = SafeMath.div(
SafeMath.mul(
tokens,
SafeMath.sub(time, start)
),
SafeMath.sub(vesting, start)
);
return vestedTokens;
}
/**
* @dev Get all information about a specific grant.
* @param _holder The address which will have its tokens revoked.
* @param _grantId The id of the token grant.
* @return Returns all the values that represent a TokenGrant(address, value, start, cliff,
* revokability, burnsOnRevoke, and vesting) plus the vested value at the current time.
*/
function tokenGrant(address _holder, uint256 _grantId) public constant returns (address granter, uint256 value, uint256 vested, uint64 start, uint64 cliff, uint64 vesting, bool revokable, bool burnsOnRevoke) {
TokenGrant storage grant = grants[_holder][_grantId];
granter = grant.granter;
value = grant.value;
start = grant.start;
cliff = grant.cliff;
vesting = grant.vesting;
revokable = grant.revokable;
burnsOnRevoke = grant.burnsOnRevoke;
vested = vestedTokens(grant, uint64(now));
}
/**
* @dev Get the amount of vested tokens at a specific time.
* @param grant TokenGrant The grant to be checked.
* @param time The time to be checked
* @return An uint256 representing the amount of vested tokens of a specific grant at a specific time.
*/
function vestedTokens(TokenGrant grant, uint64 time) private constant returns (uint256) {
return calculateVestedTokens(
grant.value,
uint256(time),
uint256(grant.start),
uint256(grant.cliff),
uint256(grant.vesting)
);
}
/**
* @dev Calculate the amount of non vested tokens at a specific time.
* @param grant TokenGrant The grant to be checked.
* @param time uint64 The time to be checked
* @return An uint256 representing the amount of non vested tokens of a specific grant on the
* passed time frame.
*/
function nonVestedTokens(TokenGrant grant, uint64 time) private constant returns (uint256) {
return grant.value.sub(vestedTokens(grant, time));
}
/**
* @dev Calculate the date when the holder can transfer all its tokens
* @param holder address The address of the holder
* @return An uint256 representing the date of the last transferable tokens.
*/
function lastTokenIsTransferableDate(address holder) public constant returns (uint64 date) {
date = uint64(now);
uint256 grantIndex = grants[holder].length;
for (uint256 i = 0; i < grantIndex; i++) {
date = Math.max64(grants[holder][i].vesting, date);
}
}
}
contract Certifier {
event Confirmed(address indexed who);
event Revoked(address indexed who);
function certified(address _who) constant returns (bool);
// function get(address _who, string _field) constant returns (bytes32) {}
// function getAddress(address _who, string _field) constant returns (address) {}
// function getUint(address _who, string _field) constant returns (uint) {}
}
contract SimpleCertifier is Owned, Certifier {
modifier only_delegate {
assert(msg.sender == delegate);
_;
}
modifier only_certified(address _who) {
if (!certs[_who].active)
return;
_;
}
struct Certification {
bool active;
mapping (string => bytes32) meta;
}
function certify(address _who) only_delegate {
certs[_who].active = true;
Confirmed(_who);
}
function revoke(address _who) only_delegate only_certified(_who) {
certs[_who].active = false;
Revoked(_who);
}
function certified(address _who) constant returns (bool) { return certs[_who].active; }
// function get(address _who, string _field) constant returns (bytes32) { return certs[_who].meta[_field]; }
// function getAddress(address _who, string _field) constant returns (address) { return address(certs[_who].meta[_field]); }
// function getUint(address _who, string _field) constant returns (uint) { return uint(certs[_who].meta[_field]); }
function setDelegate(address _new) only_owner { delegate = _new; }
mapping (address => Certification) certs;
// So that the server posting puzzles doesn't have access to the ETH.
address public delegate = msg.sender;
}
contract ProofOfSMS is SimpleCertifier {
modifier when_fee_paid {
if (msg.value < fee) {
RequiredFeeNotMet(fee, msg.value);
return;
}
_;
}
event RequiredFeeNotMet(uint required, uint provided);
event Requested(address indexed who);
event Puzzled(address who, bytes32 puzzle);
event LogAddress(address test);
function request() payable when_fee_paid {
if (certs[msg.sender].active) {
return;
}
Requested(msg.sender);
}
function puzzle (address _who, bytes32 _puzzle) only_delegate {
puzzles[_who] = _puzzle;
Puzzled(_who, _puzzle);
}
function confirm(bytes32 _code) returns (bool) {
LogAddress(msg.sender);
if (puzzles[msg.sender] != sha3(_code))
return;
delete puzzles[msg.sender];
certs[msg.sender].active = true;
Confirmed(msg.sender);
return true;
}
function setFee(uint _new) only_owner {
fee = _new;
}
function drain() only_owner {
require(msg.sender.send(this.balance));
}
function certified(address _who) constant returns (bool) {
return certs[_who].active;
}
mapping (address => bytes32) puzzles;
uint public fee = 30 finney;
}
contract LegalToken is LegalLazyScheduler, MintableToken, VestedToken {
/**
* The name of the token
*/
bytes32 public name;
/**
* The symbol used for exchange
*/
bytes32 public symbol;
/**
* Use to convert to number of tokens.
*/
uint public decimals = 18;
/**
* The yearly expected inflation rate in base points.
*/
uint32 public inflationCompBPS;
/**
* The tokens are locked until the end of the TGE.
* The contract can release the tokens if TGE successful. If false we are in transfer lock up period.
*/
bool public released = false;
/**
* Annually new minted tokens will be transferred to this wallet.
* Publications will be rewarded with funds (incentives).
*/
address public rewardWallet;
/**
* Name and symbol were updated.
*/
event UpdatedTokenInformation(bytes32 newName, bytes32 newSymbol);
/**
* @dev Constructor that gives msg.sender all of existing tokens.
*/
function LegalToken(address _rewardWallet, uint32 _inflationCompBPS, uint32 _inflationCompInterval) onlyOwner public {
setTokenInformation("Legal Token", "LGL");
totalSupply = 0;
rewardWallet = _rewardWallet;
inflationCompBPS = _inflationCompBPS;
registerIntervalCall(_inflationCompInterval, mintInflationPeriod);
}
/**
* This function allows the token owner to rename the token after the operations
* have been completed and then point the audience to use the token contract.
*/
function setTokenInformation(bytes32 _name, bytes32 _symbol) onlyOwner public {
name = _name;
symbol = _symbol;
UpdatedTokenInformation(name, symbol);
}
/**
* Mint new tokens for the predefined inflation period and assign them to the reward wallet.
*/
function mintInflationPeriod() private {
uint256 tokensToMint = totalSupply.mul(inflationCompBPS).div(10000);
totalSupply = totalSupply.add(tokensToMint);
balances[rewardWallet] = balances[rewardWallet].add(tokensToMint);
Mint(rewardWallet, tokensToMint);
Transfer(0x0, rewardWallet, tokensToMint);
}
function setRewardWallet(address _rewardWallet) public onlyOwner {
rewardWallet = _rewardWallet;
}
/**
* Limit token transfer until the TGE is over.
*/
modifier tokenReleased(address _sender) {
require(released);
_;
}
/**
* This will make the tokens transferable
*/
function releaseTokenTransfer() public onlyOwner {
released = true;
}
// error: canTransfer(msg.sender, _value)
function transfer(address _to, uint _value) public tokenReleased(msg.sender) intervalTrigger returns (bool success) {
// Calls StandardToken.transfer()
// error: super.transfer(_to, _value);
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint _value) public tokenReleased(_from) intervalTrigger returns (bool success) {
// Calls StandardToken.transferForm()
return super.transferFrom(_from, _to, _value);
}
function approve(address _spender, uint256 _value) public tokenReleased(msg.sender) intervalTrigger returns (bool) {
// calls StandardToken.approve(..)
return super.approve(_spender, _value);
}
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
// calls StandardToken.allowance(..)
return super.allowance(_owner, _spender);
}
function increaseApproval (address _spender, uint _addedValue) public tokenReleased(msg.sender) intervalTrigger returns (bool success) {
// calls StandardToken.increaseApproval(..)
return super.increaseApproval(_spender, _addedValue);
}
function decreaseApproval (address _spender, uint _subtractedValue) public tokenReleased(msg.sender) intervalTrigger returns (bool success) {
// calls StandardToken.decreaseApproval(..)
return super.decreaseApproval(_spender, _subtractedValue);
}
}
|
fallback function can be used to buy tokens
|
function () payable public {
contribute();
}
| 6,387,518 |
pragma solidity >=0.4 <0.6.0;
import "./Managed.sol";
import "./IRegistry.sol";
contract Registry is IRegistry, Managed {
// the place where all components in the system are going to be stored
address[] private _registry;
mapping(address => uint256) private _addressToIndex;
mapping(address => uint256) private _addressToReward;
mapping(address => ProducerStruct) private _producerToData;
mapping(address => RecyclerStruct) private _recyclerToData;
mapping(address => RepairerStruct) private _repairerToData;
constructor(address _manager) Managed(_manager) public {}
function addComponent(address _componentAddress, uint256 _reward) external onlyManager {
uint256 _index = _registry.push(_componentAddress) - 1;
_addressToIndex[_componentAddress] = _index;
_addressToReward[_componentAddress] = _reward;
emit ComponentRegistred(_index, _componentAddress);
}
function componentDestroyed(address _componentAddress)
external
onlyManager
returns (uint256)
{
uint256 _index = _addressToIndex[_componentAddress];
emit ComponentDestroyed(_index, _componentAddress);
return _addressToReward[_componentAddress];
}
function componentRecycled(address _componentAddress)
external
onlyManager
returns (uint256)
{
uint256 _index = _addressToIndex[_componentAddress];
emit ComponentRecycled(_index, _componentAddress);
return _addressToReward[_componentAddress];
}
function registerProducer(
address _producerAddress,
string calldata _name,
string calldata _information
)
external
onlyManager
returns (bool)
{
_producerToData[_producerAddress] = ProducerStruct({
name: _name,
information: _information,
isRegistred: true,
isConfirmed: false
});
emit ProducerRegistred(_producerAddress);
return true;
}
function confirmProducer(address _producerAddress)
external
onlyManager
returns (bool)
{
ProducerStruct storage _producer = _producerToData[_producerAddress];
if (_producer.isRegistred) {
_producer.isConfirmed = true;
emit ProducerConfirmed(_producerAddress);
return true;
}
return false;
}
function registerRecycler(
address _recyclerAddress,
string calldata _name,
string calldata _information
)
external
onlyManager
returns (bool)
{
_recyclerToData[_recyclerAddress] = RecyclerStruct({
name: _name,
information: _information,
valueRecycled: 0,
isRegistred: true,
isConfirmed: false
});
emit RecyclerRegistred(_recyclerAddress);
return true;
}
function confirmRecycler(
address _recyclerAddress
)
external
returns (bool)
{
RecyclerStruct storage _recycler = _recyclerToData[_recyclerAddress];
if (_recycler.isRegistred) {
_recycler.isConfirmed = true;
emit RecyclerConfirmed(_recyclerAddress);
return true;
}
return false;
}
function registerRepairer(
address _repairerAddress,
string calldata _name,
string calldata _information
)
external
onlyManager
returns (bool)
{
_repairerToData[_repairerAddress] = RepairerStruct({
name: _name,
information: _information,
isRegistred: true,
isConfirmed: false
});
emit RepairerRegistred(_repairerAddress);
return true;
}
function confirmRepairer(
address _repairerAddress
)
external
returns (bool)
{
RepairerStruct storage _repairer = _repairerToData[_repairerAddress];
if (_repairer.isRegistred) {
_repairer.isConfirmed = true;
emit RepairerConfirmed(_repairerAddress);
return true;
}
return false;
}
function isProducer(address _producerAddress) external view returns (bool) {
// returns true if this is a certified producer
return _producerToData[_producerAddress].isConfirmed;
}
function isRecycler(address _recyclerAddress) external view returns (bool) {
// returns true if this is a certified recycler
return _recyclerToData[_recyclerAddress].isConfirmed;
}
function isRepairer(address _repairerAddress) external view returns (bool) {
// returns true if this is a certified repairer
return _repairerToData[_repairerAddress].isConfirmed;
}
function getRegistrySize() external view returns(uint256) {
return _registry.length;
}
function getRegistredComponentAtIndex(
uint256 _index
)
external
view
returns(address)
{
return _registry[_index];
}
function getRegistredComponents()
external
view
returns(address[] memory)
{
return _registry;
}
function getProducerInfo(
address _producerAddress
)
external
view
returns
(
string memory,
string memory,
bool,
bool
)
{
ProducerStruct memory _producer = _producerToData[_producerAddress];
return (
_producer.name,
_producer.information,
_producer.isRegistred,
_producer.isConfirmed
);
}
function getRecyclerInfo(
address _recyclerAddress
)
external
view
returns
(
string memory,
string memory,
uint256,
bool,
bool
)
{
RecyclerStruct memory _recycler = _recyclerToData[_recyclerAddress];
return (
_recycler.name,
_recycler.information,
_recycler.valueRecycled,
_recycler.isRegistred,
_recycler.isConfirmed
);
}
function getRepairerInfo(
address _repairerAddress
)
external
view
returns
(
string memory,
string memory,
bool,
bool
)
{
RepairerStruct memory _repairer = _repairerToData[_repairerAddress];
return (
_repairer.name,
_repairer.information,
_repairer.isRegistred,
_repairer.isConfirmed
);
}
function getComponentReward(
address _componentAddress
)
external
view
returns(uint256)
{
return _addressToReward[_componentAddress];
}
}
|
returns true if this is a certified recycler
|
function isRecycler(address _recyclerAddress) external view returns (bool) {
return _recyclerToData[_recyclerAddress].isConfirmed;
}
| 1,070,433 |
pragma solidity 0.6.12;
import "./ERC20Interface.sol";
import "./IPToken.sol";
import "../libs/Exponential.sol";
import "../libs/ErrorReporter.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
contract PERC20Optimism is IPToken, Exponential, TokenErrorReporter, OwnableUpgradeable {
using SafeMath for uint256;
address public underlying;
function initialize(address underlying_, string memory name_, string memory symbol_, uint8 decimals_, uint256 initialExchangeRateMantissa_) public initializer {
OwnableUpgradeable.__Ownable_init();
initialExchangeRateMantissa = initialExchangeRateMantissa_;
accrualBlockNumber = getBlockNumber();
borrowIndex = mantissaOne;
name = name_;
symbol = symbol_;
decimals = decimals_;
underlying = underlying_;
_notEntered = true;
}
/**
* @notice Transfer `tokens` tokens from `src` to `dst` by `spender`
* @dev Called by both `transfer` and `transferFrom` internally
* @param spender The address of the account performing the transfer
* @param src The address of the source account
* @param dst The address of the destination account
* @param tokens The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferTokens(address spender, address src, address dst, uint tokens) internal returns (uint) {
uint allowed = comptroller.transferAllowed(address(this), src, dst, tokens);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.TRANSFER_COMPTROLLER_REJECTION, allowed);
}
if (src == dst) {
return fail(Error.BAD_INPUT, FailureInfo.TRANSFER_NOT_ALLOWED);
}
uint startingAllowance = 0;
if (spender == src) {
startingAllowance = uint(- 1);
} else {
startingAllowance = transferAllowances[src][spender];
}
uint allowanceNew = startingAllowance.sub(tokens);
uint srcTokensNew = accountTokens[src].sub(tokens);
uint dstTokensNew = accountTokens[dst].add(tokens);
accountTokens[src] = srcTokensNew;
accountTokens[dst] = dstTokensNew;
if (startingAllowance != uint(- 1)) {
transferAllowances[src][spender] = allowanceNew;
}
emit Transfer(src, dst, tokens);
return 0;
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 amount) external override nonReentrant returns (bool) {
return transferTokens(msg.sender, msg.sender, dst, amount) == 0;
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint256 amount) external override nonReentrant returns (bool) {
return transferTokens(msg.sender, src, dst, amount) == 0;
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external override returns (bool) {
address src = msg.sender;
transferAllowances[src][spender] = amount;
emit Approval(src, spender, amount);
return true;
}
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent (-1 means infinite)
*/
function allowance(address owner, address spender) external override view returns (uint256) {
return transferAllowances[owner][spender];
}
/**
* @notice Get the token balance of the `owner`
* @param owner The address of the account to query
* @return The number of tokens owned by `owner`
*/
function balanceOf(address owner) external override view returns (uint256) {
return accountTokens[owner];
}
function balanceOfUnderlying(address owner) external override returns (uint) {
Exp memory exchangeRate = Exp({mantissa : exchangeRateCurrent()});
(MathError mErr, uint balance) = mulScalarTruncate(exchangeRate, accountTokens[owner]);
return balance;
}
/**
* @notice Get a snapshot of the account's balances, and the cached exchange rate
* @dev This is used by comptroller to more efficiently perform liquidity checks.
* @param account Address of the account to snapshot
* @return (possible error, token balance, borrow balance, exchange rate mantissa)
*/
function getAccountSnapshot(address account) external override view returns (uint, uint, uint, uint) {
uint pTokenBalance = accountTokens[account];
uint borrowBalance = borrowBalanceStoredInternal(account);
uint exchangeRateMantissa = exchangeRateStoredInternal();
return (0, pTokenBalance, borrowBalance, exchangeRateMantissa);
}
/**
* @dev Function to simply retrieve block number
* This exists mainly for inheriting test contracts to stub this result.
*/
function getBlockNumber() internal view returns (uint) {
return block.number;
}
/**
* @notice Returns the current per-block borrow interest rate for this cToken
* @return The borrow interest rate per block, scaled by 1e18
*/
function borrowRatePerBlock() external override view returns (uint) {
return interestRateModel.getBorrowRate(getCash(), totalBorrows, totalReserves);
}
/**
* @notice Returns the current per-block supply interest rate for this cToken
* @return The supply interest rate per block, scaled by 1e18
*/
function supplyRatePerBlock() external override view returns (uint) {
return interestRateModel.getSupplyRate(getCash(), totalBorrows, totalReserves, reserveFactorMantissa);
}
function totalBorrowsCurrent() external override nonReentrant returns (uint) {
accrueInterest();
return totalBorrows;
}
function borrowBalanceCurrent(address account) external override nonReentrant returns (uint) {
accrueInterest();
return borrowBalanceStored(account);
}
/**
* @notice Return the borrow balance of account based on stored data
* @param account The address whose balance should be calculated
* @return The calculated balance
*/
function borrowBalanceStored(address account) public override view returns (uint) {
return borrowBalanceStoredInternal(account);
}
function borrowInterestBalancePriorInternal(address account) internal view returns (uint) {
uint borrowBalance = borrowBalanceStoredInternal(account);
uint interestAmountPrior = borrowBalance.sub(accountBorrows[account].principal);
return interestAmountPrior;
}
/**
* @notice Return the borrow balance of account based on stored data
* @param account The address whose balance should be calculated
* If borrowBalance = 0 then borrowIndex is likely also 0
* Otherwise: recentBorrowBalance = borrower.borrowBalance * market.borrowIndex / borrower.borrowIndex
* @return (the calculated balance or 0 if error code is non-zero)
*/
function borrowBalanceStoredInternal(address account) internal view returns (uint) {
BorrowSnapshot storage borrowSnapshot = accountBorrows[account];
if (borrowSnapshot.principal == 0) {
return 0;
}
uint principalTimesIndex = borrowSnapshot.principal.mul(borrowIndex);
uint result = principalTimesIndex.div(borrowSnapshot.interestIndex);
return result;
}
function exchangeRateCurrent() public override nonReentrant returns (uint) {
accrueInterest();
return exchangeRateStored();
}
/**
* @notice Calculates the exchange rate from the underlying to the PToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateStored() public override view returns (uint) {
return exchangeRateStoredInternal();
}
/**
* @notice Calculates the exchange rate from the underlying to the CToken
* If there are no tokens minted: exchangeRate = initialExchangeRate
* Otherwise: exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply
* @dev This function does not accrue interest before calculating the exchange rate
* @return (calculated exchange rate scaled by 1e18)
*/
function exchangeRateStoredInternal() internal view returns (uint) {
uint _totalSupply = totalSupply;
if (_totalSupply == 0) {
return initialExchangeRateMantissa;
} else {
uint totalCash = getCash();
uint cashPlusBorrowsMinusReserves = totalCash.add(totalBorrows).sub(totalReserves);
(MathError mathErr, Exp memory exchangeRate) = getExp(cashPlusBorrowsMinusReserves, _totalSupply);
require(mathErr == MathError.NO_ERROR, "exchangeRateStoredInternal failed");
return exchangeRate.mantissa;
}
}
/**
* @notice Get cash balance of this cToken in the underlying asset
* @return The quantity of underlying asset owned by this contract
*/
function getCash() public override view returns (uint) {
return IEIP20(underlying).balanceOf(address(this));
}
/**
* @notice Applies accrued interest to total borrows and reserves
* @dev This calculates interest accrued from the last checkpointed block
* up to the current block and writes new checkpoint to storage.
*/
function accrueInterest() public override returns (uint) {
uint currentBlockNumber = getBlockNumber();
uint accrualBlockNumberPrior = accrualBlockNumber;
if (accrualBlockNumberPrior == currentBlockNumber) {
return uint(Error.NO_ERROR);
}
uint cashPrior = getCash();
uint borrowsPrior = totalBorrows;
uint reservesPrior = totalReserves;
uint borrowIndexPrior = borrowIndex;
uint borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, borrowsPrior, reservesPrior);
require(borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate is absurdly high");
uint blockDelta = currentBlockNumber.sub(accrualBlockNumberPrior);
MathError mathErr;
Exp memory simpleInterestFactor;
uint interestAccumulated;
uint totalBorrowsNew;
uint totalReservesNew;
uint borrowIndexNew;
(mathErr, simpleInterestFactor) = mulScalar(Exp({mantissa : borrowRateMantissa}), blockDelta);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, interestAccumulated) = mulScalarTruncate(simpleInterestFactor, borrowsPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, uint(mathErr));
}
totalBorrowsNew = interestAccumulated.add(borrowsPrior);
(mathErr, totalReservesNew) = mulScalarTruncateAddUInt(Exp({mantissa : reserveFactorMantissa}), interestAccumulated, reservesPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, borrowIndexNew) = mulScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, uint(mathErr));
}
accrualBlockNumber = currentBlockNumber;
borrowIndex = borrowIndexNew;
totalBorrows = totalBorrowsNew;
totalReserves = totalReservesNew;
emit AccrueInterest(cashPrior, interestAccumulated, borrowIndexNew, totalBorrowsNew, totalReservesNew);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender supplies assets into the market and receives cTokens in exchange
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param mintAmount The amount of the underlying asset to supply
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.
*/
function mint(uint mintAmount) external nonReentrant returns (uint) {
uint err = accrueInterest();
if (err != 0) {
return fail(Error(err), FailureInfo.MINT_ACCRUE_INTEREST_FAILED);
}
return mintFresh(msg.sender, mintAmount);
}
struct MintLocalVars {
Error err;
MathError mathErr;
uint exchangeRateMantissa;
uint mintTokens;
uint totalSupplyNew;
uint accountTokensNew;
uint actualMintAmount;
}
/**
* @notice User supplies assets into the market and receives cTokens in exchange
* @dev Assumes interest has already been accrued up to the current block
* @param minter The address of the account which is supplying the assets
* @param mintAmount The amount of the underlying asset to supply
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.
*/
function mintFresh(address minter, uint mintAmount) internal returns (uint) {
uint allowed = comptroller.mintAllowed(address(this), minter, mintAmount);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.MINT_COMPTROLLER_REJECTION, allowed);
}
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.MINT_FRESHNESS_CHECK);
}
MintLocalVars memory vars;
vars.exchangeRateMantissa = exchangeRateStoredInternal();
vars.actualMintAmount = doTransferIn(minter, mintAmount);
(vars.mathErr, vars.mintTokens) = divScalarByExpTruncate(vars.actualMintAmount, Exp({mantissa : vars.exchangeRateMantissa}));
require(vars.mathErr == MathError.NO_ERROR, "MINT_EXCHANGE_CALCULATION_FAILED");
vars.totalSupplyNew = totalSupply.add(vars.mintTokens);
vars.accountTokensNew = accountTokens[minter].add(vars.mintTokens);
totalSupply = vars.totalSupplyNew;
accountTokens[minter] = vars.accountTokensNew;
emit Mint(minter, vars.actualMintAmount, vars.mintTokens, vars.totalSupplyNew, vars.accountTokensNew);
emit Transfer(address(this), minter, vars.mintTokens);
return 0;
}
/**
* @notice Sender redeems cTokens in exchange for the underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemTokens The number of cTokens to redeem into underlying
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeem(uint redeemTokens) external nonReentrant returns (uint) {
uint err = accrueInterest();
if (err != 0) {
return fail(Error(err), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED);
}
return redeemFresh(msg.sender, redeemTokens, 0);
}
/**
* @notice Sender redeems cTokens in exchange for a specified amount of underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemAmount The amount of underlying to receive from redeeming cTokens
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemUnderlying(uint redeemAmount) external nonReentrant returns (uint) {
uint err = accrueInterest();
if (err != 0) {
return fail(Error(err), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED);
}
return redeemFresh(msg.sender, 0, redeemAmount);
}
struct RedeemLocalVars {
Error err;
MathError mathErr;
uint exchangeRateMantissa;
uint redeemTokens;
uint redeemAmount;
uint totalSupplyNew;
uint accountTokensNew;
}
/**
* @notice User redeems cTokens in exchange for the underlying asset
* @dev Assumes interest has already been accrued up to the current block
* @param redeemer The address of the account which is redeeming the tokens
* @param redeemTokensIn The number of cTokens to redeem into underlying (only one of redeemTokensIn or redeemAmountIn may be non-zero)
* @param redeemAmountIn The number of underlying tokens to receive from redeeming cTokens (only one of redeemTokensIn or redeemAmountIn may be non-zero)
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemFresh(address payable redeemer, uint redeemTokensIn, uint redeemAmountIn) internal returns (uint) {
RedeemLocalVars memory vars;
vars.exchangeRateMantissa = exchangeRateStoredInternal();
if (redeemTokensIn > 0) {
vars.redeemTokens = redeemTokensIn;
(vars.mathErr, vars.redeemAmount) = mulScalarTruncate(Exp({mantissa : vars.exchangeRateMantissa}), redeemTokensIn);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, uint(vars.mathErr));
}
} else {
(vars.mathErr, vars.redeemTokens) = divScalarByExpTruncate(redeemAmountIn, Exp({mantissa : vars.exchangeRateMantissa}));
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, uint(vars.mathErr));
}
vars.redeemAmount = redeemAmountIn;
}
uint allowed = comptroller.redeemAllowed(address(this), redeemer, vars.redeemTokens);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REDEEM_COMPTROLLER_REJECTION, allowed);
}
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDEEM_FRESHNESS_CHECK);
}
vars.totalSupplyNew = totalSupply.sub(vars.redeemTokens);
vars.accountTokensNew = accountTokens[redeemer].sub(vars.redeemTokens);
if (getCash() < vars.redeemAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE);
}
doTransferOut(redeemer, vars.redeemAmount);
totalSupply = vars.totalSupplyNew;
accountTokens[redeemer] = vars.accountTokensNew;
emit Transfer(redeemer, address(this), vars.redeemTokens);
emit Redeem(redeemer, vars.redeemAmount, vars.redeemTokens, vars.totalSupplyNew, vars.accountTokensNew);
return 0;
}
/**
* @notice Sender borrows assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrow(uint borrowAmount) external nonReentrant returns (uint) {
uint err = accrueInterest();
if (err != 0) {
return fail(Error(err), FailureInfo.BORROW_ACCRUE_INTEREST_FAILED);
}
return borrowFresh(msg.sender, borrowAmount);
}
struct BorrowLocalVars {
MathError mathErr;
uint accountBorrows;
uint accountBorrowsNew;
uint totalBorrowsNew;
uint interestBalancePrior; //interest balance before now.
}
/**
* @notice Users borrow assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrowFresh(address payable borrower, uint borrowAmount) internal returns (uint) {
uint allowed = comptroller.borrowAllowed(address(this), borrower, borrowAmount);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.BORROW_COMPTROLLER_REJECTION, allowed);
}
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.BORROW_FRESHNESS_CHECK);
}
if (getCash() < borrowAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_CASH_NOT_AVAILABLE);
}
BorrowLocalVars memory vars;
vars.interestBalancePrior = borrowInterestBalancePriorInternal(borrower);
vars.accountBorrows = borrowBalanceStoredInternal(borrower);
vars.accountBorrowsNew = vars.accountBorrows.add(borrowAmount);
vars.totalBorrowsNew = totalBorrows.add(borrowAmount);
doTransferOut(borrower, borrowAmount);
accountBorrows[borrower].principal = vars.accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = vars.totalBorrowsNew;
emit Borrow(borrower, borrowAmount, vars.accountBorrowsNew, vars.totalBorrowsNew, vars.interestBalancePrior);
return 0;
}
/**
* @notice Sender repays their own borrow
* @param repayAmount The amount to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrow(uint repayAmount) external nonReentrant returns (uint) {
uint err = accrueInterest();
if (err != 0) {
return fail(Error(err), FailureInfo.REPAY_BORROW_ACCRUE_INTEREST_FAILED);
}
(err,) = repayBorrowFresh(msg.sender, msg.sender, repayAmount);
return err;
}
/**
* @notice Sender repays a borrow belonging to borrower
* @param borrower the account with the debt being payed off
* @param repayAmount The amount to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowBehalf(address borrower, uint repayAmount) external nonReentrant returns (uint) {
uint err = accrueInterest();
if (err != 0) {
return fail(Error(err), FailureInfo.REPAY_BEHALF_ACCRUE_INTEREST_FAILED);
}
(err,) = repayBorrowFresh(msg.sender, borrower, repayAmount);
return err;
}
struct RepayBorrowLocalVars {
Error err;
MathError mathErr;
uint repayAmount;
uint borrowerIndex;
uint accountBorrows;
uint accountBorrowsNew;
uint totalBorrowsNew;
uint actualRepayAmount;
uint interestBalancePrior;
}
/**
* @notice Borrows are repaid by another user (possibly the borrower).
* @param payer the account paying off the borrow
* @param borrower the account with the debt being payed off
* @param repayAmount the amount of undelrying tokens being returned
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowFresh(address payer, address borrower, uint repayAmount) internal returns (uint, uint) {
uint allowed = comptroller.repayBorrowAllowed(address(this), payer, borrower, repayAmount);
if (allowed != 0) {
return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REPAY_BORROW_COMPTROLLER_REJECTION, allowed), 0);
}
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.REPAY_BORROW_FRESHNESS_CHECK), 0);
}
RepayBorrowLocalVars memory vars;
vars.borrowerIndex = accountBorrows[borrower].interestIndex;
vars.interestBalancePrior = borrowInterestBalancePriorInternal(borrower);
vars.accountBorrows = borrowBalanceStoredInternal(borrower);
if (repayAmount == uint(- 1)) {
vars.repayAmount = vars.accountBorrows;
} else {
vars.repayAmount = repayAmount;
}
vars.actualRepayAmount = doTransferIn(payer, vars.repayAmount);
vars.accountBorrowsNew = vars.accountBorrows.sub(vars.actualRepayAmount);
vars.totalBorrowsNew = totalBorrows.sub(vars.actualRepayAmount);
accountBorrows[borrower].principal = vars.accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = vars.totalBorrowsNew;
emit RepayBorrow(payer, borrower, vars.actualRepayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew, vars.interestBalancePrior);
return (0, vars.actualRepayAmount);
}
/**
* @notice The sender liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this cToken to be liquidated
* @param pTokenCollateral The market in which to seize collateral from the borrower
* @param repayAmount The amount of the underlying borrowed asset to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function liquidateBorrow(address borrower, uint repayAmount, IPToken pTokenCollateral) external nonReentrant returns (uint) {
uint err = accrueInterest();
if (err != 0) {
return fail(Error(err), FailureInfo.LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED);
}
err = pTokenCollateral.accrueInterest();
if (err != 0) {
return fail(Error(err), FailureInfo.LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED);
}
return liquidateBorrowFresh(msg.sender, borrower, repayAmount, pTokenCollateral);
}
/**
* @notice The liquidator liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this cToken to be liquidated
* @param liquidator The address repaying the borrow and seizing collateral
* @param pTokenCollateral The market in which to seize collateral from the borrower
* @param repayAmount The amount of the underlying borrowed asset to repay
* @return (uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol)
*/
function liquidateBorrowFresh(address liquidator, address borrower, uint repayAmount, IPToken pTokenCollateral) internal returns (uint) {
uint allowed = comptroller.liquidateBorrowAllowed(address(this), address(pTokenCollateral), liquidator, borrower, repayAmount);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_COMPTROLLER_REJECTION, allowed);
}
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_FRESHNESS_CHECK);
}
if (pTokenCollateral.accrualBlockNumber() != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_COLLATERAL_FRESHNESS_CHECK);
}
if (borrower == liquidator) {
return fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_LIQUIDATOR_IS_BORROWER);
}
if (repayAmount == 0) {
return fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_ZERO);
}
if (repayAmount == uint(- 1)) {
return fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX);
}
(uint repayBorrowError, uint actualRepayAmount) = repayBorrowFresh(liquidator, borrower, repayAmount);
if (repayBorrowError != uint(Error.NO_ERROR)) {
return fail(Error(repayBorrowError), FailureInfo.LIQUIDATE_REPAY_BORROW_FRESH_FAILED);
}
(uint amountSeizeError, uint seizeTokens) = comptroller.liquidateCalculateSeizeTokens(address(this), address(pTokenCollateral), actualRepayAmount);
require(amountSeizeError == uint(Error.NO_ERROR), "LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED");
require(pTokenCollateral.balanceOf(borrower) >= seizeTokens, "LIQUIDATE_SEIZE_TOO_MUCH");
uint seizeError;
if (address(pTokenCollateral) == address(this)) {
seizeError = seizeInternal(address(this), liquidator, borrower, seizeTokens);
} else {
seizeError = pTokenCollateral.seize(liquidator, borrower, seizeTokens);
}
require(seizeError == uint(Error.NO_ERROR), "token seizure failed");
emit LiquidateBorrow(liquidator, borrower, actualRepayAmount, address(pTokenCollateral), seizeTokens);
return 0;
}
/**
* @notice Transfers collateral tokens (this market) to the liquidator.
* @dev Will fail unless called by another cToken during the process of liquidation.
* Its absolutely critical to use msg.sender as the borrowed cToken and not a parameter.
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of cTokens to seize
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function seize(address liquidator, address borrower, uint seizeTokens) external override nonReentrant returns (uint) {
return seizeInternal(msg.sender, liquidator, borrower, seizeTokens);
}
/**
* @notice Transfers collateral tokens (this market) to the liquidator.
* @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another PToken.
* Its absolutely critical to use msg.sender as the seizer cToken and not a parameter.
* @param seizerToken The contract seizing the collateral (i.e. borrowed cToken)
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of cTokens to seize
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function seizeInternal(address seizerToken, address liquidator, address borrower, uint seizeTokens) internal returns (uint) {
uint allowed = comptroller.seizeAllowed(address(this), seizerToken, liquidator, borrower, seizeTokens);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_SEIZE_COMPTROLLER_REJECTION, allowed);
}
if (borrower == liquidator) {
return fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER);
}
MathError mathErr;
uint borrowerTokensNew = accountTokens[borrower].sub(seizeTokens);
uint liquidatorTokensNew = accountTokens[liquidator].add(seizeTokens);
accountTokens[borrower] = borrowerTokensNew;
accountTokens[liquidator] = liquidatorTokensNew;
emit Transfer(borrower, liquidator, seizeTokens);
return 0;
}
/*** Admin Functions ***/
/**
* @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh
* @dev Admin function to accrue interest and set a new reserve factor
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setReserveFactor(uint newReserveFactorMantissa) external onlyOwner override nonReentrant returns (uint) {
uint err = accrueInterest();
if (err != 0) {
return fail(Error(err), FailureInfo.SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED);
}
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_RESERVE_FACTOR_FRESH_CHECK);
}
if (newReserveFactorMantissa > reserveFactorMaxMantissa) {
return fail(Error.BAD_INPUT, FailureInfo.SET_RESERVE_FACTOR_BOUNDS_CHECK);
}
reserveFactorMantissa = newReserveFactorMantissa;
return 0;
}
/**
* @notice Accrues interest and reduces reserves by transferring from msg.sender
* @param addAmount Amount of addition to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _addReserves(uint addAmount) external nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != 0) {
return fail(Error(error), FailureInfo.ADD_RESERVES_ACCRUE_INTEREST_FAILED);
}
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.ADD_RESERVES_FRESH_CHECK);
}
uint actualAddAmount = doTransferIn(msg.sender, addAmount);
uint totalReservesNew = totalReserves + actualAddAmount;
require(totalReservesNew >= totalReserves, "addAmount error");
totalReserves = totalReservesNew;
emit ReservesAdded(msg.sender, actualAddAmount, totalReservesNew);
return 0;
}
/**
* @notice Accrues interest and reduces reserves by transferring to admin
* @param reduceAmount Amount of reduction to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _reduceReserves(uint reduceAmount) external override nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != 0) {
return fail(Error(error), FailureInfo.REDUCE_RESERVES_ACCRUE_INTEREST_FAILED);
}
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDUCE_RESERVES_FRESH_CHECK);
}
if (getCash() < reduceAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDUCE_RESERVES_CASH_NOT_AVAILABLE);
}
if (reduceAmount > totalReserves) {
return fail(Error.BAD_INPUT, FailureInfo.REDUCE_RESERVES_VALIDATION);
}
uint totalReservesNew = totalReserves - reduceAmount;
require(totalReservesNew <= totalReserves, "reduceAmount error");
totalReserves = totalReservesNew;
doTransferOut(payable(owner()), reduceAmount);
emit ReservesReduced(owner(), reduceAmount, totalReservesNew);
return 0;
}
/**
* @notice accrues interest and updates the interest rate model using _setInterestRateModelFresh
* @dev Admin function to accrue interest and update the interest rate model
* @param _interestRateModel the new interest rate model to use
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setInterestRateModel(IInterestRateModel _interestRateModel) public onlyOwner override returns (uint) {
if (interestRateModel != IInterestRateModel(0)) {
accrueInterest();
}
interestRateModel = _interestRateModel;
return 0;
}
/**
* @notice Sets a new comptroller for the market
* @dev Admin function to set a new comptroller
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setComptroller(IComptroller _comptroller) public onlyOwner override returns (uint) {
comptroller = _comptroller;
return 0;
}
/*** Safe Token ***/
/**
* @dev Similar to EIP20 transfer, except it handles a False result from `transferFrom` and reverts in that case.
* This will revert due to insufficient balance or insufficient allowance.
* This function returns the actual amount received,
* which may be less than `amount` if there is a fee attached to the transfer.
*
* Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value.
* See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
function doTransferIn(address from, uint amount) internal returns (uint) {
IEIP20 token = IEIP20(underlying);
uint balanceBefore = token.balanceOf(address(this));
token.transferFrom(from, address(this), amount);
bool success;
assembly {
switch returndatasize()
case 0 {
success := not(0)
}
case 32 {
returndatacopy(0, 0, 32)
success := mload(0)
}
default {
revert(0, 0)
}
}
require(success, "TOKEN_TRANSFER_IN_FAILED");
uint balanceAfter = token.balanceOf(address(this));
require(balanceAfter >= balanceBefore, "TOKEN_TRANSFER_IN_OVERFLOW");
return balanceAfter - balanceBefore;
}
/**
* @dev Similar to EIP20 transfer, except it handles a False success from `transfer` and returns an explanatory
* error code rather than reverting. If caller has not called checked protocol's balance, this may revert due to
* insufficient cash held in this contract. If caller has checked protocol's balance prior to this call, and verified
* it is >= amount, this should not revert in normal conditions.
*
* Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value.
* See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
function doTransferOut(address payable to, uint amount) internal {
IEIP20 token = IEIP20(underlying);
token.transfer(to, amount);
bool success;
assembly {
switch returndatasize()
case 0 {
success := not(0)
}
case 32 {
returndatacopy(0, 0, 32)
success := mload(0)
}
default {
revert(0, 0)
}
}
require(success, "TOKEN_TRANSFER_OUT_FAILED");
}
/*** Reentrancy Guard ***/
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
*/
modifier nonReentrant() {
require(_notEntered, "re-entered");
_notEntered = false;
_;
_notEntered = true;
}
}
|
Borrows are repaid by another user (possibly the borrower). payer the account paying off the borrow borrower the account with the debt being payed off repayAmount the amount of undelrying tokens being returned return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount./
|
function repayBorrowFresh(address payer, address borrower, uint repayAmount) internal returns (uint, uint) {
uint allowed = comptroller.repayBorrowAllowed(address(this), payer, borrower, repayAmount);
if (allowed != 0) {
return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REPAY_BORROW_COMPTROLLER_REJECTION, allowed), 0);
}
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.REPAY_BORROW_FRESHNESS_CHECK), 0);
}
RepayBorrowLocalVars memory vars;
vars.borrowerIndex = accountBorrows[borrower].interestIndex;
vars.interestBalancePrior = borrowInterestBalancePriorInternal(borrower);
vars.accountBorrows = borrowBalanceStoredInternal(borrower);
if (repayAmount == uint(- 1)) {
vars.repayAmount = vars.accountBorrows;
vars.repayAmount = repayAmount;
}
vars.actualRepayAmount = doTransferIn(payer, vars.repayAmount);
vars.accountBorrowsNew = vars.accountBorrows.sub(vars.actualRepayAmount);
vars.totalBorrowsNew = totalBorrows.sub(vars.actualRepayAmount);
accountBorrows[borrower].principal = vars.accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = vars.totalBorrowsNew;
emit RepayBorrow(payer, borrower, vars.actualRepayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew, vars.interestBalancePrior);
return (0, vars.actualRepayAmount);
}
| 908,571 |
./partial_match/4/0x8d059179C7193dD292b89bA12869A0C559F4CDA8/sources/ERC20.sol
|
Burns a specific amount of tokens. amount The amount of token to be burned./
|
function burn(uint256 amount) public onlyOwner
{
_burn(msg.sender, amount);
}
| 8,651,086 |
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
contract Universe {
using SafeMath for uint;
//The register of poem creators
mapping (uint => address) public poemOwners;
//The maximum number of poems
uint constant public MAXPOEMS = 100;
//The array of all poems
bytes32[MAXPOEMS] public poems;
//A mask for selecting half of the poems
bytes32 mask = 0x00000000000000000000000000000000ffffffffffffffffffffffffffffffff;
//A mask to be used when selecting the other half
bytes32 mask2 = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
//The IPFS hash of the words
string URL = "https://ipfs.io/ipfs/QmbKfq8MUGduaTk71aegxpzUseBxmufXW9MPaLy7c31Bcu";
//An event to log all newly made poems
event LogNewPoem(uint rejectedPoemId, address owner, bytes32 newPoem);
/*
* constructor that creates the initial set of poems
* @emits new poems
*/
constructor() public {
//Create the first poem, using the contract creator's address as a random seed
poems[0] = keccak256(abi.encodePacked(msg.sender));
emit LogNewPoem(0, msg.sender, poems[0]);
//Create the remaining poems
for(uint i=1; i<poems.length; i++) {
poems[i] = keccak256(abi.encodePacked(poems[i-1]));
emit LogNewPoem(i, msg.sender, poems[i]);
}
}
/*
* A function to get hardcoded url of the dictionary
* @returns the url of the dictionary on ipfs
*/
function getDictionary() view public returns (string memory) {
return URL;
}
/*
* A function that will delete a poem from the array of poems and
* in its place will go a new poem created by evolvePoem function
* @param _selectedPoemId is the index of the poem in the array poems that will be spliced
* @param _rejectedPoemId is the index of the poem in the array poems that will be deleted
* @emits _rejectedPoemId, msg.sender and new poem
* @returns nothing
*/
function selectPoem(uint _selectedPoemId, uint _rejectedPoemId) public {
require(_selectedPoemId >= 0 && _selectedPoemId < MAXPOEMS && _rejectedPoemId >= 0 && _rejectedPoemId < MAXPOEMS && _selectedPoemId != _rejectedPoemId);
bytes32 newPoem = evolvePoem(_selectedPoemId);
poems[_rejectedPoemId] = newPoem;
poemOwners[_rejectedPoemId] = msg.sender;
emit LogNewPoem(_rejectedPoemId, msg.sender, newPoem);
}
/*
* A function to get all poems
* @returns the array of all poems
*/
function getPoems() view public returns (bytes32[MAXPOEMS] memory) {
return poems;
}
/*
* A function to get a poem at a given index
* @param id is the index of the poem in the array poems
* @returns the poem at the index specified
*/
function getPoem(uint id) view public returns (bytes32) {
return poems[id];
}
/*
* A function to get a poem's creator
* @param is the index of the poem in the array of poems
* @returns the poem at the index specified
*/
function getPoemOwner(uint id) view public returns (address poemOwner) {
require(id < MAXPOEMS);
return poemOwners[id];
}
/*
* A function to get two different arbitrary poems
* @returns two poems and their indices
*/
function getTwoPoems() view public returns (uint IDofFirstPoem, bytes32 poemA, uint IDofSecondPoem, bytes32 poemB) {
//Get one arbitrary poem ID using timestamp
uint arbitraryPoem1 = uint(block.timestamp.mod(MAXPOEMS));
uint arbitraryPoem2 = uint(block.number.mod(MAXPOEMS));
//Make sure second arbitrary poem ID using block height is difference from arbitraryPoem1
if(arbitraryPoem1 == arbitraryPoem2) {
arbitraryPoem2++;
}
return (arbitraryPoem1, poems[arbitraryPoem1], arbitraryPoem2, poems[arbitraryPoem2]);
}
/*
* An internal function to get the splice of two poems
* @returns one new poem
*/
function evolvePoem(uint _selectedPoemId) internal view returns (bytes32) {
//Get an arbitrary number
uint arbitraryMate = uint(block.timestamp.mod(MAXPOEMS));
//Move the mask to pick a random 128 contiguous bits
uint arbitraryGeneShare = uint(block.timestamp.mod(128));
//Move the mask
bytes32 tempMask1 = mask << arbitraryGeneShare;
//Create the opposite mask
bytes32 tempMask2 = mask2 ^ tempMask1;
//Mask selected poem to keep half
bytes32 keep1 = poems[_selectedPoemId] & tempMask1;
//Mask arbitrary poem to keep opposite half
bytes32 keep2 = poems[arbitraryMate] & tempMask2;
//Merge poems by masking one with the other
bytes32 evolvedPoem = keep1 | keep2;
return evolvedPoem;
}
}
|
A function to get a poem at a given index id is the index of the poem in the array poems returns the poem at the index specified/
|
function getPoem(uint id) view public returns (bytes32) {
return poems[id];
}
| 1,086,879 |
./full_match/1/0x25e3C9dBAC271a2500071f9eea9993155836E9a0/sources/contracts/Messaging.sol
|
Consume l2 message.
|
function _consumeL2Message(uint256 l2ContractAddress, uint256[] memory data) internal {
starknetCore.consumeMessageFromL2(l2ContractAddress, data);
}
| 16,486,110 |
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.2;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
function totalSupply() external view returns (uint256);
function decimals() external view returns (uint8);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev Interface of the ERC2612 standard as defined in the EIP.
*
* Adds the {permit} method, which can be used to change one's
* {IERC20-allowance} without having to send a transaction, by signing a
* message. This allows users to spend tokens without having to hold Ether.
*
* See https://eips.ethereum.org/EIPS/eip-2612.
*/
interface IERC2612 {
/**
* @dev Returns the current ERC2612 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);
function permit(address target, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external;
function transferWithPermit(address target, address to, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external returns (bool);
}
/// @dev Wrapped ERC-20 v10 (AnyswapV3ERC20) is an ERC-20 ERC-20 wrapper. You can `deposit` ERC-20 and obtain an AnyswapV3ERC20 balance which can then be operated as an ERC-20 token. You can
/// `withdraw` ERC-20 from AnyswapV3ERC20, which will then burn AnyswapV3ERC20 token in your wallet. The amount of AnyswapV3ERC20 token in any wallet is always identical to the
/// balance of ERC-20 deposited minus the ERC-20 withdrawn with that specific wallet.
interface IAnyswapV3ERC20 is IERC20, IERC2612 {
/// @dev Sets `value` as allowance of `spender` account over caller account's AnyswapV3ERC20 token,
/// after which a call is executed to an ERC677-compliant contract with the `data` parameter.
/// Emits {Approval} event.
/// Returns boolean value indicating whether operation succeeded.
/// For more information on approveAndCall format, see https://github.com/ethereum/EIPs/issues/677.
function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
/// @dev Moves `value` AnyswapV3ERC20 token from caller's account to account (`to`),
/// after which a call is executed to an ERC677-compliant contract with the `data` parameter.
/// A transfer to `address(0)` triggers an ERC-20 withdraw matching the sent AnyswapV3ERC20 token in favor of caller.
/// Emits {Transfer} event.
/// Returns boolean value indicating whether operation succeeded.
/// Requirements:
/// - caller account must have at least `value` AnyswapV3ERC20 token.
/// For more information on transferAndCall format, see https://github.com/ethereum/EIPs/issues/677.
function transferAndCall(address to, uint value, bytes calldata data) external returns (bool);
}
interface ITransferReceiver {
function onTokenTransfer(address, uint, bytes calldata) external returns (bool);
}
interface IApprovalReceiver {
function onTokenApproval(address, uint, bytes calldata) external returns (bool);
}
library Address {
function isContract(address account) internal view returns (bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
library SafeERC20 {
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract AnyswapV6ERC20 is IAnyswapV3ERC20 {
using SafeERC20 for IERC20;
string public name;
string public symbol;
uint8 public immutable override decimals;
address public immutable underlying;
bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 public constant TRANSFER_TYPEHASH = keccak256("Transfer(address owner,address to,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 public immutable DOMAIN_SEPARATOR;
/// @dev Records amount of AnyswapV3ERC20 token owned by account.
mapping (address => uint256) public override balanceOf;
uint256 private _totalSupply;
// init flag for setting immediate vault, needed for CREATE2 support
bool private _init;
// flag to enable/disable swapout vs vault.burn so multiple events are triggered
bool private _vaultOnly;
// configurable delay for timelock functions
uint public delay = 2*24*3600;
// set of minters, can be this bridge or other bridges
mapping(address => bool) public isMinter;
address[] public minters;
// primary controller of the token contract
address public vault;
address public pendingMinter;
uint public delayMinter;
address public pendingVault;
uint public delayVault;
modifier onlyAuth() {
require(isMinter[msg.sender], "AnyswapV4ERC20: FORBIDDEN");
_;
}
modifier onlyVault() {
require(msg.sender == mpc(), "AnyswapV3ERC20: FORBIDDEN");
_;
}
function owner() public view returns (address) {
return mpc();
}
function mpc() public view returns (address) {
if (block.timestamp >= delayVault) {
return pendingVault;
}
return vault;
}
function setVaultOnly(bool enabled) external onlyVault {
_vaultOnly = enabled;
}
function initVault(address _vault) external onlyVault {
require(_init);
vault = _vault;
pendingVault = _vault;
isMinter[_vault] = true;
minters.push(_vault);
delayVault = block.timestamp;
_init = false;
}
function setVault(address _vault) external onlyVault {
require(_vault != address(0), "AnyswapV3ERC20: address(0x0)");
pendingVault = _vault;
delayVault = block.timestamp + delay;
}
function applyVault() external onlyVault {
require(block.timestamp >= delayVault);
vault = pendingVault;
}
function setMinter(address _auth) external onlyVault {
require(_auth != address(0), "AnyswapV3ERC20: address(0x0)");
pendingMinter = _auth;
delayMinter = block.timestamp + delay;
}
function applyMinter() external onlyVault {
require(block.timestamp >= delayMinter);
isMinter[pendingMinter] = true;
minters.push(pendingMinter);
}
// No time delay revoke minter emergency function
function revokeMinter(address _auth) external onlyVault {
isMinter[_auth] = false;
}
function getAllMinters() external view returns (address[] memory) {
return minters;
}
function changeVault(address newVault) external onlyVault returns (bool) {
require(newVault != address(0), "AnyswapV3ERC20: address(0x0)");
vault = newVault;
pendingVault = newVault;
emit LogChangeVault(vault, pendingVault, block.timestamp);
return true;
}
function mint(address to, uint256 amount) external onlyAuth returns (bool) {
_mint(to, amount);
return true;
}
function burn(address from, uint256 amount) external onlyAuth returns (bool) {
require(from != address(0), "AnyswapV3ERC20: address(0x0)");
_burn(from, amount);
return true;
}
function Swapin(bytes32 txhash, address account, uint256 amount) public onlyAuth returns (bool) {
_mint(account, amount);
emit LogSwapin(txhash, account, amount);
return true;
}
function Swapout(uint256 amount, address bindaddr) public returns (bool) {
require(!_vaultOnly, "AnyswapV4ERC20: onlyAuth");
require(bindaddr != address(0), "AnyswapV3ERC20: address(0x0)");
_burn(msg.sender, amount);
emit LogSwapout(msg.sender, bindaddr, amount);
return true;
}
/// @dev Records current ERC2612 nonce for account. This value must be included whenever signature is generated for {permit}.
/// Every successful call to {permit} increases account's nonce by one. This prevents signature from being used multiple times.
mapping (address => uint256) public override nonces;
/// @dev Records number of AnyswapV3ERC20 token that account (second) will be allowed to spend on behalf of another account (first) through {transferFrom}.
mapping (address => mapping (address => uint256)) public override allowance;
event LogChangeVault(address indexed oldVault, address indexed newVault, uint indexed effectiveTime);
event LogSwapin(bytes32 indexed txhash, address indexed account, uint amount);
event LogSwapout(address indexed account, address indexed bindaddr, uint amount);
constructor(string memory _name, string memory _symbol, uint8 _decimals, address _underlying, address _vault) {
name = _name;
symbol = _symbol;
decimals = _decimals;
underlying = _underlying;
if (_underlying != address(0x0)) {
require(_decimals == IERC20(_underlying).decimals());
}
// Use init to allow for CREATE2 accross all chains
_init = true;
// Disable/Enable swapout for v1 tokens vs mint/burn for v3 tokens
_vaultOnly = false;
vault = _vault;
pendingVault = _vault;
delayVault = block.timestamp;
uint256 chainId;
assembly {chainId := chainid()}
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
keccak256(bytes(name)),
keccak256(bytes("1")),
chainId,
address(this)));
}
/// @dev Returns the total supply of AnyswapV3ERC20 token as the ETH held in this contract.
function totalSupply() external view override returns (uint256) {
return _totalSupply;
}
function deposit() external returns (uint) {
uint _amount = IERC20(underlying).balanceOf(msg.sender);
IERC20(underlying).safeTransferFrom(msg.sender, address(this), _amount);
return _deposit(_amount, msg.sender);
}
function deposit(uint amount) external returns (uint) {
IERC20(underlying).safeTransferFrom(msg.sender, address(this), amount);
return _deposit(amount, msg.sender);
}
function deposit(uint amount, address to) external returns (uint) {
IERC20(underlying).safeTransferFrom(msg.sender, address(this), amount);
return _deposit(amount, to);
}
function depositVault(uint amount, address to) external onlyVault returns (uint) {
return _deposit(amount, to);
}
function _deposit(uint amount, address to) internal returns (uint) {
require(underlying != address(0x0) && underlying != address(this));
_mint(to, amount);
return amount;
}
function withdraw() external returns (uint) {
return _withdraw(msg.sender, balanceOf[msg.sender], msg.sender);
}
function withdraw(uint amount) external returns (uint) {
return _withdraw(msg.sender, amount, msg.sender);
}
function withdraw(uint amount, address to) external returns (uint) {
return _withdraw(msg.sender, amount, to);
}
function withdrawVault(address from, uint amount, address to) external onlyVault returns (uint) {
return _withdraw(from, amount, to);
}
function _withdraw(address from, uint amount, address to) internal returns (uint) {
_burn(from, amount);
IERC20(underlying).safeTransfer(to, amount);
return 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 += amount;
balanceOf[account] += amount;
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
balanceOf[account] -= amount;
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
}
/// @dev Sets `value` as allowance of `spender` account over caller account's AnyswapV3ERC20 token.
/// Emits {Approval} event.
/// Returns boolean value indicating whether operation succeeded.
function approve(address spender, uint256 value) external override returns (bool) {
// _approve(msg.sender, spender, value);
allowance[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/// @dev Sets `value` as allowance of `spender` account over caller account's AnyswapV3ERC20 token,
/// after which a call is executed to an ERC677-compliant contract with the `data` parameter.
/// Emits {Approval} event.
/// Returns boolean value indicating whether operation succeeded.
/// For more information on approveAndCall format, see https://github.com/ethereum/EIPs/issues/677.
function approveAndCall(address spender, uint256 value, bytes calldata data) external override returns (bool) {
// _approve(msg.sender, spender, value);
allowance[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return IApprovalReceiver(spender).onTokenApproval(msg.sender, value, data);
}
/// @dev Sets `value` as allowance of `spender` account over `owner` account's AnyswapV3ERC20 token, given `owner` account's signed approval.
/// Emits {Approval} event.
/// Requirements:
/// - `deadline` must be timestamp in future.
/// - `v`, `r` and `s` must be valid `secp256k1` signature from `owner` account over EIP712-formatted function arguments.
/// - the signature must use `owner` account's current nonce (see {nonces}).
/// - the signer cannot be zero address and must be `owner` account.
/// For more information on signature format, see https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP section].
/// AnyswapV3ERC20 token implementation adapted from https://github.com/albertocuestacanada/ERC20Permit/blob/master/contracts/ERC20Permit.sol.
function permit(address target, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external override {
require(block.timestamp <= deadline, "AnyswapV3ERC20: Expired permit");
bytes32 hashStruct = keccak256(
abi.encode(
PERMIT_TYPEHASH,
target,
spender,
value,
nonces[target]++,
deadline));
require(verifyEIP712(target, hashStruct, v, r, s) || verifyPersonalSign(target, hashStruct, v, r, s));
// _approve(owner, spender, value);
allowance[target][spender] = value;
emit Approval(target, spender, value);
}
function transferWithPermit(address target, address to, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external override returns (bool) {
require(block.timestamp <= deadline, "AnyswapV3ERC20: Expired permit");
bytes32 hashStruct = keccak256(
abi.encode(
TRANSFER_TYPEHASH,
target,
to,
value,
nonces[target]++,
deadline));
require(verifyEIP712(target, hashStruct, v, r, s) || verifyPersonalSign(target, hashStruct, v, r, s));
require(to != address(0) || to != address(this));
uint256 balance = balanceOf[target];
require(balance >= value, "AnyswapV3ERC20: transfer amount exceeds balance");
balanceOf[target] = balance - value;
balanceOf[to] += value;
emit Transfer(target, to, value);
return true;
}
function verifyEIP712(address target, bytes32 hashStruct, uint8 v, bytes32 r, bytes32 s) internal view returns (bool) {
bytes32 hash = keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR,
hashStruct));
address signer = ecrecover(hash, v, r, s);
return (signer != address(0) && signer == target);
}
function verifyPersonalSign(address target, bytes32 hashStruct, uint8 v, bytes32 r, bytes32 s) internal view returns (bool) {
bytes32 hash = keccak256(
abi.encodePacked(
"\x19Ethereum Signed Message:\n32",
DOMAIN_SEPARATOR,
hashStruct));
address signer = ecrecover(hash, v, r, s);
return (signer != address(0) && signer == target);
}
/// @dev Moves `value` AnyswapV3ERC20 token from caller's account to account (`to`).
/// A transfer to `address(0)` triggers an ETH withdraw matching the sent AnyswapV3ERC20 token in favor of caller.
/// Emits {Transfer} event.
/// Returns boolean value indicating whether operation succeeded.
/// Requirements:
/// - caller account must have at least `value` AnyswapV3ERC20 token.
function transfer(address to, uint256 value) external override returns (bool) {
require(to != address(0) || to != address(this));
uint256 balance = balanceOf[msg.sender];
require(balance >= value, "AnyswapV3ERC20: transfer amount exceeds balance");
balanceOf[msg.sender] = balance - value;
balanceOf[to] += value;
emit Transfer(msg.sender, to, value);
return true;
}
/// @dev Moves `value` AnyswapV3ERC20 token from account (`from`) to account (`to`) using allowance mechanism.
/// `value` is then deducted from caller account's allowance, unless set to `type(uint256).max`.
/// A transfer to `address(0)` triggers an ETH withdraw matching the sent AnyswapV3ERC20 token in favor of caller.
/// Emits {Approval} event to reflect reduced allowance `value` for caller account to spend from account (`from`),
/// unless allowance is set to `type(uint256).max`
/// Emits {Transfer} event.
/// Returns boolean value indicating whether operation succeeded.
/// Requirements:
/// - `from` account must have at least `value` balance of AnyswapV3ERC20 token.
/// - `from` account must have approved caller to spend at least `value` of AnyswapV3ERC20 token, unless `from` and caller are the same account.
function transferFrom(address from, address to, uint256 value) external override returns (bool) {
require(to != address(0) || to != address(this));
if (from != msg.sender) {
// _decreaseAllowance(from, msg.sender, value);
uint256 allowed = allowance[from][msg.sender];
if (allowed != type(uint256).max) {
require(allowed >= value, "AnyswapV3ERC20: request exceeds allowance");
uint256 reduced = allowed - value;
allowance[from][msg.sender] = reduced;
emit Approval(from, msg.sender, reduced);
}
}
uint256 balance = balanceOf[from];
require(balance >= value, "AnyswapV3ERC20: transfer amount exceeds balance");
balanceOf[from] = balance - value;
balanceOf[to] += value;
emit Transfer(from, to, value);
return true;
}
/// @dev Moves `value` AnyswapV3ERC20 token from caller's account to account (`to`),
/// after which a call is executed to an ERC677-compliant contract with the `data` parameter.
/// A transfer to `address(0)` triggers an ETH withdraw matching the sent AnyswapV3ERC20 token in favor of caller.
/// Emits {Transfer} event.
/// Returns boolean value indicating whether operation succeeded.
/// Requirements:
/// - caller account must have at least `value` AnyswapV3ERC20 token.
/// For more information on transferAndCall format, see https://github.com/ethereum/EIPs/issues/677.
function transferAndCall(address to, uint value, bytes calldata data) external override returns (bool) {
require(to != address(0) || to != address(this));
uint256 balance = balanceOf[msg.sender];
require(balance >= value, "AnyswapV3ERC20: transfer amount exceeds balance");
balanceOf[msg.sender] = balance - value;
balanceOf[to] += value;
emit Transfer(msg.sender, to, value);
return ITransferReceiver(to).onTokenTransfer(msg.sender, value, data);
}
}
|
Interface of the ERC20 standard as defined in the EIP./
|
interface IERC20 {
function totalSupply() external view returns (uint256);
function decimals() external view returns (uint8);
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);
}
| 1,607,177 |
./partial_match/1/0x640f7B78830db57BAfDF6F462d2B458dA80825D3/sources/contracts/protocol/libraries/configuration/ReserveConfiguration.sol
|
Gets the liquidation threshold of the reserve self The reserve configuration return The liquidation threshold/
|
function getLiquidationThreshold(
DataTypes.ReserveConfigurationMap storage self
) internal view returns (uint256) {
return (self.data & ~LIQUIDATION_THRESHOLD_MASK) >> LIQUIDATION_THRESHOLD_START_BIT_POSITION;
}
| 15,492,490 |
./partial_match/1/0x085515c2eD7B498Df5E2d508Fe2F28733d2F137c/sources/MigrationTool.sol
|
IERC20Mintable Alchemix Finance
|
interface IERC20Mintable is IERC20 {
function mint(address recipient, uint256 amount) external;
}
}
| 9,135,036 |
./full_match/80001/0xf4f036a18961f7Ab421145bac1f27f0F73BFb643/sources/contracts/Company.sol
|
returns company address of the caller _sender (address) the address of the caller return if the caller is the company, then it returns the company address. If it is an user then it returns the address of the company of the user. Else 0x00 (address)/ if company address exists if user address exists take the companyaddress from the user
|
function returnCompanyAddressOrCompanyAddressFromUser(
address _sender
) public view returns (address) {
if (getCompanyAddress(_sender) != address(0x00)) {
return getCompanyAddress(_sender);
return getCompanyAddress(User.getUserCompanyAddress(_sender));
return address(0x00);
}
}
| 5,596,751 |
./full_match/1/0x7af62458e41E2F490D2Df54A8FeDc56fFedB8c17/sources/lib/solady/src/utils/SignatureCheckerLib.sol
|
@solidity memory-safe-assembly
|
function isValidERC1271SignatureNow(address signer, bytes32 hash, bytes32 r, bytes32 vs)
internal
view
returns (bool isValid)
assembly {
s := shr(1, shl(1, vs))
v := add(shr(255, vs), 27)
}
isValid = isValidERC1271SignatureNow(signer, hash, v, r, s);
| 3,202,623 |
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.4;
import "iron-swap/contracts/IronSwap.sol";
// import "iron-swap/contracts/IronSwapLib.sol";
// import "iron-swap/contracts/FeeDistributor.sol"; // you may choose to deploy it
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/proxy/utils/Initializable.sol";
import "../interfaces/IIronSwapInit.sol";
interface IFeeDistributor {
function initialize(address _target, address _swapRouter) external;
}
contract StableswapFactory is Ownable {
address public libAddress;
address public feeDistributor;
address public ironSwapRouter;
constructor(address _ironSwapRouter) {
setParams(_ironSwapRouter);
}
function setParams(address _ironSwapRouter) public onlyOwner {
ironSwapRouter = _ironSwapRouter;
}
/**
e.g.
[wellknown.addresses.usdc, wellknown.addresses.usdt, wellknown.addresses.dai], //_coins,
[6, 6, 18], //token decimals
'IRON Stableswap 3USD', // pool token name
'IS3USD', //_pool_token
800, // _A
1e6, //_fee 0.01%
5000000000, //_admin_fee 50%
5e7, // withdrawal fee 0.4%
feeDistributor.address
*/
function deployStableSwap(
address[] memory _coins,
uint8[] memory _decimals,
string memory lpTokenName,
string memory lpTokenSymbol,
uint256 _A,
uint256 _fee,
uint256 _adminFee,
uint256 _withdrawFee
) external returns (address res) {
res = address(new IronSwap());
// fd = deployFeeDistributor(_feeBaseToken);
IIronSwapInit(res).initialize(
_coins,
_decimals,
lpTokenName,
lpTokenSymbol,
_A,
_fee,
_adminFee,
_withdrawFee,
msg.sender // update to a fee distributor or payment splitter post deploy
);
Ownable(res).transferOwnership(msg.sender);
// Ownable(fd).transferOwnership(msg.sender);
}
}
|
/ fd = deployFeeDistributor(_feeBaseToken); Ownable(fd).transferOwnership(msg.sender);
|
function deployStableSwap(
address[] memory _coins,
uint8[] memory _decimals,
string memory lpTokenName,
string memory lpTokenSymbol,
uint256 _A,
uint256 _fee,
uint256 _adminFee,
uint256 _withdrawFee
) external returns (address res) {
res = address(new IronSwap());
IIronSwapInit(res).initialize(
_coins,
_decimals,
lpTokenName,
lpTokenSymbol,
_A,
_fee,
_adminFee,
_withdrawFee,
);
Ownable(res).transferOwnership(msg.sender);
}
| 2,561,314 |
/*
_____ _ _ _
| __ \ (_) | | |
| | | |_ ___| |_| |_ ___ _ __
| | | \ \ /\ / / | __| __/ _ \ '__|
| |__| |\ V V /| | |_| || __/ |
|_____/ \_/\_/ |_|\__|\__\___|_|
*/
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.0 <0.8.0;
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
return c;
}
}
/// @title A Decentralised Social Media Platform
/// @author Mohit Bhat
/// @notice You can use this contract to connect to decentralised social network, share your content to the world in a decentralised way!
/// @dev Most of the features are implemented keeping note of security concerns
contract Dwitter{
using SafeMath for uint;
address payable public owner; //Owner is also a maintainer
bool public stopped = false;
struct User{
uint id;
address ethAddress;
string username;
string name;
string profileImgHash;
string profileCoverImgHash;
string bio;
accountStatus status; // Account Banned or Not
}
struct Dweet{
uint dweetId;
address author;
string hashtag;
string content;
string imgHash;
uint timestamp;
uint likeCount;
uint reportCount;
cdStatus status; // Dweet Active-Deleted-Banned
}
struct Comment{
uint commentId;
address author;
uint dweetId;
string content;
uint likeCount;
// uint reportCount;
uint timestamp;
cdStatus status; // Comment Reported and Banned or not
}
uint public totalDweets=0;
uint public totalComments=0;
uint public totalUsers=0;
///@dev NP means not present the default value for status
enum accountStatus{NP,Active,Banned,Deactivated}
enum cdStatus{NP,Active, Banned, Deleted}//Comment-Dweet status
// enum dweetStatus{NP,Active, Banned, Deleted}
mapping(address=>User) private users; //mapping to get user details from user address
mapping(string=>address) private userAddressFromUsername;//to get user address from username
// mapping(address=>bool) private registeredUser; //mapping to get user details from user address
mapping(string=>bool) private usernames;//To check which username is taken taken=>true, not taken=>false
mapping(uint=>Dweet) private dweets;// mapping to get dweet from Id
mapping(address=>uint[]) private userDweets; // Array to store dweets(Id) done by user
// mapping(uint=>address[]) private dweetLikersList;
mapping(uint=>mapping(address=>bool)) private dweetLikers; // Mapping to track who liked which dweet
mapping(uint=>Comment) private comments; //Mapping to get comment from comment Id
mapping(address=>uint[]) private userComments;// Mapping to track user comments from there address
// mapping(uint=>mapping(address=>bool)) private commentReporters; // Mapping to track who reported which comment
// mapping(uint=>mapping(address=>bool)) private commentLikers; // Mapping to track who liked on which comment
mapping(uint=>uint[]) private dweetComments; // Getting comments for a specific dweet
modifier stopInEmergency { require(!stopped,"Dapp has been stopped!"); _; }
modifier onlyInEmergency { require(stopped); _; }
modifier onlyOwner{require(msg.sender==owner,"You are not owner!"); _;}
modifier onlyDweetAuthor(uint id){require(msg.sender==dweets[id].author,"You are not Author!"); _;}
modifier onlyCommentAuthor(uint id){require(msg.sender==comments[id].author,"You are not Author!"); _;}
modifier onlyAllowedUser(address user){require(users[user].status==accountStatus.Active,"Not a Registered User!"); _;}
modifier onlyActiveDweet(uint id){require(dweets[id].status==cdStatus.Active,"Not a active dweet"); _;}
modifier onlyActiveComment(uint id){require(comments[id].status==cdStatus.Active,"Not a active comment"); _;}
modifier usernameTaken(string memory username){require(!usernames[username],"Username already taken"); _;}
// modifier checkUserExists(){require(registeredUser[msg.sender]); _;}
modifier checkUserNotExists(address user){require(users[user].status==accountStatus.NP,"User already registered"); _;}
event logRegisterUser(address user, uint id);
event logUserBanned(address user, uint id);
event logDweetCreated(address author, uint userid, uint dweetid, string hashtag);
event logDweetDeleted(uint id, string hashtag);
// event logCommentBanned(uint id, string hashtag);
constructor() {
owner=msg.sender;
addMaintainer(msg.sender);
registerUser("owner","owner","","","owner");
}
fallback() external{
revert();
}
/*
**************************************USER FUNCTIONS********************************************************************************
*/
/// @notice Check username available or not
/// @param _username username to Check
/// @return status true or false
function usernameAvailable(string memory _username) public view returns(bool status){
return !usernames[_username];
}
/// @notice Register a new user
/// @param _username username of username
/// @param _name name of person
/// @param _imgHash Ipfs Hash of users Profile Image
/// @param _coverHash Ipfs Hash of user cover Image
/// @param _bio Biography of user
function registerUser(string memory _username, string memory _name, string memory _imgHash, string memory _coverHash, string memory _bio ) public stopInEmergency checkUserNotExists(msg.sender) usernameTaken(_username){
usernames[_username]=true;// Attack Prevented
totalUsers=totalUsers.add(1);
uint id=totalUsers;
users[msg.sender]=User(id, msg.sender, _username, _name, _imgHash, _coverHash, _bio, accountStatus.Active);
userAddressFromUsername[_username]=msg.sender;
emit logRegisterUser(msg.sender, totalUsers);
}
/// @notice Check accountStatus of user-Registered, Banned or Deleted
/// @return status NP, Active, Banned or Deleted
function userStatus() public view returns(accountStatus status){
return users[msg.sender].status;
}
/// @notice Change username of a user
/// @param _username New username of user
function changeUsername(string memory _username) public stopInEmergency onlyAllowedUser(msg.sender) usernameTaken(_username){
users[msg.sender].username=_username;
}
/// @notice Get user details
/// @return id Id of user
/// @return username username of person
/// @return name Name of user
/// @return imghash user profile image ipfs hash
/// @return coverhash usercCover image ipfs hash
/// @return bio Biography of user
function getUser() public view returns(uint id, string memory username, string memory name, string memory imghash, string memory coverhash, string memory bio){
return(users[msg.sender].id,users[msg.sender].username, users[msg.sender].name, users[msg.sender].profileImgHash, users[msg.sender].profileCoverImgHash, users[msg.sender].bio);
}
/// @notice Get user details
/// @param _user address of user
/// @return id Id of user
/// @return username username of person
/// @return name Name of user
/// @return imghash user profile image ipfs hash
/// @return coverhash usercCover image ipfs hash
/// @return bio Biography of user
function getUser(address _user) public view returns(uint id, string memory username, string memory name, string memory imghash, string memory coverhash, string memory bio){
return(users[_user].id,users[_user].username, users[_user].name, users[_user].profileImgHash, users[_user].profileCoverImgHash, users[_user].bio);
}
/// @notice Ban user Internal Function
/// @param _user address of user
function banUser(address _user) internal onlyAllowedUser(_user) onlyMaintainer {
delete users[_user];
users[_user].status=accountStatus.Banned;
emit logUserBanned(msg.sender, users[_user].id);
}
/*
**************************************DWEET FUNCTIONS***********************************************************
*/
/// @notice Create a new dweet
/// @param _hashtag hashtag of dweet ex. #ethereum
/// @param _content content of dweet to show
/// @param _imghash Image type content ipfs hash
function createDweet(string memory _hashtag, string memory _content, string memory _imghash) public stopInEmergency onlyAllowedUser(msg.sender) {
totalDweets=totalDweets.add(1);
uint id=totalDweets;
dweets[id]=Dweet(id, msg.sender, _hashtag, _content, _imghash, block.timestamp , 0, 0, cdStatus.Active);
userDweets[msg.sender].push(totalDweets);
emit logDweetCreated(msg.sender, users[msg.sender].id, totalDweets, _hashtag);
}
/// @notice Ban Dweet Internal Function
/// @param _id Id of dweet
function banDweet(uint _id) internal{
emit logDweetBanned(_id, dweets[_id].hashtag, maintainerId[msg.sender]);
delete dweets[_id];
dweets[_id].status=cdStatus.Banned;
for(uint i=0;i<dweetComments[_id].length;i++){
delete dweetComments[_id][i];
}
delete dweetComments[_id];
}
/// @notice Edit a dweet
/// @param _id Id of dweet
/// @param _hashtag New tag of dweet
/// @param _content New content of dweet
/// @param _imghash Hash of new image content
function editDweet(uint _id, string memory _hashtag, string memory _content, string memory _imghash) public stopInEmergency onlyActiveDweet(_id)
onlyAllowedUser(msg.sender) onlyDweetAuthor(_id) {
dweets[_id].hashtag=_hashtag;
dweets[_id].content=_content;
dweets[_id].imgHash=_imghash;
}
/// @notice Delete a dweet
/// @param _id Id of dweet
function deleteDweet(uint _id) public onlyActiveDweet(_id) onlyAllowedUser(msg.sender) stopInEmergency onlyDweetAuthor(_id){
emit logDweetDeleted(_id, dweets[_id].hashtag);
delete dweets[_id];
dweets[_id].status=cdStatus.Deleted;
for(uint i=0;i<dweetComments[_id].length;i++){
delete dweetComments[_id][i];
}
delete dweetComments[_id];
}
/// @notice Get a Dweet
/// @param _id Id of dweet
/// @return author Dweet author address
/// @return hashtag Tag of dweet
/// @return content Content of dweet
/// @return imgHash Hash of image content
/// @return timestamp Dweet creation timestamp
/// @return likeCount No of likes on dweet
function getDweet(uint _id) public onlyAllowedUser(msg.sender) onlyActiveDweet(_id) view returns ( address author, string memory hashtag, string memory content, string memory imgHash, uint timestamp, uint likeCount ){
return (dweets[_id].author, dweets[_id].hashtag, dweets[_id].content, dweets[_id].imgHash, dweets[_id].timestamp, dweets[_id].likeCount);
}
/// @notice Like a dweets
/// @param _id Id of dweet to be likeDweet
function likeDweet(uint _id) public onlyAllowedUser(msg.sender) onlyActiveDweet(_id){
require(!dweetLikers[_id][msg.sender]);
dweets[_id].likeCount=dweets[_id].likeCount.add(1);
dweetLikers[_id][msg.sender]=true;
}
/// @notice Get list of dweets done by a user
/// @return dweetList Array of dweet ids
function getUserDweets() public view onlyAllowedUser(msg.sender) returns(uint[] memory dweetList){
return userDweets[msg.sender];
}
/// @notice Get list of dweets done by a user
/// @param _user User address
/// @return dweetList Array of dweet ids
function getUserDweets(address _user) public view onlyAllowedUser(msg.sender) returns(uint[] memory dweetList){
return userDweets[_user];
}
/*
**************************************COMMENT FUNCTIONS*************************************************************************
*/
/// @notice Create a comment on dweet
/// @param _dweetid Id of dweetList
/// @param _comment content of comment
function createComment(uint _dweetid, string memory _comment) public stopInEmergency onlyAllowedUser(msg.sender) onlyActiveDweet(_dweetid){
totalComments=totalComments.add(1);
uint id=totalComments;
comments[id]=Comment(id, msg.sender, _dweetid, _comment, 0, block.timestamp, cdStatus.Active);
userComments[msg.sender].push(totalComments);
dweetComments[_dweetid].push(totalComments);
}
// function banComment(uint _id) internal {
// emit logCommentBanned(_id, dweets[comments[_id].dweetId].hashtag);
// delete comments[_id];
// comments[_id].status=cdStatus.Banned;
// }
/// @notice Get list of dweets done by a user
/// @param _commentid Id of comments
/// @param _comment New content of comment
function editComment(uint _commentid, string memory _comment) public stopInEmergency onlyAllowedUser(msg.sender) onlyActiveComment(_commentid) onlyCommentAuthor(_commentid){
comments[_commentid].content=_comment;
}
/// @notice Delete a comment
/// @param _id Id of comment to be Deleted
function deleteComment(uint _id) public stopInEmergency onlyActiveComment(_id) onlyAllowedUser(msg.sender) onlyCommentAuthor(_id) {
delete comments[_id];
comments[_id].status=cdStatus.Deleted;
}
/// @notice Get a comment
/// @param _id Id of comment
/// @return author Address of author
/// @return dweetId Id of dweet
/// @return content content of comment
/// @return likeCount Likes on commment
/// @return timestamp Comment creation timestamp
/// @return status status of Comment active-banned-deleted
function getComment(uint _id) public view onlyAllowedUser(msg.sender) onlyActiveComment(_id) returns(address author, uint dweetId, string memory content, uint likeCount, uint timestamp, cdStatus status){
return(comments[_id].author, comments[_id].dweetId, comments[_id].content, comments[_id].likeCount, comments[_id].timestamp, comments[_id].status);
}
/// @notice Get comments done by user
/// @return commentList Array of comment ids
/// @dev Though onlyAllowedUser can be bypassed easily but still keeping for calls from frontend
function getUserComments() public view onlyAllowedUser(msg.sender) returns(uint[] memory commentList){
return userComments[msg.sender];
}
/// @notice Get comments done by user
/// @param _user address of user
/// @return commentList Array of comment ids
function getUserComments(address _user) public view onlyAllowedUser(msg.sender) returns(uint[] memory commentList){
return userComments[_user];
}
/// @notice Get comments on a dweet
/// @return list Array of comment ids
function getDweetComments(uint _id) public view onlyAllowedUser(msg.sender) onlyActiveDweet(_id) returns(uint[] memory list){
return(dweetComments[_id]);
}
/*
**********************************Reporting And Maintanining*****************************************************************************************
*/
uint public totalMaintainers=0;
uint[] private dweetsReportedList;// List of ids of reported dweets
uint private noOfReportsRequired=1;// No of reports required to term a dweet reported and send for action
uint public reportingstakePrice=1936458778290500;// Stake amount to pay while reporting
uint public reportingRewardPrice=3872917556581000;// Reward of correct reporting
mapping(address=>bool) public isMaintainer;
mapping(address=>uint) private maintainerId;
mapping(uint=>mapping(address=>bool)) private dweetReporters; // Mapping to track who reported which dweet
mapping(uint=>reportAction) private actionOnDweet;// What is the ction on dweet done by maintainers
mapping(address=>uint[]) public userReportList;// Ids of dweets reported by a user
//mapping(address=>uint) private userRewards;
mapping(address=>uint) private fakeReportingReward;// Reward a user get when somebody do a fake reporting against that user
mapping(uint=>mapping(address=>userdweetReportingStatus)) private claimedReward;//To check whether user has claimed reward for a particular reporting
enum userdweetReportingStatus{NP, Reported, Claimed}
enum reportAction{NP, Banned, Free}
modifier onlyMaintainer(){
require(isMaintainer[msg.sender],"You are not a maintainer");
_;
}
modifier paidEnoughforReporter() { require(msg.value >= reportingstakePrice,"You have not paid enough for advertisement"); _;}
modifier checkValueforReporter() {
_;
uint amountToRefund = msg.value.sub(reportingstakePrice);
msg.sender.transfer(amountToRefund);
}
/// @notice Add a maintainer to the platform
/// @param _user Address of user to be added as maintainer
function addMaintainer(address _user) public onlyOwner {
isMaintainer[_user]=true;
totalMaintainers=totalMaintainers.add(1);
maintainerId[msg.sender]=totalMaintainers;
}
/// @notice Remove a maintainer
/// @param _user Address of user to be removed from maintainer
function revokeMaintainer(address _user) public onlyOwner{
isMaintainer[_user]=false;
}
event logDweetReported(uint id, string hashtag);
event logDweetBanned(uint id, string hashtag, uint maintainer); // To track how many dweets were banned to specific hashtag
event logDweetFreed(uint id, string hashtag, uint maintainer); // To track how many dweets were banned to specific hashtag
/// @notice Report a dweet
/// @param _dweetId Id of the dweet to be reported
function reportDweet(uint _dweetId) public payable onlyActiveDweet(_dweetId) onlyAllowedUser(msg.sender) paidEnoughforReporter checkValueforReporter{
require(dweets[_dweetId].reportCount<=noOfReportsRequired,"Dweet have got required no of Reports");
require(!dweetReporters[_dweetId][msg.sender],"You have already Reported!");
dweetReporters[_dweetId][msg.sender]=true;//Reentracy attack Prevented
userReportList[msg.sender].push(_dweetId);
claimedReward[_dweetId][msg.sender]=userdweetReportingStatus.Reported;
dweets[_dweetId].reportCount=dweets[_dweetId].reportCount.add(1);
uint reports= dweets[_dweetId].reportCount;
if(reports==noOfReportsRequired){
dweetsReportedList.push(_dweetId);
emit logDweetReported(_dweetId, dweets[_dweetId].hashtag);
}
}
/// @notice Take action on a reported dweets
/// @param _dweetId Id of dweets
/// @param _action ban or free, true or false
function takeAction(uint _dweetId, bool _action) public onlyMaintainer onlyActiveDweet(_dweetId) onlyAllowedUser(msg.sender){
require(actionOnDweet[_dweetId]==reportAction.NP,"Action already taken!");
if(_action){
actionOnDweet[_dweetId]=reportAction.Banned;
banDweet(_dweetId);
}else{
actionOnDweet[_dweetId]=reportAction.Free;
fakeReportingReward[dweets[_dweetId].author]=fakeReportingReward[dweets[_dweetId].author].add(reportingstakePrice.mul(noOfReportsRequired));
emit logDweetFreed(_dweetId, dweets[_dweetId].hashtag, maintainerId[msg.sender]);
}
}
/// @notice Claim right reporting reward
/// @param _id Id of dweet on which reward is to be claimed
function claimReportingReward(uint _id) public onlyAllowedUser(msg.sender){
require(claimedReward[_id][msg.sender]==userdweetReportingStatus.Reported,"You have not reported or already claimed");
require(userReportList[msg.sender].length>0);
require(actionOnDweet[_id]==reportAction.Banned,"Not eligible for reward, Dweet has been freed my mainatiners");
claimedReward[_id][msg.sender]=userdweetReportingStatus.Claimed;//Reentracy Prevented
msg.sender.transfer(reportingRewardPrice);
}
/// @notice Claim fake reporting reward(suit)
function claimSuitReward()public onlyAllowedUser(msg.sender){
require(fakeReportingReward[msg.sender]>0,"Not enough balance");
uint amount=fakeReportingReward[msg.sender];
fakeReportingReward[msg.sender]=0;//Attack Prevented
msg.sender.transfer(amount);
}
/// @notice To get list of reportings done by a user
/// @param list Array of dweet Ids reported by user
function myReportings() public view onlyAllowedUser(msg.sender) returns(uint[] memory list){
return userReportList[msg.sender];
}
// function myReportingReward() public view onlyAllowedUser(msg.sender) returns(uint balance){
// return userRewards[msg.sender];
// }
/// @notice To get claim status of reporting
/// @param _id Id of dweetsReportedList
/// @return status status of claim reported or claimed
function reportingClaimStatus(uint _id) public view onlyAllowedUser(msg.sender) returns(userdweetReportingStatus status){
return claimedReward[_id][msg.sender];
}
/// @notice To get fake reporting reward balance
/// @return balance reward balance of user
function fakeReportingSuitReward() public view onlyAllowedUser(msg.sender) returns(uint balance){
return fakeReportingReward[msg.sender];
}
/// @notice To get list of reported dweets on the platform
/// @return list Array of reported dweet ids
function getReportedDweets() public view onlyAllowedUser(msg.sender) returns(uint[] memory list){
return(dweetsReportedList);
}
/// @notice Get action status of reporting on a dweet
/// @param _dweetId Id of dweet
/// @return status status of action NP-BAN_FREE
function getReportedDweetStatus(uint _dweetId) public view onlyAllowedUser(msg.sender) returns(reportAction status){
return(actionOnDweet[_dweetId]);
}
/*
*******************************************Advertisement **************************************************************
*/
uint public advertisementCost=96822938914524992;
uint public totalAdvertisements=0;
uint[] private advertisementsList;
enum AdApprovalStatus{NP, Approved, Rejected}
struct Advertisement{
uint id;
address advertiser;
string imgHash;
string link;
AdApprovalStatus status;// Advertisement Approve or Rejected
uint expiry; //timestamp to put expiry of Advertisement
}
modifier paidEnoughforAdvertisement() { require(msg.value >= advertisementCost); _;}
modifier checkValueforAdvertisement() {
_;
uint amountToRefund = msg.value - advertisementCost;
msg.sender.transfer(amountToRefund);
}
mapping(address=>uint[]) public advertiserAdvertisementsList;
mapping(uint=>Advertisement) private advertisements;
event logAdvertisementApproved(uint id, uint maintainer);
event logAdvertisementRejected(uint id, uint maintainer);
/// @notice Submit a new advertisement
/// @param _imgHash Ipfs hash of image to be shown as advertisement
/// @param _link Href link for the advertisement
function submitAdvertisement(string memory _imgHash, string memory _link) public payable onlyAllowedUser(msg.sender) paidEnoughforAdvertisement checkValueforAdvertisement{
totalAdvertisements=totalAdvertisements.add(1);
uint id=totalAdvertisements;
advertisements[id]=Advertisement(id, msg.sender, _imgHash, _link, AdApprovalStatus.NP, 0);
advertisementsList.push(id);
advertiserAdvertisementsList[msg.sender].push(id);
}
/// @notice Approve or reject advertisements
/// @param _id Id of advertisement
/// @param _decision Approval decision Accepted or Rejected, true or false
function advertisementApproval(uint _id, bool _decision) public onlyMaintainer{
require(advertisements[_id].status==AdApprovalStatus.NP,"Approval already given!");
if(_decision){
advertisements[_id].status=AdApprovalStatus.Approved;
advertisements[_id].expiry=block.timestamp.add(1 days);
emit logAdvertisementApproved(_id,maintainerId[msg.sender]);
}else{
advertisements[_id].status=AdApprovalStatus.Rejected;
uint refund=advertisementCost.mul(8).div(100);
msg.sender.transfer(refund);
emit logAdvertisementRejected(_id,maintainerId[msg.sender]);
}
}
/// @notice Get all ads submitted on platform
/// @return list Array of advertisement ids
function getAds() public view onlyAllowedUser(msg.sender) returns(uint[] memory list){
return(advertisementsList);
}
/// @notice Get details of a advertisement
/// @param _id Id of advertisement
/// @return advertiser address of advertiser
/// @return imgHash Ipfs hash of advertisement image
/// @return link Href link of advertisement
/// @return status Approval status of advertisements
/// @return expiry advertisement expiry timestamp
function getAd(uint _id) public view onlyAllowedUser(msg.sender) returns(address advertiser, string memory imgHash, string memory link, AdApprovalStatus status, uint expiry){
return(advertisements[_id].advertiser, advertisements[_id].imgHash, advertisements[_id].link, advertisements[_id].status, advertisements[_id].expiry);
}
/// @notice Get advertisement done by user
/// @return list Array of advertisement ids
function myAdvertisements() public view onlyAllowedUser(msg.sender) returns(uint[] memory list){
return(advertiserAdvertisementsList[msg.sender]);
}
/// @notice Status of a advertisement
/// @param _id Id of advertisement
/// @return status Approval status accepted or rejected
function getAdvertisementStatus(uint _id) public view onlyAllowedUser(msg.sender) returns(AdApprovalStatus status){
return advertisements[_id].status;
}
/*
****************************************Owner Admin ******************************************************************************************
*/
/// @notice Get balance of contract
/// @return balance balance of contract
function getBalance()public view onlyOwner() returns(uint balance){
return address(this).balance;
}
/// @notice Withdraw contract funds to owner
/// @param _amount Amount to be withdrawn
function transferContractBalance(uint _amount)public onlyOwner{
require(_amount<=address(this).balance,"Withdraw amount greater than balance");
msg.sender.transfer(_amount);
}
function stopDapp() public onlyOwner{
require(!stopped,"Already stopped");
stopped=true;
}
function startDapp() public onlyOwner{
require(stopped,"Already started");
stopped=false;
}
function changeOwner(address payable _newOwner) public onlyOwner{
owner=_newOwner;
}
}
|
Get comments on a dweet return list Array of comment ids
|
function getDweetComments(uint _id) public view onlyAllowedUser(msg.sender) onlyActiveDweet(_id) returns(uint[] memory list){
return(dweetComments[_id]);
}
mapping(address=>bool) public isMaintainer;
mapping(address=>uint) private maintainerId;
| 7,226,651 |
./full_match/3/0x17f68701C496De8B3671aAEC542170460Bf4D37C/sources/Quoter.sol
|
the inputs of prior swaps become the outputs of subsequent ones decide whether to continue or terminate
|
function quoteExactOutputSingle(
address quoteAddress,
address tokenIn,
address tokenOut,
uint24 fee,
uint256 amountOut,
uint160 sqrtPriceLimitX96
}
}
while (true) {
bool hasMultiplePools = path.hasMultiplePools();
(address tokenOut, address tokenIn, uint24 fee) = path.decodeFirstPool();
amountOut = quoteExactOutputSingle(quoteAddress,tokenIn, tokenOut, fee, amountOut, 0);
if (hasMultiplePools) {
path = path.skipToken();
return amountOut;
}
}
| 8,275,100 |
// File: contracts/vaults/IStrategy.sol
/*
A strategy must implement the following functions:
- getName(): Name of strategy
- want(): Desired token for investment. Should be same as underlying vault token (Eg. USDC)
- deposit function that will calls controller.earn()
- withdraw(address): For miscellaneous tokens, must exclude any tokens used in the yield
- Should return to Controller
- withdraw(uint): Controller | Vault role - withdraw should always return to vault
- withdrawAll(): Controller | Vault role - withdraw should always return to vault
- balanceOf(): Should return underlying vault token amount
*/
pragma solidity 0.5.17;
interface IStrategy {
function getName() external pure returns (string memory);
function want() external view returns (address);
function withdraw(address) external;
function withdraw(uint256) external;
function withdrawAll() external returns (uint256);
function balanceOf() external view returns (uint256);
}
// File: contracts/IERC20.sol
//SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.5.17;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: contracts/ITreasury.sol
pragma solidity 0.5.17;
interface ITreasury {
function defaultToken() external view returns (IERC20);
function deposit(IERC20 token, uint256 amount) external;
function withdraw(uint256 amount, address withdrawAddress) external;
}
// File: contracts/vaults/IVault.sol
pragma solidity 0.5.17;
interface IVault {
function want() external view returns (IERC20);
function transferFundsToStrategy(address strategy, uint256 amount) external;
function availableFunds() external view returns (uint256);
}
// File: contracts/vaults/IVaultRewards.sol
pragma solidity 0.5.17;
interface IVaultRewards {
function want() external view returns (IERC20);
function notifyRewardAmount(uint256 reward) external;
}
// File: contracts/vaults/IController.sol
pragma solidity 0.5.17;
interface IController {
function currentEpochTime() external view returns (uint256);
function balanceOf(address) external view returns (uint256);
function rewards(address token) external view returns (IVaultRewards);
function vault(address token) external view returns (IVault);
function allowableAmount(address) external view returns (uint256);
function treasury() external view returns (ITreasury);
function approvedStrategies(address, address) external view returns (bool);
function getHarvestInfo(address strategy, address user)
external view returns (
uint256 vaultRewardPercentage,
uint256 hurdleAmount,
uint256 harvestPercentage
);
function withdraw(address, uint256) external;
function earn(address, uint256) external;
function increaseHurdleRate(address token) external;
}
// File: contracts/SafeMath.sol
pragma solidity 0.5.17;
// Note: This file has been modified to include the sqrt function for quadratic voting
/**
* @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);
}
/**
* Imported from: https://github.com/alianse777/solidity-standard-library/blob/master/Math.sol
* @dev Compute square root of x
* @return sqrt(x)
*/
function sqrt(uint256 x) internal pure returns (uint256) {
uint256 n = x / 2;
uint256 lstX = 0;
while (n != lstX){
lstX = n;
n = (n + x/n) / 2;
}
return uint256(n);
}
}
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: contracts/zeppelin/Address.sol
pragma solidity 0.5.17;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* This test is non-exhaustive, and there may be false-negatives: during the
* execution of a contract's constructor, its address will be reported as
* not containing a contract.
*
* IMPORTANT: It is unsafe to assume that an address for which this
* function returns false is an externally-owned account (EOA) and not a
* contract.
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
// File: contracts/zeppelin/SafeERC20.sol
pragma solidity 0.5.17;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: contracts/vaults/strategy/MStableStrategy.sol
//SPDX-License-Identifier: MIT
/*
* MIT License
* ===========
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
*/
pragma solidity 0.5.17;
interface IBalProxy {
function smartSwapExactIn(
IERC20 tokenIn,
IERC20 tokenOut,
uint totalAmountIn,
uint minTotalAmountOut,
uint nPools
)
external payable
returns (uint totalAmountOut);
}
interface IBPT {
function totalSupply() external view returns (uint256);
function balanceOf(address whom) external view returns (uint);
function getSpotPrice(address tokenIn, address tokenOut) external view returns (uint spotPrice);
function swapExactAmountIn(address, uint, address, uint, uint) external returns (uint, uint);
function swapExactAmountOut(address, uint, address, uint, uint) external returns (uint, uint);
function joinswapExternAmountIn(
address tokenIn,
uint tokenAmountIn,
uint minPoolAmountOut
) external returns (uint poolAmountOut);
function exitswapExternAmountOut(
address tokenOut,
uint tokenAmountOut,
uint maxPoolAmountIn
) external returns (uint poolAmountIn);
function exitswapPoolAmountIn(
address tokenOut,
uint poolAmountIn,
uint minAmountOut
) external returns (uint tokenAmountOut);
}
interface IMPool {
function balanceOf(address _account) external view returns (uint256);
function earned(address _account) external view returns (uint256, uint256);
function stake(uint256 _amount) external;
function claimReward() external;
function exit() external;
}
interface IMTAGov {
function balanceOf(address _account) external view returns (uint256);
function earned(address _account) external view returns (uint256);
function createLock(uint256 _value, uint256 _unlockTime) external;
function withdraw() external;
function increaseLockAmount(uint256 _value) external;
function claimReward() external;
}
contract MStableStrat is IStrategy {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
uint256 public constant PERFORMANCE_FEE = 500; // 5%
uint256 public constant DENOM = 10000;
uint256 public hurdleLastUpdateTime;
uint256 public harvestAmountThisEpoch;
uint256 public strategistCollectedFee;
uint256 public numPools = 1;
IERC20 internal usdc = IERC20(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48);
IERC20 internal musd = IERC20(0xe2f2a5C287993345a840Db3B0845fbC70f5935a5);
IERC20 internal mta = IERC20(0xa3BeD4E1c75D00fa6f4E5E6922DB7261B5E9AcD2);
IBPT internal musdcBpt = IBPT(0x72Cd8f4504941Bf8c5a21d1Fd83A96499FD71d2C);
IBalProxy internal balProxy = IBalProxy(0x3E66B66Fd1d0b02fDa6C811Da9E0547970DB2f21);
IMPool internal mPool = IMPool(0x881c72D1e6317f10a1cDCBe05040E7564E790C80);
IMTAGov internal mtaGov = IMTAGov(0xaE8bC96DA4F9A9613c323478BE181FDb2Aa0E1BF);
IERC20 public want = usdc; // should be set only in constructor or hardcoded
IController public controller; // should be set only in constructor
address public strategist; // mutable, but only by strategist
// want must be equal to an underlying vault token (Eg. USDC)
constructor(IController _controller) public {
controller = _controller;
strategist = msg.sender;
}
function getName() external pure returns (string memory) {
return "MstableStrategy";
}
function setStrategist(address _strategist) external {
require(msg.sender == strategist, "!strategist");
strategist = _strategist;
}
function setNumPoolsForSwap(uint256 _numPools) external {
require(msg.sender == strategist, "!strategist");
numPools = _numPools;
}
function setAllowances(IERC20 token, address[] calldata recipients, bool isIncrease) external {
require(msg.sender == strategist, "!strategist");
for (uint i = 0; i < recipients.length; i++) {
require(
recipients[i] == address(musdcBpt) ||
recipients[i] == address(balProxy) ||
recipients[i] == address(mPool) ||
recipients[i] == address(mtaGov),
"bad recipient"
);
uint256 allowance = isIncrease ? uint256(-1) : 0;
token.safeApprove(recipients[i], allowance);
}
}
// Assumed that caller checks against available funds in vault
function deposit(uint256 amount) public {
uint256 availFunds = controller.allowableAmount(address(this));
require(amount <= availFunds, "exceed contAllowance");
controller.earn(address(this), amount);
// deposit into musdcBpt
uint256 bptTokenAmt = musdcBpt.joinswapExternAmountIn(address(want), amount, 0);
// deposit into mstable pool
mPool.stake(bptTokenAmt);
// deposit any MTA token in this contract into mStaking contract
depositMTAInStaking();
}
function balanceOf() external view returns (uint256) {
// get balance in mPool
uint256 bptStakeAmt = mPool.balanceOf(address(this));
// get usdc + musd amts in BPT, and total BPT
uint256 usdcAmt = usdc.balanceOf(address(musdcBpt));
uint256 musdAmt = musd.balanceOf(address(musdcBpt));
uint256 totalBptAmt = musdcBpt.totalSupply();
// convert musd to usdc
usdcAmt = usdcAmt.add(
// 1e12 = 1e18 / 1e6 (usdc has 6 decimals)
musdAmt.mul(1e12).div(musdcBpt.getSpotPrice(address(musd), address(usdc)))
);
return bptStakeAmt.mul(usdcAmt).div(totalBptAmt);
}
function earned() external view returns (uint256) {
(uint256 earnedAmt,) = mPool.earned(address(this));
return earnedAmt.add(mtaGov.earned(address(this)));
}
function withdraw(address token) external {
IERC20 erc20Token = IERC20(token);
require(msg.sender == address(controller), "!controller");
require(erc20Token != want, "want");
require(erc20Token != musd, "musd");
require(erc20Token != mta, "mta");
require(token != address(musdcBpt), "bpt");
erc20Token.safeTransfer(address(controller), erc20Token.balanceOf(address(this)));
}
function withdraw(uint256 amount) external {
require(msg.sender == address(controller), "!controller");
// exit fully
mPool.exit();
// convert to desired amount
musdcBpt.exitswapExternAmountOut(address(want), amount, uint256(-1));
// deposit whatever remaining bpt back into mPool
mPool.stake(musdcBpt.balanceOf(address(this)));
// send funds to vault
want.safeTransfer(address(controller.vault(address(want))), amount);
}
function withdrawAll() external returns (uint256 balance) {
require(msg.sender == address(controller), "!controller");
// exit fully
mPool.exit();
// convert reward to want tokens
exchangeRewardForWant(true);
// convert bpt to want tokens
musdcBpt.exitswapPoolAmountIn(
address(want),
musdcBpt.balanceOf(address(this)),
0
);
// exclude collected strategist fee
balance = want.balanceOf(address(this)).sub(strategistCollectedFee);
// send funds to vault
want.safeTransfer(address(controller.vault(address(want))), balance);
}
function harvest() external {
(uint256 amount,) = mPool.earned(address(this));
// collect farmed tokens
if (amount > 0) {
mPool.claimReward();
}
if (mtaGov.earned(address(this)) > 0) {
mtaGov.claimReward();
}
// convert 80% reward to want tokens
exchangeRewardForWant(false);
amount = want.balanceOf(address(this)).sub(strategistCollectedFee);
uint256 vaultRewardPercentage;
uint256 hurdleAmount;
uint256 harvestPercentage;
uint256 epochTime;
(vaultRewardPercentage, hurdleAmount, harvestPercentage) =
controller.getHarvestInfo(address(this), msg.sender);
// check if harvest amount has to be reset
if (hurdleLastUpdateTime < epochTime) {
// reset collected amount
harvestAmountThisEpoch = 0;
}
// update variables
hurdleLastUpdateTime = block.timestamp;
harvestAmountThisEpoch = harvestAmountThisEpoch.add(amount);
// first, take harvester fee
uint256 harvestFee = amount.mul(harvestPercentage).div(DENOM);
want.safeTransfer(msg.sender, harvestFee);
uint256 fee;
// then, if hurdle amount has been exceeded, take performance fee
if (harvestAmountThisEpoch >= hurdleAmount) {
fee = amount.mul(PERFORMANCE_FEE).div(DENOM);
strategistCollectedFee = strategistCollectedFee.add(fee);
}
// do the subtraction of harvester and strategist fees
amount = amount.sub(harvestFee).sub(fee);
// finally, calculate how much is to be re-invested
// fee = vault reward amount, reusing variable
fee = amount.mul(vaultRewardPercentage).div(DENOM);
want.safeTransfer(address(controller.rewards(address(want))), fee);
controller.rewards(address(want)).notifyRewardAmount(fee);
amount = amount.sub(fee);
// finally, use remaining want amount for reinvestment
amount = musdcBpt.joinswapExternAmountIn(address(want), amount, 0);
// deposit into mstable pool
mPool.stake(amount);
// deposit any MTA token in this contract into mStaking contract
depositMTAInStaking();
}
function withdrawStrategistFee() external {
strategistCollectedFee = 0;
want.safeTransfer(strategist, strategistCollectedFee);
}
function depositMTAInStaking() internal {
uint256 mtaBal = mta.balanceOf(address(this));
if (mtaBal == 0) return;
if (mtaGov.balanceOf(address(this)) == 0) {
// create lock with max time
mtaGov.createLock(mtaBal, 1632580257);
} else {
// increase amount
mtaGov.increaseLockAmount(mtaBal);
}
}
function exchangeRewardForWant(bool exchangeAll) internal returns (uint256) {
uint256 mtaToSwap = mta.balanceOf(address(this));
balProxy.smartSwapExactIn(
mta,
want,
exchangeAll ? mtaToSwap : mtaToSwap.mul(8000).div(DENOM),
0,
numPools
);
}
}
|
get balance in mPool get usdc + musd amts in BPT, and total BPT convert musd to usdc 1e12 = 1e18 / 1e6 (usdc has 6 decimals)
|
function balanceOf() external view returns (uint256) {
uint256 bptStakeAmt = mPool.balanceOf(address(this));
uint256 usdcAmt = usdc.balanceOf(address(musdcBpt));
uint256 musdAmt = musd.balanceOf(address(musdcBpt));
uint256 totalBptAmt = musdcBpt.totalSupply();
usdcAmt = usdcAmt.add(
musdAmt.mul(1e12).div(musdcBpt.getSpotPrice(address(musd), address(usdc)))
);
return bptStakeAmt.mul(usdcAmt).div(totalBptAmt);
}
| 10,230,158 |
./full_match/1/0x324D4D87a4a27C58Af3e08e6624Bc8700c545602/sources/Hotdog.sol
|
Finalize starting index/ Just a sanity case in the worst case if this function is called late (EVM only stores last 256 block hashes). Prevent default sequence because that would be a bit boring.
|
function finalizeStartingIndex() public {
require(startingIndex == 0, "Starting index is already set");
require(startingIndexBlock != 0, "Starting index block must be set");
startingIndex = uint(blockhash(startingIndexBlock)) % MAX_HOTDOG_SUPPLY;
if (SafeMath.sub(block.number, startingIndexBlock) > 255) {
startingIndex = uint(blockhash(block.number-1)) % MAX_HOTDOG_SUPPLY;
}
if (startingIndex == 0) {
startingIndex = SafeMath.add(startingIndex, 1);
}
}
| 17,198,778 |
./partial_match/1/0x21fC96B8C0d429820bcD03872083Bf8B1A0970eb/sources/TokenSale.sol
|
Low-level token purchase with USDT This function has a non-reentrancy guard, so it shouldn't be called by another `nonReentrant` function. amount The amount of USDT tokens to buy return The total tokens bought/
|
function buyWithUSDT(uint256 amount) public nonReentrant returns (uint256) {
require(amount > 0, "USDT: invalid buy amount");
require(beneficiaryAddress != address(0), "Beneficiary address not set");
IERC20 usdtToken = IERC20(usdtTokenAddress);
require(usdtToken.transferFrom(msg.sender, address(beneficiaryAddress), amount), "USDT transfer failed");
uint256 tokens = _buyTokens(amount);
totalRaisedUSDT += amount;
return tokens;
}
| 9,408,737 |
// SPDX-License-Identifier: MIT
// @unsupported: ovm
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_NVMCodec } from "../../libraries/codec/Lib_NVMCodec.sol";
import { Lib_AddressResolver } from "../../libraries/resolver/Lib_AddressResolver.sol";
import { Lib_MerkleTree } from "../../libraries/utils/Lib_MerkleTree.sol";
/* Interface Imports */
import { iNVM_MessageQueue } from "../../iNVM/chain/iNVM_MessageQueue.sol";
import { iNVM_ChainStorageContainer } from "../../iNVM/chain/iNVM_ChainStorageContainer.sol";
/* Contract Imports */
import { NVM_ExecutionManager } from "../execution/NVM_ExecutionManager.sol";
/* External Imports */
import { Math } from "@openzeppelin/contracts/math/Math.sol";
/**
* @title NVM_MessageQueue
* @dev TODO
*
* Compiler used: solc
* Runtime target: EVM
*/
contract NVM_MessageQueue is iNVM_MessageQueue, Lib_AddressResolver {
/*************
* Constants *
*************/
// L2 tx gas-related
uint256 constant public MIN_ROLLUP_TX_GAS = 100000;
uint256 constant public MAX_ROLLUP_TX_SIZE = 50000;
uint256 constant public L2_GAS_DISCOUNT_DIVISOR = 32;
/*************
* Variables *
*************/
uint256 public forceInclusionPeriodSeconds;
uint256 public forceInclusionPeriodBlocks;
uint256 public maxTransactionGasLimit;
/***************
* Constructor *
***************/
constructor(
address _libAddressManager,
uint256 _maxTransactionGasLimit
)
Lib_AddressResolver(_libAddressManager)
{
maxTransactionGasLimit = _maxTransactionGasLimit;
}
/********************
* Public Functions *
********************/
/**
* Accesses the queue storage container.
* @return Reference to the queue storage container.
*/
function queue()
override
public
view
returns (
iNVM_ChainStorageContainer
)
{
return iNVM_ChainStorageContainer(
resolve("NVM_ChainStorageContainer-message-queue")
);
}
/**
* Gets the queue element at a particular index.
* @param _index Index of the queue element to access.
* @return _element Queue element at the given index.
*/
function getQueueElement(
uint256 _index
)
override
public
view
returns (
Lib_NVMCodec.QueueElement memory _element
)
{
return _getQueueElement(
_index,
queue()
);
}
/**
* Retrieves the length of the queue, including
* both pending and canonical transactions.
* @return Length of the queue.
*/
function getQueueLength()
override
public
view
returns (
uint40
)
{
return _getQueueLength(
queue()
);
}
/**
* Adds a transaction to the queue.
* @param _target Target L2 contract to send the transaction to.
* @param _gasLimit Gas limit for the enqueued L2 transaction.
* @param _data Transaction data.
*/
function enqueue(
address _target,
uint256 _gasLimit,
bytes memory _data
)
override
public
{
require(
_data.length <= MAX_ROLLUP_TX_SIZE,
"Transaction data size exceeds maximum for rollup transaction."
);
require(
_gasLimit <= maxTransactionGasLimit,
"Transaction gas limit exceeds maximum for rollup transaction."
);
require(
_gasLimit >= MIN_ROLLUP_TX_GAS,
"Transaction gas limit too low to enqueue."
);
// We need to consume some amount of L1 gas in order to rate limit transactions going into
// L2. However, L2 is cheaper than L1 so we only need to burn some small proportion of the
// provided L1 gas.
uint256 gasToConsume = _gasLimit/L2_GAS_DISCOUNT_DIVISOR;
uint256 startingGas = gasleft();
// Although this check is not necessary (burn below will run out of gas if not true), it
// gives the user an explicit reason as to why the enqueue attempt failed.
require(
startingGas > gasToConsume,
"Insufficient gas for L2 rate limiting burn."
);
// Here we do some "dumb" work in order to burn gas, although we should probably replace
// this with something like minting gas token later on.
uint256 i;
while(startingGas - gasleft() < gasToConsume) {
i++;
}
bytes32 transactionHash = keccak256(
abi.encode(
msg.sender,
_target,
_gasLimit,
_data
)
);
bytes32 timestampAndBlockNumber;
assembly {
timestampAndBlockNumber := timestamp()
timestampAndBlockNumber := or(timestampAndBlockNumber, shl(40, number()))
}
iNVM_ChainStorageContainer queueRef = queue();
queueRef.push(transactionHash);
queueRef.push(timestampAndBlockNumber);
// The underlying queue data structure stores 2 elements
// per insertion, so to get the real queue length we need
// to divide by 2 and subtract 1.
uint256 queueIndex = queueRef.length() / 2 - 1;
emit TransactionEnqueued(
msg.sender,
_target,
_gasLimit,
_data,
queueIndex,
block.timestamp
);
}
/**********************
* Internal Functions *
**********************/
/**
* Gets the queue element at a particular index.
* @param _index Index of the queue element to access.
* @return _element Queue element at the given index.
*/
function _getQueueElement(
uint256 _index,
iNVM_ChainStorageContainer _queueRef
)
internal
view
returns (
Lib_NVMCodec.QueueElement memory _element
)
{
// The underlying queue data structure stores 2 elements
// per insertion, so to get the actual desired queue index
// we need to multiply by 2.
uint40 trueIndex = uint40(_index * 2);
bytes32 transactionHash = _queueRef.get(trueIndex);
bytes32 timestampAndBlockNumber = _queueRef.get(trueIndex + 1);
uint40 elementTimestamp;
uint40 elementBlockNumber;
// solhint-disable max-line-length
assembly {
elementTimestamp := and(timestampAndBlockNumber, 0x000000000000000000000000000000000000000000000000000000FFFFFFFFFF)
elementBlockNumber := shr(40, and(timestampAndBlockNumber, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000000000))
}
// solhint-enable max-line-length
return Lib_NVMCodec.QueueElement({
transactionHash: transactionHash,
timestamp: elementTimestamp,
blockNumber: elementBlockNumber
});
}
/**
* Retrieves the length of the queue.
* @return Length of the queue.
*/
function _getQueueLength(
iNVM_ChainStorageContainer _queueRef
)
internal
view
returns (
uint40
)
{
// The underlying queue data structure stores 2 elements
// per insertion, so to get the real queue length we need
// to divide by 2.
return uint40(_queueRef.length() / 2);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_RLPReader } from "../rlp/Lib_RLPReader.sol";
import { Lib_RLPWriter } from "../rlp/Lib_RLPWriter.sol";
import { Lib_BytesUtils } from "../utils/Lib_BytesUtils.sol";
import { Lib_Bytes32Utils } from "../utils/Lib_Bytes32Utils.sol";
/**
* @title Lib_NVMCodec
*/
library Lib_NVMCodec {
/*********
* Enums *
*********/
enum QueueOrigin {
SEQUENCER_QUEUE,
L1TOL2_QUEUE
}
/***********
* Structs *
***********/
struct Account {
uint256 nonce;
uint256 balance;
bytes32 storageRoot;
bytes32 codeHash;
address ethAddress;
bool isFresh;
}
struct EVMAccount {
uint256 nonce;
uint256 balance;
bytes32 storageRoot;
bytes32 codeHash;
}
struct ChainBatchHeader {
uint256 batchIndex;
bytes32 batchRoot;
uint256 batchSize;
uint256 prevTotalElements;
bytes extraData;
}
struct ChainInclusionProof {
uint256 index;
bytes32[] siblings;
}
struct Transaction {
uint256 timestamp;
uint256 blockNumber;
QueueOrigin l1QueueOrigin;
address l1TxOrigin;
address entrypoint;
uint256 gasLimit;
bytes data;
}
struct Receipt {
uint256 index;
bytes32 stateRoot;
bytes32 nvmTransactionHash;
bytes operatorSignature;
}
struct TransactionChainElement {
bool isSequenced;
uint256 queueIndex; // QUEUED TX ONLY
uint256 timestamp; // SEQUENCER TX ONLY
uint256 blockNumber; // SEQUENCER TX ONLY
bytes txData; // SEQUENCER TX ONLY
}
struct QueueElement {
bytes32 transactionHash;
uint40 timestamp;
uint40 blockNumber;
}
/**********************
* Internal Functions *
**********************/
/**
* Encodes a standard OVM transaction.
* @param _transaction OVM transaction to encode.
* @return Encoded transaction bytes.
*/
function encodeTransaction(
Transaction memory _transaction
)
internal
pure
returns (
bytes memory
)
{
return abi.encodePacked(
_transaction.timestamp,
_transaction.blockNumber,
_transaction.l1QueueOrigin,
_transaction.l1TxOrigin,
_transaction.entrypoint,
_transaction.gasLimit,
_transaction.data
);
}
/**
* Hashes a standard OVM transaction.
* @param _transaction OVM transaction to encode.
* @return Hashed transaction
*/
function hashTransaction(
Transaction memory _transaction
)
internal
pure
returns (
bytes32
)
{
return keccak256(encodeTransaction(_transaction));
}
/**
* Converts an OVM account to an EVM account.
* @param _in OVM account to convert.
* @return Converted EVM account.
*/
function toEVMAccount(
Account memory _in
)
internal
pure
returns (
EVMAccount memory
)
{
return EVMAccount({
nonce: _in.nonce,
balance: _in.balance,
storageRoot: _in.storageRoot,
codeHash: _in.codeHash
});
}
/**
* @notice RLP-encodes an account state struct.
* @param _account Account state struct.
* @return RLP-encoded account state.
*/
function encodeEVMAccount(
EVMAccount memory _account
)
internal
pure
returns (
bytes memory
)
{
bytes[] memory raw = new bytes[](4);
// Unfortunately we can't create this array outright because
// Lib_RLPWriter.writeList will reject fixed-size arrays. Assigning
// index-by-index circumvents this issue.
raw[0] = Lib_RLPWriter.writeBytes(
Lib_Bytes32Utils.removeLeadingZeros(
bytes32(_account.nonce)
)
);
raw[1] = Lib_RLPWriter.writeBytes(
Lib_Bytes32Utils.removeLeadingZeros(
bytes32(_account.balance)
)
);
raw[2] = Lib_RLPWriter.writeBytes(abi.encodePacked(_account.storageRoot));
raw[3] = Lib_RLPWriter.writeBytes(abi.encodePacked(_account.codeHash));
return Lib_RLPWriter.writeList(raw);
}
/**
* @notice Decodes an RLP-encoded account state into a useful struct.
* @param _encoded RLP-encoded account state.
* @return Account state struct.
*/
function decodeEVMAccount(
bytes memory _encoded
)
internal
pure
returns (
EVMAccount memory
)
{
Lib_RLPReader.RLPItem[] memory accountState = Lib_RLPReader.readList(_encoded);
return EVMAccount({
nonce: Lib_RLPReader.readUint256(accountState[0]),
balance: Lib_RLPReader.readUint256(accountState[1]),
storageRoot: Lib_RLPReader.readBytes32(accountState[2]),
codeHash: Lib_RLPReader.readBytes32(accountState[3])
});
}
/**
* Calculates a hash for a given batch header.
* @param _batchHeader Header to hash.
* @return Hash of the header.
*/
function hashBatchHeader(
Lib_NVMCodec.ChainBatchHeader memory _batchHeader
)
internal
pure
returns (
bytes32
)
{
return keccak256(
abi.encode(
_batchHeader.batchRoot,
_batchHeader.batchSize,
_batchHeader.prevTotalElements,
_batchHeader.extraData
)
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/* Library Imports */
import { Lib_AddressManager } from "./Lib_AddressManager.sol";
/**
* @title Lib_AddressResolver
*/
abstract contract Lib_AddressResolver {
/*************
* Variables *
*************/
Lib_AddressManager public libAddressManager;
/***************
* Constructor *
***************/
/**
* @param _libAddressManager Address of the Lib_AddressManager.
*/
constructor(
address _libAddressManager
) {
libAddressManager = Lib_AddressManager(_libAddressManager);
}
/********************
* Public Functions *
********************/
/**
* Resolves the address associated with a given name.
* @param _name Name to resolve an address for.
* @return Address associated with the given name.
*/
function resolve(
string memory _name
)
public
view
returns (
address
)
{
return libAddressManager.getAddress(_name);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/**
* @title Lib_MerkleTree
* @author River Keefer
*/
library Lib_MerkleTree {
/**********************
* Internal Functions *
**********************/
/**
* Calculates a merkle root for a list of 32-byte leaf hashes. WARNING: If the number
* of leaves passed in is not a power of two, it pads out the tree with zero hashes.
* If you do not know the original length of elements for the tree you are verifying, then
* this may allow empty leaves past _elements.length to pass a verification check down the line.
* Note that the _elements argument is modified, therefore it must not be used again afterwards
* @param _elements Array of hashes from which to generate a merkle root.
* @return Merkle root of the leaves, with zero hashes for non-powers-of-two (see above).
*/
function getMerkleRoot(
bytes32[] memory _elements
)
internal
pure
returns (
bytes32
)
{
require(
_elements.length > 0,
"Lib_MerkleTree: Must provide at least one leaf hash."
);
if (_elements.length == 1) {
return _elements[0];
}
uint256[16] memory defaults = [
0x290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e563,
0x633dc4d7da7256660a892f8f1604a44b5432649cc8ec5cb3ced4c4e6ac94dd1d,
0x890740a8eb06ce9be422cb8da5cdafc2b58c0a5e24036c578de2a433c828ff7d,
0x3b8ec09e026fdc305365dfc94e189a81b38c7597b3d941c279f042e8206e0bd8,
0xecd50eee38e386bd62be9bedb990706951b65fe053bd9d8a521af753d139e2da,
0xdefff6d330bb5403f63b14f33b578274160de3a50df4efecf0e0db73bcdd3da5,
0x617bdd11f7c0a11f49db22f629387a12da7596f9d1704d7465177c63d88ec7d7,
0x292c23a9aa1d8bea7e2435e555a4a60e379a5a35f3f452bae60121073fb6eead,
0xe1cea92ed99acdcb045a6726b2f87107e8a61620a232cf4d7d5b5766b3952e10,
0x7ad66c0a68c72cb89e4fb4303841966e4062a76ab97451e3b9fb526a5ceb7f82,
0xe026cc5a4aed3c22a58cbd3d2ac754c9352c5436f638042dca99034e83636516,
0x3d04cffd8b46a874edf5cfae63077de85f849a660426697b06a829c70dd1409c,
0xad676aa337a485e4728a0b240d92b3ef7b3c372d06d189322bfd5f61f1e7203e,
0xa2fca4a49658f9fab7aa63289c91b7c7b6c832a6d0e69334ff5b0a3483d09dab,
0x4ebfd9cd7bca2505f7bef59cc1c12ecc708fff26ae4af19abe852afe9e20c862,
0x2def10d13dd169f550f578bda343d9717a138562e0093b380a1120789d53cf10
];
// Reserve memory space for our hashes.
bytes memory buf = new bytes(64);
// We'll need to keep track of left and right siblings.
bytes32 leftSibling;
bytes32 rightSibling;
// Number of non-empty nodes at the current depth.
uint256 rowSize = _elements.length;
// Current depth, counting from 0 at the leaves
uint256 depth = 0;
// Common sub-expressions
uint256 halfRowSize; // rowSize / 2
bool rowSizeIsOdd; // rowSize % 2 == 1
while (rowSize > 1) {
halfRowSize = rowSize / 2;
rowSizeIsOdd = rowSize % 2 == 1;
for (uint256 i = 0; i < halfRowSize; i++) {
leftSibling = _elements[(2 * i) ];
rightSibling = _elements[(2 * i) + 1];
assembly {
mstore(add(buf, 32), leftSibling )
mstore(add(buf, 64), rightSibling)
}
_elements[i] = keccak256(buf);
}
if (rowSizeIsOdd) {
leftSibling = _elements[rowSize - 1];
rightSibling = bytes32(defaults[depth]);
assembly {
mstore(add(buf, 32), leftSibling)
mstore(add(buf, 64), rightSibling)
}
_elements[halfRowSize] = keccak256(buf);
}
rowSize = halfRowSize + (rowSizeIsOdd ? 1 : 0);
depth++;
}
return _elements[0];
}
/**
* Verifies a merkle branch for the given leaf hash. Assumes the original length
* of leaves generated is a known, correct input, and does not return true for indices
* extending past that index (even if _siblings would be otherwise valid.)
* @param _root The Merkle root to verify against.
* @param _leaf The leaf hash to verify inclusion of.
* @param _index The index in the tree of this leaf.
* @param _siblings Array of sibline nodes in the inclusion proof, starting from depth 0
* (bottom of the tree).
* @param _totalLeaves The total number of leaves originally passed into.
* @return Whether or not the merkle branch and leaf passes verification.
*/
function verify(
bytes32 _root,
bytes32 _leaf,
uint256 _index,
bytes32[] memory _siblings,
uint256 _totalLeaves
)
internal
pure
returns (
bool
)
{
require(
_totalLeaves > 0,
"Lib_MerkleTree: Total leaves must be greater than zero."
);
require(
_index < _totalLeaves,
"Lib_MerkleTree: Index out of bounds."
);
require(
_siblings.length == _ceilLog2(_totalLeaves),
"Lib_MerkleTree: Total siblings does not correctly correspond to total leaves."
);
bytes32 computedRoot = _leaf;
for (uint256 i = 0; i < _siblings.length; i++) {
if ((_index & 1) == 1) {
computedRoot = keccak256(
abi.encodePacked(
_siblings[i],
computedRoot
)
);
} else {
computedRoot = keccak256(
abi.encodePacked(
computedRoot,
_siblings[i]
)
);
}
_index >>= 1;
}
return _root == computedRoot;
}
/*********************
* Private Functions *
*********************/
/**
* Calculates the integer ceiling of the log base 2 of an input.
* @param _in Unsigned input to calculate the log.
* @return ceil(log_base_2(_in))
*/
function _ceilLog2(
uint256 _in
)
private
pure
returns (
uint256
)
{
require(
_in > 0,
"Lib_MerkleTree: Cannot compute ceil(log_2) of 0."
);
if (_in == 1) {
return 0;
}
// Find the highest set bit (will be floor(log_2)).
// Borrowed with <3 from https://github.com/ethereum/solidity-examples
uint256 val = _in;
uint256 highest = 0;
for (uint256 i = 128; i >= 1; i >>= 1) {
if (val & (uint(1) << i) - 1 << i != 0) {
highest += i;
val >>= i;
}
}
// Increment by one if this is not a perfect logarithm.
if ((uint(1) << highest) != _in) {
highest += 1;
}
return highest;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_NVMCodec } from "../../libraries/codec/Lib_NVMCodec.sol";
/* Interface Imports */
import { iNVM_ChainStorageContainer } from "./iNVM_ChainStorageContainer.sol";
/**
* @title iNVM_MessageQueue
*/
interface iNVM_MessageQueue {
/**********
* Events *
**********/
event TransactionEnqueued(
address _l1TxOrigin,
address _target,
uint256 _gasLimit,
bytes _data,
uint256 _queueIndex,
uint256 _timestamp
);
/********************
* Public Functions *
********************/
/**
* Accesses the queue storage container.
* @return Reference to the queue storage container.
*/
function queue()
external
view
returns (
iNVM_ChainStorageContainer
);
/**
* Gets the queue element at a particular index.
* @param _index Index of the queue element to access.
* @return _element Queue element at the given index.
*/
function getQueueElement(
uint256 _index
)
external
view
returns (
Lib_NVMCodec.QueueElement memory _element
);
/**
* Retrieves the length of the queue, including
* both pending and canonical transactions.
* @return Length of the queue.
*/
function getQueueLength()
external
view
returns (
uint40
);
/**
* Adds a transaction to the queue.
* @param _target Target contract to send the transaction to.
* @param _gasLimit Gas limit for the given transaction.
* @param _data Transaction data.
*/
function enqueue(
address _target,
uint256 _gasLimit,
bytes memory _data
)
external;
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/**
* @title iNVM_ChainStorageContainer
*/
interface iNVM_ChainStorageContainer {
/********************
* Public Functions *
********************/
/**
* Sets the container's global metadata field. We're using `bytes27` here because we use five
* bytes to maintain the length of the underlying data structure, meaning we have an extra
* 27 bytes to store arbitrary data.
* @param _globalMetadata New global metadata to set.
*/
function setGlobalMetadata(
bytes27 _globalMetadata
)
external;
/**
* Retrieves the container's global metadata field.
* @return Container global metadata field.
*/
function getGlobalMetadata()
external
view
returns (
bytes27
);
/**
* Retrieves the number of objects stored in the container.
* @return Number of objects in the container.
*/
function length()
external
view
returns (
uint256
);
/**
* Pushes an object into the container.
* @param _object A 32 byte value to insert into the container.
*/
function push(
bytes32 _object
)
external;
/**
* Pushes an object into the container. Function allows setting the global metadata since
* we'll need to touch the "length" storage slot anyway, which also contains the global
* metadata (it's an optimization).
* @param _object A 32 byte value to insert into the container.
* @param _globalMetadata New global metadata for the container.
*/
function push(
bytes32 _object,
bytes27 _globalMetadata
)
external;
/**
* Retrieves an object from the container.
* @param _index Index of the particular object to access.
* @return 32 byte object value.
*/
function get(
uint256 _index
)
external
view
returns (
bytes32
);
/**
* Removes all objects after and including a given index.
* @param _index Object index to delete from.
*/
function deleteElementsAfterInclusive(
uint256 _index
)
external;
/**
* Removes all objects after and including a given index. Also allows setting the global
* metadata field.
* @param _index Object index to delete from.
* @param _globalMetadata New global metadata for the container.
*/
function deleteElementsAfterInclusive(
uint256 _index,
bytes27 _globalMetadata
)
external;
}
// SPDX-License-Identifier: MIT
// @unsupported: ovm
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_NVMCodec } from "../../libraries/codec/Lib_NVMCodec.sol";
import { Lib_AddressResolver } from "../../libraries/resolver/Lib_AddressResolver.sol";
import { Lib_Bytes32Utils } from "../../libraries/utils/Lib_Bytes32Utils.sol";
import { Lib_EthUtils } from "../../libraries/utils/Lib_EthUtils.sol";
import { Lib_ErrorUtils } from "../../libraries/utils/Lib_ErrorUtils.sol";
import { Lib_PredeployAddresses } from "../../libraries/constants/Lib_PredeployAddresses.sol";
/* Interface Imports */
import { iNVM_ExecutionManager } from "../../iNVM/execution/iNVM_ExecutionManager.sol";
import { iNVM_StateManager } from "../../iNVM/execution/iNVM_StateManager.sol";
import { iNVM_SafetyChecker } from "../../iNVM/execution/iNVM_SafetyChecker.sol";
/* Contract Imports */
import { NVM_DeployerWhitelist } from "../predeploys/NVM_DeployerWhitelist.sol";
/* External Imports */
import { Math } from "@openzeppelin/contracts/math/Math.sol";
/**
* @title NVM_ExecutionManager
* @dev The Execution Manager (EM) is the core of our OVM implementation, and provides a sandboxed
* environment allowing us to execute OVM transactions deterministically on either Layer 1 or
* Layer 2.
* The EM's run() function is the first function called during the execution of any
* transaction on L2.
* For each context-dependent EVM operation the EM has a function which implements a corresponding
* OVM operation, which will read state from the State Manager contract.
* The EM relies on the Safety Checker to verify that code deployed to Layer 2 does not contain any
* context-dependent operations.
*
* Compiler used: solc
* Runtime target: EVM
*/
contract NVM_ExecutionManager is iNVM_ExecutionManager, Lib_AddressResolver {
/********************************
* External Contract References *
********************************/
iNVM_SafetyChecker internal nvmSafetyChecker;
iNVM_StateManager internal nvmStateManager;
/*******************************
* Execution Context Variables *
*******************************/
GasMeterConfig internal gasMeterConfig;
GlobalContext internal globalContext;
TransactionContext internal transactionContext;
MessageContext internal messageContext;
TransactionRecord internal transactionRecord;
MessageRecord internal messageRecord;
/**************************
* Gas Metering Constants *
**************************/
address constant GAS_METADATA_ADDRESS = 0x06a506A506a506A506a506a506A506A506A506A5;
uint256 constant NUISANCE_GAS_SLOAD = 20000;
uint256 constant NUISANCE_GAS_SSTORE = 20000;
uint256 constant MIN_NUISANCE_GAS_PER_CONTRACT = 30000;
uint256 constant NUISANCE_GAS_PER_CONTRACT_BYTE = 100;
uint256 constant MIN_GAS_FOR_INVALID_STATE_ACCESS = 30000;
/**************************
* Native Value Constants *
**************************/
// Public so we can access and make assertions in integration tests.
uint256 public constant CALL_WITH_VALUE_INTRINSIC_GAS = 90000;
/**************************
* Default Context Values *
**************************/
uint256 constant DEFAULT_UINT256 =
0xdefa017defa017defa017defa017defa017defa017defa017defa017defa017d;
address constant DEFAULT_ADDRESS = 0xdEfa017defA017DeFA017DEfa017DeFA017DeFa0;
/*************************************
* Container Contract Address Prefix *
*************************************/
/**
* @dev The Execution Manager and State Manager each have this 30 byte prefix,
* and are uncallable.
*/
address constant CONTAINER_CONTRACT_PREFIX = 0xDeadDeAddeAddEAddeadDEaDDEAdDeaDDeAD0000;
/***************
* Constructor *
***************/
/**
* @param _libAddressManager Address of the Address Manager.
*/
constructor(
address _libAddressManager,
GasMeterConfig memory _gasMeterConfig,
GlobalContext memory _globalContext
)
Lib_AddressResolver(_libAddressManager)
{
nvmSafetyChecker = iNVM_SafetyChecker(resolve("NVM_SafetyChecker"));
gasMeterConfig = _gasMeterConfig;
globalContext = _globalContext;
_resetContext();
}
/**********************
* Function Modifiers *
**********************/
/**
* Applies dynamically-sized refund to a transaction to account for the difference in execution
* between L1 and L2, so that the overall cost of the ovmOPCODE is fixed.
* @param _cost Desired gas cost for the function after the refund.
*/
modifier netGasCost(
uint256 _cost
) {
uint256 gasProvided = gasleft();
_;
uint256 gasUsed = gasProvided - gasleft();
// We want to refund everything *except* the specified cost.
if (_cost < gasUsed) {
transactionRecord.ovmGasRefund += gasUsed - _cost;
}
}
/**
* Applies a fixed-size gas refund to a transaction to account for the difference in execution
* between L1 and L2, so that the overall cost of an ovmOPCODE can be lowered.
* @param _discount Amount of gas cost to refund for the ovmOPCODE.
*/
modifier fixedGasDiscount(
uint256 _discount
) {
uint256 gasProvided = gasleft();
_;
uint256 gasUsed = gasProvided - gasleft();
// We want to refund the specified _discount, unless this risks underflow.
if (_discount < gasUsed) {
transactionRecord.ovmGasRefund += _discount;
} else {
// refund all we can without risking underflow.
transactionRecord.ovmGasRefund += gasUsed;
}
}
/**
* Makes sure we're not inside a static context.
*/
modifier notStatic() {
if (messageContext.isStatic == true) {
_revertWithFlag(RevertFlag.STATIC_VIOLATION);
}
_;
}
/************************************
* Transaction Execution Entrypoint *
************************************/
/**
* Starts the execution of a transaction via the NVM_ExecutionManager.
* @param _transaction Transaction data to be executed.
* @param _nvmStateManager iNVM_StateManager implementation providing account state.
*/
function run(
Lib_NVMCodec.Transaction memory _transaction,
address _nvmStateManager
)
override
external
returns (
bytes memory
)
{
// Make sure that run() is not re-enterable. This condition should always be satisfied
// Once run has been called once, due to the behavior of _isValidInput().
if (transactionContext.ovmNUMBER != DEFAULT_UINT256) {
return bytes("");
}
// Store our NVM_StateManager instance (significantly easier than attempting to pass the
// address around in calldata).
nvmStateManager = iNVM_StateManager(_nvmStateManager);
// Make sure this function can't be called by anyone except the owner of the
// NVM_StateManager (expected to be an NVM_StateTransitioner). We can revert here because
// this would make the `run` itself invalid.
require(
// This method may return false during fraud proofs, but always returns true in
// L2 nodes' State Manager precompile.
nvmStateManager.isAuthenticated(msg.sender),
"Only authenticated addresses in nvmStateManager can call this function"
);
// Initialize the execution context, must be initialized before we perform any gas metering
// or we'll throw a nuisance gas error.
_initContext(_transaction);
// TEMPORARY: Gas metering is disabled for minnet.
// // Check whether we need to start a new epoch, do so if necessary.
// _checkNeedsNewEpoch(_transaction.timestamp);
// Make sure the transaction's gas limit is valid. We don't revert here because we reserve
// reverts for INVALID_STATE_ACCESS.
if (_isValidInput(_transaction) == false) {
_resetContext();
return bytes("");
}
// TEMPORARY: Gas metering is disabled for minnet.
// // Check gas right before the call to get total gas consumed by OVM transaction.
// uint256 gasProvided = gasleft();
// Run the transaction, make sure to meter the gas usage.
(, bytes memory returndata) = ovmCALL(
_transaction.gasLimit - gasMeterConfig.minTransactionGasLimit,
_transaction.entrypoint,
0,
_transaction.data
);
// TEMPORARY: Gas metering is disabled for minnet.
// // Update the cumulative gas based on the amount of gas used.
// uint256 gasUsed = gasProvided - gasleft();
// _updateCumulativeGas(gasUsed, _transaction.l1QueueOrigin);
// Wipe the execution context.
_resetContext();
return returndata;
}
/******************************
* Opcodes: Execution Context *
******************************/
/**
* @notice Overrides CALLER.
* @return _CALLER Address of the CALLER within the current message context.
*/
function ovmCALLER()
override
external
view
returns (
address _CALLER
)
{
return messageContext.ovmCALLER;
}
/**
* @notice Overrides ADDRESS.
* @return _ADDRESS Active ADDRESS within the current message context.
*/
function ovmADDRESS()
override
public
view
returns (
address _ADDRESS
)
{
return messageContext.ovmADDRESS;
}
/**
* @notice Overrides CALLVALUE.
* @return _CALLVALUE Value sent along with the call according to the current message context.
*/
function ovmCALLVALUE()
override
public
view
returns (
uint256 _CALLVALUE
)
{
return messageContext.ovmCALLVALUE;
}
/**
* @notice Overrides TIMESTAMP.
* @return _TIMESTAMP Value of the TIMESTAMP within the transaction context.
*/
function ovmTIMESTAMP()
override
external
view
returns (
uint256 _TIMESTAMP
)
{
return transactionContext.ovmTIMESTAMP;
}
/**
* @notice Overrides NUMBER.
* @return _NUMBER Value of the NUMBER within the transaction context.
*/
function ovmNUMBER()
override
external
view
returns (
uint256 _NUMBER
)
{
return transactionContext.ovmNUMBER;
}
/**
* @notice Overrides GASLIMIT.
* @return _GASLIMIT Value of the block's GASLIMIT within the transaction context.
*/
function ovmGASLIMIT()
override
external
view
returns (
uint256 _GASLIMIT
)
{
return transactionContext.ovmGASLIMIT;
}
/**
* @notice Overrides CHAINID.
* @return _CHAINID Value of the chain's CHAINID within the global context.
*/
function ovmCHAINID()
override
external
view
returns (
uint256 _CHAINID
)
{
return globalContext.ovmCHAINID;
}
/*********************************
* Opcodes: L2 Execution Context *
*********************************/
/**
* @notice Specifies from which source (Sequencer or Queue) this transaction originated from.
* @return _queueOrigin Enum indicating the ovmL1QUEUEORIGIN within the current message context.
*/
function ovmL1QUEUEORIGIN()
override
external
view
returns (
Lib_NVMCodec.QueueOrigin _queueOrigin
)
{
return transactionContext.ovmL1QUEUEORIGIN;
}
/**
* @notice Specifies which L1 account, if any, sent this transaction by calling enqueue().
* @return _l1TxOrigin Address of the account which sent the tx into L2 from L1.
*/
function ovmL1TXORIGIN()
override
external
view
returns (
address _l1TxOrigin
)
{
return transactionContext.ovmL1TXORIGIN;
}
/********************
* Opcodes: Halting *
********************/
/**
* @notice Overrides REVERT.
* @param _data Bytes data to pass along with the REVERT.
*/
function ovmREVERT(
bytes memory _data
)
override
public
{
_revertWithFlag(RevertFlag.INTENTIONAL_REVERT, _data);
}
/******************************
* Opcodes: Contract Creation *
******************************/
/**
* @notice Overrides CREATE.
* @param _bytecode Code to be used to CREATE a new contract.
* @return Address of the created contract.
* @return Revert data, if and only if the creation threw an exception.
*/
function ovmCREATE(
bytes memory _bytecode
)
override
public
notStatic
fixedGasDiscount(40000)
returns (
address,
bytes memory
)
{
// Creator is always the current ADDRESS.
address creator = ovmADDRESS();
// Check that the deployer is whitelisted, or
// that arbitrary contract deployment has been enabled.
_checkDeployerAllowed(creator);
// Generate the correct CREATE address.
address contractAddress = Lib_EthUtils.getAddressForCREATE(
creator,
_getAccountNonce(creator)
);
return _createContract(
contractAddress,
_bytecode,
MessageType.ovmCREATE
);
}
/**
* @notice Overrides CREATE2.
* @param _bytecode Code to be used to CREATE2 a new contract.
* @param _salt Value used to determine the contract's address.
* @return Address of the created contract.
* @return Revert data, if and only if the creation threw an exception.
*/
function ovmCREATE2(
bytes memory _bytecode,
bytes32 _salt
)
override
external
notStatic
fixedGasDiscount(40000)
returns (
address,
bytes memory
)
{
// Creator is always the current ADDRESS.
address creator = ovmADDRESS();
// Check that the deployer is whitelisted, or
// that arbitrary contract deployment has been enabled.
_checkDeployerAllowed(creator);
// Generate the correct CREATE2 address.
address contractAddress = Lib_EthUtils.getAddressForCREATE2(
creator,
_bytecode,
_salt
);
return _createContract(
contractAddress,
_bytecode,
MessageType.ovmCREATE2
);
}
/*******************************
* Account Abstraction Opcodes *
******************************/
/**
* Retrieves the nonce of the current ovmADDRESS.
* @return _nonce Nonce of the current contract.
*/
function ovmGETNONCE()
override
external
returns (
uint256 _nonce
)
{
return _getAccountNonce(ovmADDRESS());
}
/**
* Bumps the nonce of the current ovmADDRESS by one.
*/
function ovmINCREMENTNONCE()
override
external
notStatic
{
address account = ovmADDRESS();
uint256 nonce = _getAccountNonce(account);
// Prevent overflow.
if (nonce + 1 > nonce) {
_setAccountNonce(account, nonce + 1);
}
}
/**
* Creates a new EOA contract account, for account abstraction.
* @dev Essentially functions like ovmCREATE or ovmCREATE2, but we can bypass a lot of checks
* because the contract we're creating is trusted (no need to do safety checking or to
* handle unexpected reverts). Doesn't need to return an address because the address is
* assumed to be the user's actual address.
* @param _messageHash Hash of a message signed by some user, for verification.
* @param _v Signature `v` parameter.
* @param _r Signature `r` parameter.
* @param _s Signature `s` parameter.
*/
function ovmCREATEEOA(
bytes32 _messageHash,
uint8 _v,
bytes32 _r,
bytes32 _s
)
override
public
notStatic
{
// Recover the EOA address from the message hash and signature parameters. Since we do the
// hashing in advance, we don't have handle different message hashing schemes. Even if this
// function were to return the wrong address (rather than explicitly returning the zero
// address), the rest of the transaction would simply fail (since there's no EOA account to
// actually execute the transaction).
address eoa = ecrecover(
_messageHash,
_v + 27,
_r,
_s
);
// Invalid signature is a case we proactively handle with a revert. We could alternatively
// have this function return a `success` boolean, but this is just easier.
if (eoa == address(0)) {
ovmREVERT(bytes("Signature provided for EOA contract creation is invalid."));
}
// If the user already has an EOA account, then there's no need to perform this operation.
if (_hasEmptyAccount(eoa) == false) {
return;
}
// We always need to initialize the contract with the default account values.
_initPendingAccount(eoa);
// Temporarily set the current address so it's easier to access on L2.
address prevADDRESS = messageContext.ovmADDRESS;
messageContext.ovmADDRESS = eoa;
// Creates a duplicate of the NVM_ProxyEOA located at 0x42....09. Uses the following
// "magic" prefix to deploy an exact copy of the code:
// PUSH1 0x0D # size of this prefix in bytes
// CODESIZE
// SUB # subtract prefix size from codesize
// DUP1
// PUSH1 0x0D
// PUSH1 0x00
// CODECOPY # copy everything after prefix into memory at pos 0
// PUSH1 0x00
// RETURN # return the copied code
address proxyEOA = Lib_EthUtils.createContract(abi.encodePacked(
hex"600D380380600D6000396000f3",
ovmEXTCODECOPY(
Lib_PredeployAddresses.PROXY_EOA,
0,
ovmEXTCODESIZE(Lib_PredeployAddresses.PROXY_EOA)
)
));
// Reset the address now that we're done deploying.
messageContext.ovmADDRESS = prevADDRESS;
// Commit the account with its final values.
_commitPendingAccount(
eoa,
address(proxyEOA),
keccak256(Lib_EthUtils.getCode(address(proxyEOA)))
);
_setAccountNonce(eoa, 0);
}
/*********************************
* Opcodes: Contract Interaction *
*********************************/
/**
* @notice Overrides CALL.
* @param _gasLimit Amount of gas to be passed into this call.
* @param _address Address of the contract to call.
* @param _value ETH value to pass with the call.
* @param _calldata Data to send along with the call.
* @return _success Whether or not the call returned (rather than reverted).
* @return _returndata Data returned by the call.
*/
function ovmCALL(
uint256 _gasLimit,
address _address,
uint256 _value,
bytes memory _calldata
)
override
public
fixedGasDiscount(100000)
returns (
bool _success,
bytes memory _returndata
)
{
// CALL updates the CALLER and ADDRESS.
MessageContext memory nextMessageContext = messageContext;
nextMessageContext.ovmCALLER = nextMessageContext.ovmADDRESS;
nextMessageContext.ovmADDRESS = _address;
nextMessageContext.ovmCALLVALUE = _value;
return _callContract(
nextMessageContext,
_gasLimit,
_address,
_calldata,
MessageType.ovmCALL
);
}
/**
* @notice Overrides STATICCALL.
* @param _gasLimit Amount of gas to be passed into this call.
* @param _address Address of the contract to call.
* @param _calldata Data to send along with the call.
* @return _success Whether or not the call returned (rather than reverted).
* @return _returndata Data returned by the call.
*/
function ovmSTATICCALL(
uint256 _gasLimit,
address _address,
bytes memory _calldata
)
override
public
fixedGasDiscount(80000)
returns (
bool _success,
bytes memory _returndata
)
{
// STATICCALL updates the CALLER, updates the ADDRESS, and runs in a static,
// valueless context.
MessageContext memory nextMessageContext = messageContext;
nextMessageContext.ovmCALLER = nextMessageContext.ovmADDRESS;
nextMessageContext.ovmADDRESS = _address;
nextMessageContext.isStatic = true;
nextMessageContext.ovmCALLVALUE = 0;
return _callContract(
nextMessageContext,
_gasLimit,
_address,
_calldata,
MessageType.ovmSTATICCALL
);
}
/**
* @notice Overrides DELEGATECALL.
* @param _gasLimit Amount of gas to be passed into this call.
* @param _address Address of the contract to call.
* @param _calldata Data to send along with the call.
* @return _success Whether or not the call returned (rather than reverted).
* @return _returndata Data returned by the call.
*/
function ovmDELEGATECALL(
uint256 _gasLimit,
address _address,
bytes memory _calldata
)
override
public
fixedGasDiscount(40000)
returns (
bool _success,
bytes memory _returndata
)
{
// DELEGATECALL does not change anything about the message context.
MessageContext memory nextMessageContext = messageContext;
return _callContract(
nextMessageContext,
_gasLimit,
_address,
_calldata,
MessageType.ovmDELEGATECALL
);
}
/**
* @notice Legacy ovmCALL function which did not support ETH value; this maintains backwards
* compatibility.
* @param _gasLimit Amount of gas to be passed into this call.
* @param _address Address of the contract to call.
* @param _calldata Data to send along with the call.
* @return _success Whether or not the call returned (rather than reverted).
* @return _returndata Data returned by the call.
*/
function ovmCALL(
uint256 _gasLimit,
address _address,
bytes memory _calldata
)
override
public
returns(
bool _success,
bytes memory _returndata
)
{
// Legacy ovmCALL assumed always-0 value.
return ovmCALL(
_gasLimit,
_address,
0,
_calldata
);
}
/************************************
* Opcodes: Contract Storage Access *
************************************/
/**
* @notice Overrides SLOAD.
* @param _key 32 byte key of the storage slot to load.
* @return _value 32 byte value of the requested storage slot.
*/
function ovmSLOAD(
bytes32 _key
)
override
external
netGasCost(40000)
returns (
bytes32 _value
)
{
// We always SLOAD from the storage of ADDRESS.
address contractAddress = ovmADDRESS();
return _getContractStorage(
contractAddress,
_key
);
}
/**
* @notice Overrides SSTORE.
* @param _key 32 byte key of the storage slot to set.
* @param _value 32 byte value for the storage slot.
*/
function ovmSSTORE(
bytes32 _key,
bytes32 _value
)
override
external
notStatic
netGasCost(60000)
{
// We always SSTORE to the storage of ADDRESS.
address contractAddress = ovmADDRESS();
_putContractStorage(
contractAddress,
_key,
_value
);
}
/*********************************
* Opcodes: Contract Code Access *
*********************************/
/**
* @notice Overrides EXTCODECOPY.
* @param _contract Address of the contract to copy code from.
* @param _offset Offset in bytes from the start of contract code to copy beyond.
* @param _length Total number of bytes to copy from the contract's code.
* @return _code Bytes of code copied from the requested contract.
*/
function ovmEXTCODECOPY(
address _contract,
uint256 _offset,
uint256 _length
)
override
public
returns (
bytes memory _code
)
{
return Lib_EthUtils.getCode(
_getAccountEthAddress(_contract),
_offset,
_length
);
}
/**
* @notice Overrides EXTCODESIZE.
* @param _contract Address of the contract to query the size of.
* @return _EXTCODESIZE Size of the requested contract in bytes.
*/
function ovmEXTCODESIZE(
address _contract
)
override
public
returns (
uint256 _EXTCODESIZE
)
{
return Lib_EthUtils.getCodeSize(
_getAccountEthAddress(_contract)
);
}
/**
* @notice Overrides EXTCODEHASH.
* @param _contract Address of the contract to query the hash of.
* @return _EXTCODEHASH Hash of the requested contract.
*/
function ovmEXTCODEHASH(
address _contract
)
override
external
returns (
bytes32 _EXTCODEHASH
)
{
return Lib_EthUtils.getCodeHash(
_getAccountEthAddress(_contract)
);
}
/***************************************
* Public Functions: ETH Value Opcodes *
***************************************/
/**
* @notice Overrides BALANCE.
* NOTE: In the future, this could be optimized to directly invoke EM._getContractStorage(...).
* @param _contract Address of the contract to query the NVM_ETH balance of.
* @return _BALANCE NVM_ETH balance of the requested contract.
*/
function ovmBALANCE(
address _contract
)
override
public
returns (
uint256 _BALANCE
)
{
// Easiest way to get the balance is query NVM_ETH as normal.
bytes memory balanceOfCalldata = abi.encodeWithSignature(
"balanceOf(address)",
_contract
);
// Static call because this should be a read-only query.
(bool success, bytes memory returndata) = ovmSTATICCALL(
gasleft(),
Lib_PredeployAddresses.NVM_ETH,
balanceOfCalldata
);
// All balanceOf queries should successfully return a uint, otherwise this must be an OOG.
if (!success || returndata.length != 32) {
_revertWithFlag(RevertFlag.OUT_OF_GAS);
}
// Return the decoded balance.
return abi.decode(returndata, (uint256));
}
/**
* @notice Overrides SELFBALANCE.
* @return _BALANCE NVM_ETH balance of the requesting contract.
*/
function ovmSELFBALANCE()
override
external
returns (
uint256 _BALANCE
)
{
return ovmBALANCE(ovmADDRESS());
}
/***************************************
* Public Functions: Execution Context *
***************************************/
function getMaxTransactionGasLimit()
external
view
override
returns (
uint256 _maxTransactionGasLimit
)
{
return gasMeterConfig.maxTransactionGasLimit;
}
/********************************************
* Public Functions: Deployment Whitelisting *
********************************************/
/**
* Checks whether the given address is on the whitelist to ovmCREATE/ovmCREATE2,
* and reverts if not.
* @param _deployerAddress Address attempting to deploy a contract.
*/
function _checkDeployerAllowed(
address _deployerAddress
)
internal
{
// From an OVM semantics perspective, this will appear identical to
// the deployer ovmCALLing the whitelist. This is fine--in a sense, we are forcing them to.
(bool success, bytes memory data) = ovmSTATICCALL(
gasleft(),
Lib_PredeployAddresses.DEPLOYER_WHITELIST,
abi.encodeWithSelector(
NVM_DeployerWhitelist.isDeployerAllowed.selector,
_deployerAddress
)
);
bool isAllowed = abi.decode(data, (bool));
if (!isAllowed || !success) {
_revertWithFlag(RevertFlag.CREATOR_NOT_ALLOWED);
}
}
/********************************************
* Internal Functions: Contract Interaction *
********************************************/
/**
* Creates a new contract and associates it with some contract address.
* @param _contractAddress Address to associate the created contract with.
* @param _bytecode Bytecode to be used to create the contract.
* @return Final OVM contract address.
* @return Revertdata, if and only if the creation threw an exception.
*/
function _createContract(
address _contractAddress,
bytes memory _bytecode,
MessageType _messageType
)
internal
returns (
address,
bytes memory
)
{
// We always update the nonce of the creating account, even if the creation fails.
_setAccountNonce(ovmADDRESS(), _getAccountNonce(ovmADDRESS()) + 1);
// We're stepping into a CREATE or CREATE2, so we need to update ADDRESS to point
// to the contract's associated address and CALLER to point to the previous ADDRESS.
MessageContext memory nextMessageContext = messageContext;
nextMessageContext.ovmCALLER = messageContext.ovmADDRESS;
nextMessageContext.ovmADDRESS = _contractAddress;
// Run the common logic which occurs between call-type and create-type messages,
// passing in the creation bytecode and `true` to trigger create-specific logic.
(bool success, bytes memory data) = _handleExternalMessage(
nextMessageContext,
gasleft(),
_contractAddress,
_bytecode,
_messageType
);
// Yellow paper requires that address returned is zero if the contract deployment fails.
return (
success ? _contractAddress : address(0),
data
);
}
/**
* Calls the deployed contract associated with a given address.
* @param _nextMessageContext Message context to be used for the call.
* @param _gasLimit Amount of gas to be passed into this call.
* @param _contract OVM address to be called.
* @param _calldata Data to send along with the call.
* @return _success Whether or not the call returned (rather than reverted).
* @return _returndata Data returned by the call.
*/
function _callContract(
MessageContext memory _nextMessageContext,
uint256 _gasLimit,
address _contract,
bytes memory _calldata,
MessageType _messageType
)
internal
returns (
bool _success,
bytes memory _returndata
)
{
// We reserve addresses of the form 0xdeaddeaddead...NNNN for the container contracts in L2
// geth. So, we block calls to these addresses since they are not safe to run as an OVM
// contract itself.
if (
(uint256(_contract) &
uint256(0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0000))
== uint256(CONTAINER_CONTRACT_PREFIX)
) {
// solhint-disable-next-line max-line-length
// EVM does not return data in the success case, see: https://github.com/ethereum/go-ethereum/blob/aae7660410f0ef90279e14afaaf2f429fdc2a186/core/vm/instructions.go#L600-L604
return (true, hex'');
}
// Both 0x0000... and the EVM precompiles have the same address on L1 and L2 -->
// no trie lookup needed.
address codeContractAddress =
uint(_contract) < 100
? _contract
: _getAccountEthAddress(_contract);
return _handleExternalMessage(
_nextMessageContext,
_gasLimit,
codeContractAddress,
_calldata,
_messageType
);
}
/**
* Handles all interactions which involve the execution manager calling out to untrusted code
* (both calls and creates). Ensures that OVM-related measures are enforced, including L2 gas
* refunds, nuisance gas, and flagged reversions.
*
* @param _nextMessageContext Message context to be used for the external message.
* @param _gasLimit Amount of gas to be passed into this message. NOTE: this argument is
* overwritten in some cases to avoid stack-too-deep.
* @param _contract OVM address being called or deployed to
* @param _data Data for the message (either calldata or creation code)
* @param _messageType What type of ovmOPCODE this message corresponds to.
* @return Whether or not the message (either a call or deployment) succeeded.
* @return Data returned by the message.
*/
function _handleExternalMessage(
MessageContext memory _nextMessageContext,
// NOTE: this argument is overwritten in some cases to avoid stack-too-deep.
uint256 _gasLimit,
address _contract,
bytes memory _data,
MessageType _messageType
)
internal
returns (
bool,
bytes memory
)
{
uint256 messageValue = _nextMessageContext.ovmCALLVALUE;
// If there is value in this message, we need to transfer the ETH over before switching
// contexts.
if (
messageValue > 0
&& _isValueType(_messageType)
) {
// Handle out-of-intrinsic gas consistent with EVM behavior -- the subcall "appears to
// revert" if we don't have enough gas to transfer the ETH.
// Similar to dynamic gas cost of value exceeding gas here:
// solhint-disable-next-line max-line-length
// https://github.com/ethereum/go-ethereum/blob/c503f98f6d5e80e079c1d8a3601d188af2a899da/core/vm/interpreter.go#L268-L273
if (gasleft() < CALL_WITH_VALUE_INTRINSIC_GAS) {
return (false, hex"");
}
// If there *is* enough gas to transfer ETH, then we need to make sure this amount of
// gas is reserved (i.e. not given to the _contract.call below) to guarantee that
// _handleExternalMessage can't run out of gas. In particular, in the event that
// the call fails, we will need to transfer the ETH back to the sender.
// Taking the lesser of _gasLimit and gasleft() - CALL_WITH_VALUE_INTRINSIC_GAS
// guarantees that the second _attemptForcedEthTransfer below, if needed, always has
// enough gas to succeed.
_gasLimit = Math.min(
_gasLimit,
gasleft() - CALL_WITH_VALUE_INTRINSIC_GAS // Cannot overflow due to the above check.
);
// Now transfer the value of the call.
// The target is interpreted to be the next message's ovmADDRESS account.
bool transferredNvmEth = _attemptForcedEthTransfer(
_nextMessageContext.ovmADDRESS,
messageValue
);
// If the ETH transfer fails (should only be possible in the case of insufficient
// balance), then treat this as a revert. This mirrors EVM behavior, see
// solhint-disable-next-line max-line-length
// https://github.com/ethereum/go-ethereum/blob/2dee31930c9977af2a9fcb518fb9838aa609a7cf/core/vm/evm.go#L298
if (!transferredNvmEth) {
return (false, hex"");
}
}
// We need to switch over to our next message context for the duration of this call.
MessageContext memory prevMessageContext = messageContext;
_switchMessageContext(prevMessageContext, _nextMessageContext);
// Nuisance gas is a system used to bound the ability for an attacker to make fraud proofs
// expensive by touching a lot of different accounts or storage slots. Since most contracts
// only use a few storage slots during any given transaction, this shouldn't be a limiting
// factor.
uint256 prevNuisanceGasLeft = messageRecord.nuisanceGasLeft;
uint256 nuisanceGasLimit = _getNuisanceGasLimit(_gasLimit);
messageRecord.nuisanceGasLeft = nuisanceGasLimit;
// Make the call and make sure to pass in the gas limit. Another instance of hidden
// complexity. `_contract` is guaranteed to be a safe contract, meaning its return/revert
// behavior can be controlled. In particular, we enforce that flags are passed through
// revert data as to retrieve execution metadata that would normally be reverted out of
// existence.
bool success;
bytes memory returndata;
if (_isCreateType(_messageType)) {
// safeCREATE() is a function which replicates a CREATE message, but uses return values
// Which match that of CALL (i.e. bool, bytes). This allows many security checks to be
// to be shared between untrusted call and create call frames.
(success, returndata) = address(this).call{gas: _gasLimit}(
abi.encodeWithSelector(
this.safeCREATE.selector,
_data,
_contract
)
);
} else {
(success, returndata) = _contract.call{gas: _gasLimit}(_data);
}
// If the message threw an exception, its value should be returned back to the sender.
// So, we force it back, BEFORE returning the messageContext to the previous addresses.
// This operation is part of the reason we "reserved the intrinsic gas" above.
if (
messageValue > 0
&& _isValueType(_messageType)
&& !success
) {
bool transferredNvmEth = _attemptForcedEthTransfer(
prevMessageContext.ovmADDRESS,
messageValue
);
// Since we transferred it in above and the call reverted, the transfer back should
// always pass. This code path should NEVER be triggered since we sent `messageValue`
// worth of NVM_ETH into the target and reserved sufficient gas to execute the transfer,
// but in case there is some edge case which has been missed, we revert the entire frame
// (and its parent) to make sure the ETH gets sent back.
if (!transferredNvmEth) {
_revertWithFlag(RevertFlag.OUT_OF_GAS);
}
}
// Switch back to the original message context now that we're out of the call and all
// NVM_ETH is in the right place.
_switchMessageContext(_nextMessageContext, prevMessageContext);
// Assuming there were no reverts, the message record should be accurate here. We'll update
// this value in the case of a revert.
uint256 nuisanceGasLeft = messageRecord.nuisanceGasLeft;
// Reverts at this point are completely OK, but we need to make a few updates based on the
// information passed through the revert.
if (success == false) {
(
RevertFlag flag,
uint256 nuisanceGasLeftPostRevert,
uint256 ovmGasRefund,
bytes memory returndataFromFlag
) = _decodeRevertData(returndata);
// INVALID_STATE_ACCESS is the only flag that triggers an immediate abort of the
// parent EVM message. This behavior is necessary because INVALID_STATE_ACCESS must
// halt any further transaction execution that could impact the execution result.
if (flag == RevertFlag.INVALID_STATE_ACCESS) {
_revertWithFlag(flag);
}
// INTENTIONAL_REVERT, UNSAFE_BYTECODE, STATIC_VIOLATION, and CREATOR_NOT_ALLOWED aren't
// dependent on the input state, so we can just handle them like standard reverts.
// Our only change here is to record the gas refund reported by the call (enforced by
// safety checking).
if (
flag == RevertFlag.INTENTIONAL_REVERT
|| flag == RevertFlag.UNSAFE_BYTECODE
|| flag == RevertFlag.STATIC_VIOLATION
|| flag == RevertFlag.CREATOR_NOT_ALLOWED
) {
transactionRecord.ovmGasRefund = ovmGasRefund;
}
// INTENTIONAL_REVERT needs to pass up the user-provided return data encoded into the
// flag, *not* the full encoded flag. Additionally, we surface custom error messages
// to developers in the case of unsafe creations for improved devex.
// All other revert types return no data.
if (
flag == RevertFlag.INTENTIONAL_REVERT
|| flag == RevertFlag.UNSAFE_BYTECODE
) {
returndata = returndataFromFlag;
} else {
returndata = hex'';
}
// Reverts mean we need to use up whatever "nuisance gas" was used by the call.
// EXCEEDS_NUISANCE_GAS explicitly reduces the remaining nuisance gas for this message
// to zero. OUT_OF_GAS is a "pseudo" flag given that messages return no data when they
// run out of gas, so we have to treat this like EXCEEDS_NUISANCE_GAS. All other flags
// will simply pass up the remaining nuisance gas.
nuisanceGasLeft = nuisanceGasLeftPostRevert;
}
// We need to reset the nuisance gas back to its original value minus the amount used here.
messageRecord.nuisanceGasLeft = prevNuisanceGasLeft - (nuisanceGasLimit - nuisanceGasLeft);
return (
success,
returndata
);
}
/**
* Handles the creation-specific safety measures required for OVM contract deployment.
* This function sanitizes the return types for creation messages to match calls (bool, bytes),
* by being an external function which the EM can call, that mimics the success/fail case of the
* CREATE.
* This allows for consistent handling of both types of messages in _handleExternalMessage().
* Having this step occur as a separate call frame also allows us to easily revert the
* contract deployment in the event that the code is unsafe.
*
* @param _creationCode Code to pass into CREATE for deployment.
* @param _address OVM address being deployed to.
*/
function safeCREATE(
bytes memory _creationCode,
address _address
)
external
{
// The only way this should callable is from within _createContract(),
// and it should DEFINITELY not be callable by a non-EM code contract.
if (msg.sender != address(this)) {
return;
}
// Check that there is not already code at this address.
if (_hasEmptyAccount(_address) == false) {
// Note: in the EVM, this case burns all allotted gas. For improved
// developer experience, we do return the remaining gas.
_revertWithFlag(
RevertFlag.CREATE_COLLISION
);
}
// Check the creation bytecode against the NVM_SafetyChecker.
if (nvmSafetyChecker.isBytecodeSafe(_creationCode) == false) {
// Note: in the EVM, this case burns all allotted gas. For improved
// developer experience, we do return the remaining gas.
_revertWithFlag(
RevertFlag.UNSAFE_BYTECODE,
// solhint-disable-next-line max-line-length
Lib_ErrorUtils.encodeRevertString("Contract creation code contains unsafe opcodes. Did you use the right compiler or pass an unsafe constructor argument?")
);
}
// We always need to initialize the contract with the default account values.
_initPendingAccount(_address);
// Actually execute the EVM create message.
// NOTE: The inline assembly below means we can NOT make any evm calls between here and then
address ethAddress = Lib_EthUtils.createContract(_creationCode);
if (ethAddress == address(0)) {
// If the creation fails, the EVM lets us grab its revert data. This may contain a
// revert flag to be used above in _handleExternalMessage, so we pass the revert data
// back up unmodified.
assembly {
returndatacopy(0,0,returndatasize())
revert(0, returndatasize())
}
}
// Again simply checking that the deployed code is safe too. Contracts can generate
// arbitrary deployment code, so there's no easy way to analyze this beforehand.
bytes memory deployedCode = Lib_EthUtils.getCode(ethAddress);
if (nvmSafetyChecker.isBytecodeSafe(deployedCode) == false) {
_revertWithFlag(
RevertFlag.UNSAFE_BYTECODE,
// solhint-disable-next-line max-line-length
Lib_ErrorUtils.encodeRevertString("Constructor attempted to deploy unsafe bytecode.")
);
}
// Contract creation didn't need to be reverted and the bytecode is safe. We finish up by
// associating the desired address with the newly created contract's code hash and address.
_commitPendingAccount(
_address,
ethAddress,
Lib_EthUtils.getCodeHash(ethAddress)
);
}
/******************************************
* Internal Functions: Value Manipulation *
******************************************/
/**
* Invokes an ovmCALL to NVM_ETH.transfer on behalf of the current ovmADDRESS, allowing us to
* force movement of NVM_ETH in correspondence with ETH's native value functionality.
* WARNING: this will send on behalf of whatever the messageContext.ovmADDRESS is in storage
* at the time of the call.
* NOTE: In the future, this could be optimized to directly invoke EM._setContractStorage(...).
* @param _to Amount of NVM_ETH to be sent.
* @param _value Amount of NVM_ETH to send.
* @return _success Whether or not the transfer worked.
*/
function _attemptForcedEthTransfer(
address _to,
uint256 _value
)
internal
returns(
bool _success
)
{
bytes memory transferCalldata = abi.encodeWithSignature(
"transfer(address,uint256)",
_to,
_value
);
// NVM_ETH inherits from the UniswapV2ERC20 standard. In this implementation, its return
// type is a boolean. However, the implementation always returns true if it does not revert
// Thus, success of the call frame is sufficient to infer success of the transfer itself.
(bool success, ) = ovmCALL(
gasleft(),
Lib_PredeployAddresses.NVM_ETH,
0,
transferCalldata
);
return success;
}
/******************************************
* Internal Functions: State Manipulation *
******************************************/
/**
* Checks whether an account exists within the NVM_StateManager.
* @param _address Address of the account to check.
* @return _exists Whether or not the account exists.
*/
function _hasAccount(
address _address
)
internal
returns (
bool _exists
)
{
_checkAccountLoad(_address);
return nvmStateManager.hasAccount(_address);
}
/**
* Checks whether a known empty account exists within the NVM_StateManager.
* @param _address Address of the account to check.
* @return _exists Whether or not the account empty exists.
*/
function _hasEmptyAccount(
address _address
)
internal
returns (
bool _exists
)
{
_checkAccountLoad(_address);
return nvmStateManager.hasEmptyAccount(_address);
}
/**
* Sets the nonce of an account.
* @param _address Address of the account to modify.
* @param _nonce New account nonce.
*/
function _setAccountNonce(
address _address,
uint256 _nonce
)
internal
{
_checkAccountChange(_address);
nvmStateManager.setAccountNonce(_address, _nonce);
}
/**
* Gets the nonce of an account.
* @param _address Address of the account to access.
* @return _nonce Nonce of the account.
*/
function _getAccountNonce(
address _address
)
internal
returns (
uint256 _nonce
)
{
_checkAccountLoad(_address);
return nvmStateManager.getAccountNonce(_address);
}
/**
* Retrieves the Ethereum address of an account.
* @param _address Address of the account to access.
* @return _ethAddress Corresponding Ethereum address.
*/
function _getAccountEthAddress(
address _address
)
internal
returns (
address _ethAddress
)
{
_checkAccountLoad(_address);
return nvmStateManager.getAccountEthAddress(_address);
}
/**
* Creates the default account object for the given address.
* @param _address Address of the account create.
*/
function _initPendingAccount(
address _address
)
internal
{
// Although it seems like `_checkAccountChange` would be more appropriate here, we don't
// actually consider an account "changed" until it's inserted into the state (in this case
// by `_commitPendingAccount`).
_checkAccountLoad(_address);
nvmStateManager.initPendingAccount(_address);
}
/**
* Stores additional relevant data for a new account, thereby "committing" it to the state.
* This function is only called during `ovmCREATE` and `ovmCREATE2` after a successful contract
* creation.
* @param _address Address of the account to commit.
* @param _ethAddress Address of the associated deployed contract.
* @param _codeHash Hash of the code stored at the address.
*/
function _commitPendingAccount(
address _address,
address _ethAddress,
bytes32 _codeHash
)
internal
{
_checkAccountChange(_address);
nvmStateManager.commitPendingAccount(
_address,
_ethAddress,
_codeHash
);
}
/**
* Retrieves the value of a storage slot.
* @param _contract Address of the contract to query.
* @param _key 32 byte key of the storage slot.
* @return _value 32 byte storage slot value.
*/
function _getContractStorage(
address _contract,
bytes32 _key
)
internal
returns (
bytes32 _value
)
{
_checkContractStorageLoad(_contract, _key);
return nvmStateManager.getContractStorage(_contract, _key);
}
/**
* Sets the value of a storage slot.
* @param _contract Address of the contract to modify.
* @param _key 32 byte key of the storage slot.
* @param _value 32 byte storage slot value.
*/
function _putContractStorage(
address _contract,
bytes32 _key,
bytes32 _value
)
internal
{
// We don't set storage if the value didn't change. Although this acts as a convenient
// optimization, it's also necessary to avoid the case in which a contract with no storage
// attempts to store the value "0" at any key. Putting this value (and therefore requiring
// that the value be committed into the storage trie after execution) would incorrectly
// modify the storage root.
if (_getContractStorage(_contract, _key) == _value) {
return;
}
_checkContractStorageChange(_contract, _key);
nvmStateManager.putContractStorage(_contract, _key, _value);
}
/**
* Validation whenever a contract needs to be loaded. Checks that the account exists, charges
* nuisance gas if the account hasn't been loaded before.
* @param _address Address of the account to load.
*/
function _checkAccountLoad(
address _address
)
internal
{
// See `_checkContractStorageLoad` for more information.
if (gasleft() < MIN_GAS_FOR_INVALID_STATE_ACCESS) {
_revertWithFlag(RevertFlag.OUT_OF_GAS);
}
// See `_checkContractStorageLoad` for more information.
if (nvmStateManager.hasAccount(_address) == false) {
_revertWithFlag(RevertFlag.INVALID_STATE_ACCESS);
}
// Check whether the account has been loaded before and mark it as loaded if not. We need
// this because "nuisance gas" only applies to the first time that an account is loaded.
(
bool _wasAccountAlreadyLoaded
) = nvmStateManager.testAndSetAccountLoaded(_address);
// If we hadn't already loaded the account, then we'll need to charge "nuisance gas" based
// on the size of the contract code.
if (_wasAccountAlreadyLoaded == false) {
_useNuisanceGas(
(Lib_EthUtils.getCodeSize(_getAccountEthAddress(_address))
* NUISANCE_GAS_PER_CONTRACT_BYTE) + MIN_NUISANCE_GAS_PER_CONTRACT
);
}
}
/**
* Validation whenever a contract needs to be changed. Checks that the account exists, charges
* nuisance gas if the account hasn't been changed before.
* @param _address Address of the account to change.
*/
function _checkAccountChange(
address _address
)
internal
{
// Start by checking for a load as we only want to charge nuisance gas proportional to
// contract size once.
_checkAccountLoad(_address);
// Check whether the account has been changed before and mark it as changed if not. We need
// this because "nuisance gas" only applies to the first time that an account is changed.
(
bool _wasAccountAlreadyChanged
) = nvmStateManager.testAndSetAccountChanged(_address);
// If we hadn't already loaded the account, then we'll need to charge "nuisance gas" based
// on the size of the contract code.
if (_wasAccountAlreadyChanged == false) {
nvmStateManager.incrementTotalUncommittedAccounts();
_useNuisanceGas(
(Lib_EthUtils.getCodeSize(_getAccountEthAddress(_address))
* NUISANCE_GAS_PER_CONTRACT_BYTE) + MIN_NUISANCE_GAS_PER_CONTRACT
);
}
}
/**
* Validation whenever a slot needs to be loaded. Checks that the account exists, charges
* nuisance gas if the slot hasn't been loaded before.
* @param _contract Address of the account to load from.
* @param _key 32 byte key to load.
*/
function _checkContractStorageLoad(
address _contract,
bytes32 _key
)
internal
{
// Another case of hidden complexity. If we didn't enforce this requirement, then a
// contract could pass in just enough gas to cause the INVALID_STATE_ACCESS check to fail
// on L1 but not on L2. A contract could use this behavior to prevent the
// NVM_ExecutionManager from detecting an invalid state access. Reverting with OUT_OF_GAS
// allows us to also charge for the full message nuisance gas, because you deserve that for
// trying to break the contract in this way.
if (gasleft() < MIN_GAS_FOR_INVALID_STATE_ACCESS) {
_revertWithFlag(RevertFlag.OUT_OF_GAS);
}
// We need to make sure that the transaction isn't trying to access storage that hasn't
// been provided to the NVM_StateManager. We'll immediately abort if this is the case.
// We know that we have enough gas to do this check because of the above test.
if (nvmStateManager.hasContractStorage(_contract, _key) == false) {
_revertWithFlag(RevertFlag.INVALID_STATE_ACCESS);
}
// Check whether the slot has been loaded before and mark it as loaded if not. We need
// this because "nuisance gas" only applies to the first time that a slot is loaded.
(
bool _wasContractStorageAlreadyLoaded
) = nvmStateManager.testAndSetContractStorageLoaded(_contract, _key);
// If we hadn't already loaded the account, then we'll need to charge some fixed amount of
// "nuisance gas".
if (_wasContractStorageAlreadyLoaded == false) {
_useNuisanceGas(NUISANCE_GAS_SLOAD);
}
}
/**
* Validation whenever a slot needs to be changed. Checks that the account exists, charges
* nuisance gas if the slot hasn't been changed before.
* @param _contract Address of the account to change.
* @param _key 32 byte key to change.
*/
function _checkContractStorageChange(
address _contract,
bytes32 _key
)
internal
{
// Start by checking for load to make sure we have the storage slot and that we charge the
// "nuisance gas" necessary to prove the storage slot state.
_checkContractStorageLoad(_contract, _key);
// Check whether the slot has been changed before and mark it as changed if not. We need
// this because "nuisance gas" only applies to the first time that a slot is changed.
(
bool _wasContractStorageAlreadyChanged
) = nvmStateManager.testAndSetContractStorageChanged(_contract, _key);
// If we hadn't already changed the account, then we'll need to charge some fixed amount of
// "nuisance gas".
if (_wasContractStorageAlreadyChanged == false) {
// Changing a storage slot means that we're also going to have to change the
// corresponding account, so do an account change check.
_checkAccountChange(_contract);
nvmStateManager.incrementTotalUncommittedContractStorage();
_useNuisanceGas(NUISANCE_GAS_SSTORE);
}
}
/************************************
* Internal Functions: Revert Logic *
************************************/
/**
* Simple encoding for revert data.
* @param _flag Flag to revert with.
* @param _data Additional user-provided revert data.
* @return _revertdata Encoded revert data.
*/
function _encodeRevertData(
RevertFlag _flag,
bytes memory _data
)
internal
view
returns (
bytes memory _revertdata
)
{
// Out of gas and create exceptions will fundamentally return no data, so simulating it
// shouldn't either.
if (
_flag == RevertFlag.OUT_OF_GAS
) {
return bytes("");
}
// INVALID_STATE_ACCESS doesn't need to return any data other than the flag.
if (_flag == RevertFlag.INVALID_STATE_ACCESS) {
return abi.encode(
_flag,
0,
0,
bytes("")
);
}
// Just ABI encode the rest of the parameters.
return abi.encode(
_flag,
messageRecord.nuisanceGasLeft,
transactionRecord.ovmGasRefund,
_data
);
}
/**
* Simple decoding for revert data.
* @param _revertdata Revert data to decode.
* @return _flag Flag used to revert.
* @return _nuisanceGasLeft Amount of nuisance gas unused by the message.
* @return _ovmGasRefund Amount of gas refunded during the message.
* @return _data Additional user-provided revert data.
*/
function _decodeRevertData(
bytes memory _revertdata
)
internal
pure
returns (
RevertFlag _flag,
uint256 _nuisanceGasLeft,
uint256 _ovmGasRefund,
bytes memory _data
)
{
// A length of zero means the call ran out of gas, just return empty data.
if (_revertdata.length == 0) {
return (
RevertFlag.OUT_OF_GAS,
0,
0,
bytes("")
);
}
// ABI decode the incoming data.
return abi.decode(_revertdata, (RevertFlag, uint256, uint256, bytes));
}
/**
* Causes a message to revert or abort.
* @param _flag Flag to revert with.
* @param _data Additional user-provided data.
*/
function _revertWithFlag(
RevertFlag _flag,
bytes memory _data
)
internal
view
{
bytes memory revertdata = _encodeRevertData(
_flag,
_data
);
assembly {
revert(add(revertdata, 0x20), mload(revertdata))
}
}
/**
* Causes a message to revert or abort.
* @param _flag Flag to revert with.
*/
function _revertWithFlag(
RevertFlag _flag
)
internal
{
_revertWithFlag(_flag, bytes(""));
}
/******************************************
* Internal Functions: Nuisance Gas Logic *
******************************************/
/**
* Computes the nuisance gas limit from the gas limit.
* @dev This function is currently using a naive implementation whereby the nuisance gas limit
* is set to exactly equal the lesser of the gas limit or remaining gas. It's likely that
* this implementation is perfectly fine, but we may change this formula later.
* @param _gasLimit Gas limit to compute from.
* @return _nuisanceGasLimit Computed nuisance gas limit.
*/
function _getNuisanceGasLimit(
uint256 _gasLimit
)
internal
view
returns (
uint256 _nuisanceGasLimit
)
{
return _gasLimit < gasleft() ? _gasLimit : gasleft();
}
/**
* Uses a certain amount of nuisance gas.
* @param _amount Amount of nuisance gas to use.
*/
function _useNuisanceGas(
uint256 _amount
)
internal
{
// Essentially the same as a standard OUT_OF_GAS, except we also retain a record of the gas
// refund to be given at the end of the transaction.
if (messageRecord.nuisanceGasLeft < _amount) {
_revertWithFlag(RevertFlag.EXCEEDS_NUISANCE_GAS);
}
messageRecord.nuisanceGasLeft -= _amount;
}
/************************************
* Internal Functions: Gas Metering *
************************************/
/**
* Checks whether a transaction needs to start a new epoch and does so if necessary.
* @param _timestamp Transaction timestamp.
*/
function _checkNeedsNewEpoch(
uint256 _timestamp
)
internal
{
if (
_timestamp >= (
_getGasMetadata(GasMetadataKey.CURRENT_EPOCH_START_TIMESTAMP)
+ gasMeterConfig.secondsPerEpoch
)
) {
_putGasMetadata(
GasMetadataKey.CURRENT_EPOCH_START_TIMESTAMP,
_timestamp
);
_putGasMetadata(
GasMetadataKey.PREV_EPOCH_SEQUENCER_QUEUE_GAS,
_getGasMetadata(
GasMetadataKey.CUMULATIVE_SEQUENCER_QUEUE_GAS
)
);
_putGasMetadata(
GasMetadataKey.PREV_EPOCH_L1TOL2_QUEUE_GAS,
_getGasMetadata(
GasMetadataKey.CUMULATIVE_L1TOL2_QUEUE_GAS
)
);
}
}
/**
* Validates the input values of a transaction.
* @return _valid Whether or not the transaction data is valid.
*/
function _isValidInput(
Lib_NVMCodec.Transaction memory _transaction
)
view
internal
returns (
bool
)
{
// Prevent reentrancy to run():
// This check prevents calling run with the default ovmNumber.
// Combined with the first check in run():
// if (transactionContext.ovmNUMBER != DEFAULT_UINT256) { return; }
// It should be impossible to re-enter since run() returns before any other call frames are
// created. Since this value is already being written to storage, we save much gas compared
// to using the standard nonReentrant pattern.
if (_transaction.blockNumber == DEFAULT_UINT256) {
return false;
}
if (_isValidGasLimit(_transaction.gasLimit, _transaction.l1QueueOrigin) == false) {
return false;
}
return true;
}
/**
* Validates the gas limit for a given transaction.
* @param _gasLimit Gas limit provided by the transaction.
* param _queueOrigin Queue from which the transaction originated.
* @return _valid Whether or not the gas limit is valid.
*/
function _isValidGasLimit(
uint256 _gasLimit,
Lib_NVMCodec.QueueOrigin // _queueOrigin
)
view
internal
returns (
bool _valid
)
{
// Always have to be below the maximum gas limit.
if (_gasLimit > gasMeterConfig.maxTransactionGasLimit) {
return false;
}
// Always have to be above the minimum gas limit.
if (_gasLimit < gasMeterConfig.minTransactionGasLimit) {
return false;
}
// TEMPORARY: Gas metering is disabled for minnet.
return true;
// GasMetadataKey cumulativeGasKey;
// GasMetadataKey prevEpochGasKey;
// if (_queueOrigin == Lib_NVMCodec.QueueOrigin.SEQUENCER_QUEUE) {
// cumulativeGasKey = GasMetadataKey.CUMULATIVE_SEQUENCER_QUEUE_GAS;
// prevEpochGasKey = GasMetadataKey.PREV_EPOCH_SEQUENCER_QUEUE_GAS;
// } else {
// cumulativeGasKey = GasMetadataKey.CUMULATIVE_L1TOL2_QUEUE_GAS;
// prevEpochGasKey = GasMetadataKey.PREV_EPOCH_L1TOL2_QUEUE_GAS;
// }
// return (
// (
// _getGasMetadata(cumulativeGasKey)
// - _getGasMetadata(prevEpochGasKey)
// + _gasLimit
// ) < gasMeterConfig.maxGasPerQueuePerEpoch
// );
}
/**
* Updates the cumulative gas after a transaction.
* @param _gasUsed Gas used by the transaction.
* @param _queueOrigin Queue from which the transaction originated.
*/
function _updateCumulativeGas(
uint256 _gasUsed,
Lib_NVMCodec.QueueOrigin _queueOrigin
)
internal
{
GasMetadataKey cumulativeGasKey;
if (_queueOrigin == Lib_NVMCodec.QueueOrigin.SEQUENCER_QUEUE) {
cumulativeGasKey = GasMetadataKey.CUMULATIVE_SEQUENCER_QUEUE_GAS;
} else {
cumulativeGasKey = GasMetadataKey.CUMULATIVE_L1TOL2_QUEUE_GAS;
}
_putGasMetadata(
cumulativeGasKey,
(
_getGasMetadata(cumulativeGasKey)
+ gasMeterConfig.minTransactionGasLimit
+ _gasUsed
- transactionRecord.ovmGasRefund
)
);
}
/**
* Retrieves the value of a gas metadata key.
* @param _key Gas metadata key to retrieve.
* @return _value Value stored at the given key.
*/
function _getGasMetadata(
GasMetadataKey _key
)
internal
returns (
uint256 _value
)
{
return uint256(_getContractStorage(
GAS_METADATA_ADDRESS,
bytes32(uint256(_key))
));
}
/**
* Sets the value of a gas metadata key.
* @param _key Gas metadata key to set.
* @param _value Value to store at the given key.
*/
function _putGasMetadata(
GasMetadataKey _key,
uint256 _value
)
internal
{
_putContractStorage(
GAS_METADATA_ADDRESS,
bytes32(uint256(_key)),
bytes32(uint256(_value))
);
}
/*****************************************
* Internal Functions: Execution Context *
*****************************************/
/**
* Swaps over to a new message context.
* @param _prevMessageContext Context we're switching from.
* @param _nextMessageContext Context we're switching to.
*/
function _switchMessageContext(
MessageContext memory _prevMessageContext,
MessageContext memory _nextMessageContext
)
internal
{
// These conditionals allow us to avoid unneccessary SSTOREs. However, they do mean that
// the current storage value for the messageContext MUST equal the _prevMessageContext
// argument, or an SSTORE might be erroneously skipped.
if (_prevMessageContext.ovmCALLER != _nextMessageContext.ovmCALLER) {
messageContext.ovmCALLER = _nextMessageContext.ovmCALLER;
}
if (_prevMessageContext.ovmADDRESS != _nextMessageContext.ovmADDRESS) {
messageContext.ovmADDRESS = _nextMessageContext.ovmADDRESS;
}
if (_prevMessageContext.isStatic != _nextMessageContext.isStatic) {
messageContext.isStatic = _nextMessageContext.isStatic;
}
if (_prevMessageContext.ovmCALLVALUE != _nextMessageContext.ovmCALLVALUE) {
messageContext.ovmCALLVALUE = _nextMessageContext.ovmCALLVALUE;
}
}
/**
* Initializes the execution context.
* @param _transaction OVM transaction being executed.
*/
function _initContext(
Lib_NVMCodec.Transaction memory _transaction
)
internal
{
transactionContext.ovmTIMESTAMP = _transaction.timestamp;
transactionContext.ovmNUMBER = _transaction.blockNumber;
transactionContext.ovmTXGASLIMIT = _transaction.gasLimit;
transactionContext.ovmL1QUEUEORIGIN = _transaction.l1QueueOrigin;
transactionContext.ovmL1TXORIGIN = _transaction.l1TxOrigin;
transactionContext.ovmGASLIMIT = gasMeterConfig.maxGasPerQueuePerEpoch;
messageRecord.nuisanceGasLeft = _getNuisanceGasLimit(_transaction.gasLimit);
}
/**
* Resets the transaction and message context.
*/
function _resetContext()
internal
{
transactionContext.ovmL1TXORIGIN = DEFAULT_ADDRESS;
transactionContext.ovmTIMESTAMP = DEFAULT_UINT256;
transactionContext.ovmNUMBER = DEFAULT_UINT256;
transactionContext.ovmGASLIMIT = DEFAULT_UINT256;
transactionContext.ovmTXGASLIMIT = DEFAULT_UINT256;
transactionContext.ovmL1QUEUEORIGIN = Lib_NVMCodec.QueueOrigin.SEQUENCER_QUEUE;
transactionRecord.ovmGasRefund = DEFAULT_UINT256;
messageContext.ovmCALLER = DEFAULT_ADDRESS;
messageContext.ovmADDRESS = DEFAULT_ADDRESS;
messageContext.isStatic = false;
messageRecord.nuisanceGasLeft = DEFAULT_UINT256;
// Reset the nvmStateManager.
nvmStateManager = iNVM_StateManager(address(0));
}
/******************************************
* Internal Functions: Message Typechecks *
******************************************/
/**
* Returns whether or not the given message type is a CREATE-type.
* @param _messageType the message type in question.
*/
function _isCreateType(
MessageType _messageType
)
internal
pure
returns(
bool
)
{
return (
_messageType == MessageType.ovmCREATE
|| _messageType == MessageType.ovmCREATE2
);
}
/**
* Returns whether or not the given message type (potentially) requires the transfer of ETH
* value along with the message.
* @param _messageType the message type in question.
*/
function _isValueType(
MessageType _messageType
)
internal
pure
returns(
bool
)
{
// ovmSTATICCALL and ovmDELEGATECALL types do not accept or transfer value.
return (
_messageType == MessageType.ovmCALL
|| _messageType == MessageType.ovmCREATE
|| _messageType == MessageType.ovmCREATE2
);
}
/*****************************
* L2-only Helper Functions *
*****************************/
/**
* Unreachable helper function for simulating eth_calls with an OVM message context.
* This function will throw an exception in all cases other than when used as a custom
* entrypoint in L2 Geth to simulate eth_call.
* @param _transaction the message transaction to simulate.
* @param _from the OVM account the simulated call should be from.
* @param _value the amount of ETH value to send.
* @param _nvmStateManager the address of the NVM_StateManager precompile in the L2 state.
*/
function simulateMessage(
Lib_NVMCodec.Transaction memory _transaction,
address _from,
uint256 _value,
iNVM_StateManager _nvmStateManager
)
external
returns (
bytes memory
)
{
// Prevent this call from having any effect unless in a custom-set VM frame
require(msg.sender == address(0));
// Initialize the EM's internal state, ignoring nuisance gas.
nvmStateManager = _nvmStateManager;
_initContext(_transaction);
messageRecord.nuisanceGasLeft = uint(-1);
// Set the ovmADDRESS to the _from so that the subsequent call frame "comes from" them.
messageContext.ovmADDRESS = _from;
// Execute the desired message.
bool isCreate = _transaction.entrypoint == address(0);
if (isCreate) {
(address created, bytes memory revertData) = ovmCREATE(_transaction.data);
if (created == address(0)) {
return abi.encode(false, revertData);
} else {
// The eth_call RPC endpoint for to = undefined will return the deployed bytecode
// in the success case, differing from standard create messages.
return abi.encode(true, Lib_EthUtils.getCode(created));
}
} else {
(bool success, bytes memory returndata) = ovmCALL(
_transaction.gasLimit,
_transaction.entrypoint,
_value,
_transaction.data
);
return abi.encode(success, returndata);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.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);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/**
* @title Lib_RLPReader
* @dev Adapted from "RLPReader" by Hamdi Allam ([email protected]).
*/
library Lib_RLPReader {
/*************
* Constants *
*************/
uint256 constant internal MAX_LIST_LENGTH = 32;
/*********
* Enums *
*********/
enum RLPItemType {
DATA_ITEM,
LIST_ITEM
}
/***********
* Structs *
***********/
struct RLPItem {
uint256 length;
uint256 ptr;
}
/**********************
* Internal Functions *
**********************/
/**
* Converts bytes to a reference to memory position and length.
* @param _in Input bytes to convert.
* @return Output memory reference.
*/
function toRLPItem(
bytes memory _in
)
internal
pure
returns (
RLPItem memory
)
{
uint256 ptr;
assembly {
ptr := add(_in, 32)
}
return RLPItem({
length: _in.length,
ptr: ptr
});
}
/**
* Reads an RLP list value into a list of RLP items.
* @param _in RLP list value.
* @return Decoded RLP list items.
*/
function readList(
RLPItem memory _in
)
internal
pure
returns (
RLPItem[] memory
)
{
(
uint256 listOffset,
,
RLPItemType itemType
) = _decodeLength(_in);
require(
itemType == RLPItemType.LIST_ITEM,
"Invalid RLP list value."
);
// Solidity in-memory arrays can't be increased in size, but *can* be decreased in size by
// writing to the length. Since we can't know the number of RLP items without looping over
// the entire input, we'd have to loop twice to accurately size this array. It's easier to
// simply set a reasonable maximum list length and decrease the size before we finish.
RLPItem[] memory out = new RLPItem[](MAX_LIST_LENGTH);
uint256 itemCount = 0;
uint256 offset = listOffset;
while (offset < _in.length) {
require(
itemCount < MAX_LIST_LENGTH,
"Provided RLP list exceeds max list length."
);
(
uint256 itemOffset,
uint256 itemLength,
) = _decodeLength(RLPItem({
length: _in.length - offset,
ptr: _in.ptr + offset
}));
out[itemCount] = RLPItem({
length: itemLength + itemOffset,
ptr: _in.ptr + offset
});
itemCount += 1;
offset += itemOffset + itemLength;
}
// Decrease the array size to match the actual item count.
assembly {
mstore(out, itemCount)
}
return out;
}
/**
* Reads an RLP list value into a list of RLP items.
* @param _in RLP list value.
* @return Decoded RLP list items.
*/
function readList(
bytes memory _in
)
internal
pure
returns (
RLPItem[] memory
)
{
return readList(
toRLPItem(_in)
);
}
/**
* Reads an RLP bytes value into bytes.
* @param _in RLP bytes value.
* @return Decoded bytes.
*/
function readBytes(
RLPItem memory _in
)
internal
pure
returns (
bytes memory
)
{
(
uint256 itemOffset,
uint256 itemLength,
RLPItemType itemType
) = _decodeLength(_in);
require(
itemType == RLPItemType.DATA_ITEM,
"Invalid RLP bytes value."
);
return _copy(_in.ptr, itemOffset, itemLength);
}
/**
* Reads an RLP bytes value into bytes.
* @param _in RLP bytes value.
* @return Decoded bytes.
*/
function readBytes(
bytes memory _in
)
internal
pure
returns (
bytes memory
)
{
return readBytes(
toRLPItem(_in)
);
}
/**
* Reads an RLP string value into a string.
* @param _in RLP string value.
* @return Decoded string.
*/
function readString(
RLPItem memory _in
)
internal
pure
returns (
string memory
)
{
return string(readBytes(_in));
}
/**
* Reads an RLP string value into a string.
* @param _in RLP string value.
* @return Decoded string.
*/
function readString(
bytes memory _in
)
internal
pure
returns (
string memory
)
{
return readString(
toRLPItem(_in)
);
}
/**
* Reads an RLP bytes32 value into a bytes32.
* @param _in RLP bytes32 value.
* @return Decoded bytes32.
*/
function readBytes32(
RLPItem memory _in
)
internal
pure
returns (
bytes32
)
{
require(
_in.length <= 33,
"Invalid RLP bytes32 value."
);
(
uint256 itemOffset,
uint256 itemLength,
RLPItemType itemType
) = _decodeLength(_in);
require(
itemType == RLPItemType.DATA_ITEM,
"Invalid RLP bytes32 value."
);
uint256 ptr = _in.ptr + itemOffset;
bytes32 out;
assembly {
out := mload(ptr)
// Shift the bytes over to match the item size.
if lt(itemLength, 32) {
out := div(out, exp(256, sub(32, itemLength)))
}
}
return out;
}
/**
* Reads an RLP bytes32 value into a bytes32.
* @param _in RLP bytes32 value.
* @return Decoded bytes32.
*/
function readBytes32(
bytes memory _in
)
internal
pure
returns (
bytes32
)
{
return readBytes32(
toRLPItem(_in)
);
}
/**
* Reads an RLP uint256 value into a uint256.
* @param _in RLP uint256 value.
* @return Decoded uint256.
*/
function readUint256(
RLPItem memory _in
)
internal
pure
returns (
uint256
)
{
return uint256(readBytes32(_in));
}
/**
* Reads an RLP uint256 value into a uint256.
* @param _in RLP uint256 value.
* @return Decoded uint256.
*/
function readUint256(
bytes memory _in
)
internal
pure
returns (
uint256
)
{
return readUint256(
toRLPItem(_in)
);
}
/**
* Reads an RLP bool value into a bool.
* @param _in RLP bool value.
* @return Decoded bool.
*/
function readBool(
RLPItem memory _in
)
internal
pure
returns (
bool
)
{
require(
_in.length == 1,
"Invalid RLP boolean value."
);
uint256 ptr = _in.ptr;
uint256 out;
assembly {
out := byte(0, mload(ptr))
}
require(
out == 0 || out == 1,
"Lib_RLPReader: Invalid RLP boolean value, must be 0 or 1"
);
return out != 0;
}
/**
* Reads an RLP bool value into a bool.
* @param _in RLP bool value.
* @return Decoded bool.
*/
function readBool(
bytes memory _in
)
internal
pure
returns (
bool
)
{
return readBool(
toRLPItem(_in)
);
}
/**
* Reads an RLP address value into a address.
* @param _in RLP address value.
* @return Decoded address.
*/
function readAddress(
RLPItem memory _in
)
internal
pure
returns (
address
)
{
if (_in.length == 1) {
return address(0);
}
require(
_in.length == 21,
"Invalid RLP address value."
);
return address(readUint256(_in));
}
/**
* Reads an RLP address value into a address.
* @param _in RLP address value.
* @return Decoded address.
*/
function readAddress(
bytes memory _in
)
internal
pure
returns (
address
)
{
return readAddress(
toRLPItem(_in)
);
}
/**
* Reads the raw bytes of an RLP item.
* @param _in RLP item to read.
* @return Raw RLP bytes.
*/
function readRawBytes(
RLPItem memory _in
)
internal
pure
returns (
bytes memory
)
{
return _copy(_in);
}
/*********************
* Private Functions *
*********************/
/**
* Decodes the length of an RLP item.
* @param _in RLP item to decode.
* @return Offset of the encoded data.
* @return Length of the encoded data.
* @return RLP item type (LIST_ITEM or DATA_ITEM).
*/
function _decodeLength(
RLPItem memory _in
)
private
pure
returns (
uint256,
uint256,
RLPItemType
)
{
require(
_in.length > 0,
"RLP item cannot be null."
);
uint256 ptr = _in.ptr;
uint256 prefix;
assembly {
prefix := byte(0, mload(ptr))
}
if (prefix <= 0x7f) {
// Single byte.
return (0, 1, RLPItemType.DATA_ITEM);
} else if (prefix <= 0xb7) {
// Short string.
uint256 strLen = prefix - 0x80;
require(
_in.length > strLen,
"Invalid RLP short string."
);
return (1, strLen, RLPItemType.DATA_ITEM);
} else if (prefix <= 0xbf) {
// Long string.
uint256 lenOfStrLen = prefix - 0xb7;
require(
_in.length > lenOfStrLen,
"Invalid RLP long string length."
);
uint256 strLen;
assembly {
// Pick out the string length.
strLen := div(
mload(add(ptr, 1)),
exp(256, sub(32, lenOfStrLen))
)
}
require(
_in.length > lenOfStrLen + strLen,
"Invalid RLP long string."
);
return (1 + lenOfStrLen, strLen, RLPItemType.DATA_ITEM);
} else if (prefix <= 0xf7) {
// Short list.
uint256 listLen = prefix - 0xc0;
require(
_in.length > listLen,
"Invalid RLP short list."
);
return (1, listLen, RLPItemType.LIST_ITEM);
} else {
// Long list.
uint256 lenOfListLen = prefix - 0xf7;
require(
_in.length > lenOfListLen,
"Invalid RLP long list length."
);
uint256 listLen;
assembly {
// Pick out the list length.
listLen := div(
mload(add(ptr, 1)),
exp(256, sub(32, lenOfListLen))
)
}
require(
_in.length > lenOfListLen + listLen,
"Invalid RLP long list."
);
return (1 + lenOfListLen, listLen, RLPItemType.LIST_ITEM);
}
}
/**
* Copies the bytes from a memory location.
* @param _src Pointer to the location to read from.
* @param _offset Offset to start reading from.
* @param _length Number of bytes to read.
* @return Copied bytes.
*/
function _copy(
uint256 _src,
uint256 _offset,
uint256 _length
)
private
pure
returns (
bytes memory
)
{
bytes memory out = new bytes(_length);
if (out.length == 0) {
return out;
}
uint256 src = _src + _offset;
uint256 dest;
assembly {
dest := add(out, 32)
}
// Copy over as many complete words as we can.
for (uint256 i = 0; i < _length / 32; i++) {
assembly {
mstore(dest, mload(src))
}
src += 32;
dest += 32;
}
// Pick out the remaining bytes.
uint256 mask = 256 ** (32 - (_length % 32)) - 1;
assembly {
mstore(
dest,
or(
and(mload(src), not(mask)),
and(mload(dest), mask)
)
)
}
return out;
}
/**
* Copies an RLP item into bytes.
* @param _in RLP item to copy.
* @return Copied bytes.
*/
function _copy(
RLPItem memory _in
)
private
pure
returns (
bytes memory
)
{
return _copy(_in.ptr, 0, _in.length);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/**
* @title Lib_RLPWriter
* @author Bakaoh (with modifications)
*/
library Lib_RLPWriter {
/**********************
* Internal Functions *
**********************/
/**
* RLP encodes a byte string.
* @param _in The byte string to encode.
* @return The RLP encoded string in bytes.
*/
function writeBytes(
bytes memory _in
)
internal
pure
returns (
bytes memory
)
{
bytes memory encoded;
if (_in.length == 1 && uint8(_in[0]) < 128) {
encoded = _in;
} else {
encoded = abi.encodePacked(_writeLength(_in.length, 128), _in);
}
return encoded;
}
/**
* RLP encodes a list of RLP encoded byte byte strings.
* @param _in The list of RLP encoded byte strings.
* @return The RLP encoded list of items in bytes.
*/
function writeList(
bytes[] memory _in
)
internal
pure
returns (
bytes memory
)
{
bytes memory list = _flatten(_in);
return abi.encodePacked(_writeLength(list.length, 192), list);
}
/**
* RLP encodes a string.
* @param _in The string to encode.
* @return The RLP encoded string in bytes.
*/
function writeString(
string memory _in
)
internal
pure
returns (
bytes memory
)
{
return writeBytes(bytes(_in));
}
/**
* RLP encodes an address.
* @param _in The address to encode.
* @return The RLP encoded address in bytes.
*/
function writeAddress(
address _in
)
internal
pure
returns (
bytes memory
)
{
return writeBytes(abi.encodePacked(_in));
}
/**
* RLP encodes a bytes32 value.
* @param _in The bytes32 to encode.
* @return _out The RLP encoded bytes32 in bytes.
*/
function writeBytes32(
bytes32 _in
)
internal
pure
returns (
bytes memory _out
)
{
return writeBytes(abi.encodePacked(_in));
}
/**
* RLP encodes a uint.
* @param _in The uint256 to encode.
* @return The RLP encoded uint256 in bytes.
*/
function writeUint(
uint256 _in
)
internal
pure
returns (
bytes memory
)
{
return writeBytes(_toBinary(_in));
}
/**
* RLP encodes a bool.
* @param _in The bool to encode.
* @return The RLP encoded bool in bytes.
*/
function writeBool(
bool _in
)
internal
pure
returns (
bytes memory
)
{
bytes memory encoded = new bytes(1);
encoded[0] = (_in ? bytes1(0x01) : bytes1(0x80));
return encoded;
}
/*********************
* Private Functions *
*********************/
/**
* Encode the first byte, followed by the `len` in binary form if `length` is more than 55.
* @param _len The length of the string or the payload.
* @param _offset 128 if item is string, 192 if item is list.
* @return RLP encoded bytes.
*/
function _writeLength(
uint256 _len,
uint256 _offset
)
private
pure
returns (
bytes memory
)
{
bytes memory encoded;
if (_len < 56) {
encoded = new bytes(1);
encoded[0] = byte(uint8(_len) + uint8(_offset));
} else {
uint256 lenLen;
uint256 i = 1;
while (_len / i != 0) {
lenLen++;
i *= 256;
}
encoded = new bytes(lenLen + 1);
encoded[0] = byte(uint8(lenLen) + uint8(_offset) + 55);
for(i = 1; i <= lenLen; i++) {
encoded[i] = byte(uint8((_len / (256**(lenLen-i))) % 256));
}
}
return encoded;
}
/**
* Encode integer in big endian binary form with no leading zeroes.
* @notice TODO: This should be optimized with assembly to save gas costs.
* @param _x The integer to encode.
* @return RLP encoded bytes.
*/
function _toBinary(
uint256 _x
)
private
pure
returns (
bytes memory
)
{
bytes memory b = abi.encodePacked(_x);
uint256 i = 0;
for (; i < 32; i++) {
if (b[i] != 0) {
break;
}
}
bytes memory res = new bytes(32 - i);
for (uint256 j = 0; j < res.length; j++) {
res[j] = b[i++];
}
return res;
}
/**
* Copies a piece of memory to another location.
* @notice From: https://github.com/Arachnid/solidity-stringutils/blob/master/src/strings.sol.
* @param _dest Destination location.
* @param _src Source location.
* @param _len Length of memory to copy.
*/
function _memcpy(
uint256 _dest,
uint256 _src,
uint256 _len
)
private
pure
{
uint256 dest = _dest;
uint256 src = _src;
uint256 len = _len;
for(; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
uint256 mask = 256 ** (32 - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
}
/**
* Flattens a list of byte strings into one byte string.
* @notice From: https://github.com/sammayo/solidity-rlp-encoder/blob/master/RLPEncode.sol.
* @param _list List of byte strings to flatten.
* @return The flattened byte string.
*/
function _flatten(
bytes[] memory _list
)
private
pure
returns (
bytes memory
)
{
if (_list.length == 0) {
return new bytes(0);
}
uint256 len;
uint256 i = 0;
for (; i < _list.length; i++) {
len += _list[i].length;
}
bytes memory flattened = new bytes(len);
uint256 flattenedPtr;
assembly { flattenedPtr := add(flattened, 0x20) }
for(i = 0; i < _list.length; i++) {
bytes memory item = _list[i];
uint256 listPtr;
assembly { listPtr := add(item, 0x20)}
_memcpy(flattenedPtr, listPtr, item.length);
flattenedPtr += _list[i].length;
}
return flattened;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/**
* @title Lib_BytesUtils
*/
library Lib_BytesUtils {
/**********************
* Internal Functions *
**********************/
function slice(
bytes memory _bytes,
uint256 _start,
uint256 _length
)
internal
pure
returns (
bytes memory
)
{
require(_length + 31 >= _length, "slice_overflow");
require(_start + _length >= _start, "slice_overflow");
require(_bytes.length >= _start + _length, "slice_outOfBounds");
bytes memory tempBytes;
assembly {
switch iszero(_length)
case 0 {
// Get a location of some free memory and store it in tempBytes as
// Solidity does for memory variables.
tempBytes := mload(0x40)
// The first word of the slice result is potentially a partial
// word read from the original array. To read it, we calculate
// the length of that partial word and start copying that many
// bytes into the array. The first word we copy will start with
// data we don't care about, but the last `lengthmod` bytes will
// land at the beginning of the contents of the new array. When
// we're done copying, we overwrite the full first word with
// the actual length of the slice.
let lengthmod := and(_length, 31)
// The multiplication in the next line is necessary
// because when slicing multiples of 32 bytes (lengthmod == 0)
// the following copy loop was copying the origin's length
// and then ending prematurely not copying everything it should.
let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))
let end := add(mc, _length)
for {
// The multiplication in the next line has the same exact purpose
// as the one above.
let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
mstore(tempBytes, _length)
//update free-memory pointer
//allocating the array padded to 32 bytes like the compiler does now
mstore(0x40, and(add(mc, 31), not(31)))
}
//if we want a zero-length slice let's just return a zero-length array
default {
tempBytes := mload(0x40)
//zero out the 32 bytes slice we are about to return
//we need to do it because Solidity does not garbage collect
mstore(tempBytes, 0)
mstore(0x40, add(tempBytes, 0x20))
}
}
return tempBytes;
}
function slice(
bytes memory _bytes,
uint256 _start
)
internal
pure
returns (
bytes memory
)
{
if (_start >= _bytes.length) {
return bytes("");
}
return slice(_bytes, _start, _bytes.length - _start);
}
function toBytes32PadLeft(
bytes memory _bytes
)
internal
pure
returns (
bytes32
)
{
bytes32 ret;
uint256 len = _bytes.length <= 32 ? _bytes.length : 32;
assembly {
ret := shr(mul(sub(32, len), 8), mload(add(_bytes, 32)))
}
return ret;
}
function toBytes32(
bytes memory _bytes
)
internal
pure
returns (
bytes32
)
{
if (_bytes.length < 32) {
bytes32 ret;
assembly {
ret := mload(add(_bytes, 32))
}
return ret;
}
return abi.decode(_bytes,(bytes32)); // will truncate if input length > 32 bytes
}
function toUint256(
bytes memory _bytes
)
internal
pure
returns (
uint256
)
{
return uint256(toBytes32(_bytes));
}
function toUint24(
bytes memory _bytes,
uint256 _start
)
internal
pure
returns (
uint24
)
{
require(_start + 3 >= _start, "toUint24_overflow");
require(_bytes.length >= _start + 3 , "toUint24_outOfBounds");
uint24 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x3), _start))
}
return tempUint;
}
function toUint8(
bytes memory _bytes,
uint256 _start
)
internal
pure
returns (
uint8
)
{
require(_start + 1 >= _start, "toUint8_overflow");
require(_bytes.length >= _start + 1 , "toUint8_outOfBounds");
uint8 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x1), _start))
}
return tempUint;
}
function toAddress(
bytes memory _bytes,
uint256 _start
)
internal
pure
returns (
address
)
{
require(_start + 20 >= _start, "toAddress_overflow");
require(_bytes.length >= _start + 20, "toAddress_outOfBounds");
address tempAddress;
assembly {
tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)
}
return tempAddress;
}
function toNibbles(
bytes memory _bytes
)
internal
pure
returns (
bytes memory
)
{
bytes memory nibbles = new bytes(_bytes.length * 2);
for (uint256 i = 0; i < _bytes.length; i++) {
nibbles[i * 2] = _bytes[i] >> 4;
nibbles[i * 2 + 1] = bytes1(uint8(_bytes[i]) % 16);
}
return nibbles;
}
function fromNibbles(
bytes memory _bytes
)
internal
pure
returns (
bytes memory
)
{
bytes memory ret = new bytes(_bytes.length / 2);
for (uint256 i = 0; i < ret.length; i++) {
ret[i] = (_bytes[i * 2] << 4) | (_bytes[i * 2 + 1]);
}
return ret;
}
function equal(
bytes memory _bytes,
bytes memory _other
)
internal
pure
returns (
bool
)
{
return keccak256(_bytes) == keccak256(_other);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/**
* @title Lib_Byte32Utils
*/
library Lib_Bytes32Utils {
/**********************
* Internal Functions *
**********************/
/**
* Converts a bytes32 value to a boolean. Anything non-zero will be converted to "true."
* @param _in Input bytes32 value.
* @return Bytes32 as a boolean.
*/
function toBool(
bytes32 _in
)
internal
pure
returns (
bool
)
{
return _in != 0;
}
/**
* Converts a boolean to a bytes32 value.
* @param _in Input boolean value.
* @return Boolean as a bytes32.
*/
function fromBool(
bool _in
)
internal
pure
returns (
bytes32
)
{
return bytes32(uint256(_in ? 1 : 0));
}
/**
* Converts a bytes32 value to an address. Takes the *last* 20 bytes.
* @param _in Input bytes32 value.
* @return Bytes32 as an address.
*/
function toAddress(
bytes32 _in
)
internal
pure
returns (
address
)
{
return address(uint160(uint256(_in)));
}
/**
* Converts an address to a bytes32.
* @param _in Input address value.
* @return Address as a bytes32.
*/
function fromAddress(
address _in
)
internal
pure
returns (
bytes32
)
{
return bytes32(uint256(_in));
}
/**
* Removes the leading zeros from a bytes32 value and returns a new (smaller) bytes value.
* @param _in Input bytes32 value.
* @return Bytes32 without any leading zeros.
*/
function removeLeadingZeros(
bytes32 _in
)
internal
pure
returns (
bytes memory
)
{
bytes memory out;
assembly {
// Figure out how many leading zero bytes to remove.
let shift := 0
for { let i := 0 } and(lt(i, 32), eq(byte(i, _in), 0)) { i := add(i, 1) } {
shift := add(shift, 1)
}
// Reserve some space for our output and fix the free memory pointer.
out := mload(0x40)
mstore(0x40, add(out, 0x40))
// Shift the value and store it into the output bytes.
mstore(add(out, 0x20), shl(mul(shift, 8), _in))
// Store the new size (with leading zero bytes removed) in the output byte size.
mstore(out, sub(32, shift))
}
return out;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/* External Imports */
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
/**
* @title Lib_AddressManager
*/
contract Lib_AddressManager is Ownable {
/**********
* Events *
**********/
event AddressSet(
string indexed _name,
address _newAddress,
address _oldAddress
);
/*************
* Variables *
*************/
mapping (bytes32 => address) private addresses;
/********************
* Public Functions *
********************/
/**
* Changes the address associated with a particular name.
* @param _name String name to associate an address with.
* @param _address Address to associate with the name.
*/
function setAddress(
string memory _name,
address _address
)
external
onlyOwner
{
bytes32 nameHash = _getNameHash(_name);
address oldAddress = addresses[nameHash];
addresses[nameHash] = _address;
emit AddressSet(
_name,
_address,
oldAddress
);
}
/**
* Retrieves the address associated with a given name.
* @param _name Name to retrieve an address for.
* @return Address associated with the given name.
*/
function getAddress(
string memory _name
)
external
view
returns (
address
)
{
return addresses[_getNameHash(_name)];
}
/**********************
* Internal Functions *
**********************/
/**
* Computes the hash of a name.
* @param _name Name to compute a hash for.
* @return Hash of the given name.
*/
function _getNameHash(
string memory _name
)
internal
pure
returns (
bytes32
)
{
return keccak256(abi.encodePacked(_name));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @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
// @unsupported: ovm
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_RLPWriter } from "../rlp/Lib_RLPWriter.sol";
import { Lib_Bytes32Utils } from "./Lib_Bytes32Utils.sol";
/**
* @title Lib_EthUtils
*/
library Lib_EthUtils {
/**********************
* Internal Functions *
**********************/
/**
* Gets the code for a given address.
* @param _address Address to get code for.
* @param _offset Offset to start reading from.
* @param _length Number of bytes to read.
* @return Code read from the contract.
*/
function getCode(
address _address,
uint256 _offset,
uint256 _length
)
internal
view
returns (
bytes memory
)
{
bytes memory code;
assembly {
code := mload(0x40)
mstore(0x40, add(code, add(_length, 0x20)))
mstore(code, _length)
extcodecopy(_address, add(code, 0x20), _offset, _length)
}
return code;
}
/**
* Gets the full code for a given address.
* @param _address Address to get code for.
* @return Full code of the contract.
*/
function getCode(
address _address
)
internal
view
returns (
bytes memory
)
{
return getCode(
_address,
0,
getCodeSize(_address)
);
}
/**
* Gets the size of a contract's code in bytes.
* @param _address Address to get code size for.
* @return Size of the contract's code in bytes.
*/
function getCodeSize(
address _address
)
internal
view
returns (
uint256
)
{
uint256 codeSize;
assembly {
codeSize := extcodesize(_address)
}
return codeSize;
}
/**
* Gets the hash of a contract's code.
* @param _address Address to get a code hash for.
* @return Hash of the contract's code.
*/
function getCodeHash(
address _address
)
internal
view
returns (
bytes32
)
{
bytes32 codeHash;
assembly {
codeHash := extcodehash(_address)
}
return codeHash;
}
/**
* Creates a contract with some given initialization code.
* @param _code Contract initialization code.
* @return Address of the created contract.
*/
function createContract(
bytes memory _code
)
internal
returns (
address
)
{
address created;
assembly {
created := create(
0,
add(_code, 0x20),
mload(_code)
)
}
return created;
}
/**
* Computes the address that would be generated by CREATE.
* @param _creator Address creating the contract.
* @param _nonce Creator's nonce.
* @return Address to be generated by CREATE.
*/
function getAddressForCREATE(
address _creator,
uint256 _nonce
)
internal
pure
returns (
address
)
{
bytes[] memory encoded = new bytes[](2);
encoded[0] = Lib_RLPWriter.writeAddress(_creator);
encoded[1] = Lib_RLPWriter.writeUint(_nonce);
bytes memory encodedList = Lib_RLPWriter.writeList(encoded);
return Lib_Bytes32Utils.toAddress(keccak256(encodedList));
}
/**
* Computes the address that would be generated by CREATE2.
* @param _creator Address creating the contract.
* @param _bytecode Bytecode of the contract to be created.
* @param _salt 32 byte salt value mixed into the hash.
* @return Address to be generated by CREATE2.
*/
function getAddressForCREATE2(
address _creator,
bytes memory _bytecode,
bytes32 _salt
)
internal
pure
returns (
address
)
{
bytes32 hashedData = keccak256(abi.encodePacked(
byte(0xff),
_creator,
_salt,
keccak256(_bytecode)
));
return Lib_Bytes32Utils.toAddress(hashedData);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/**
* @title Lib_ErrorUtils
*/
library Lib_ErrorUtils {
/**********************
* Internal Functions *
**********************/
/**
* Encodes an error string into raw solidity-style revert data.
* (i.e. ascii bytes, prefixed with bytes4(keccak("Error(string))"))
* Ref: https://docs.soliditylang.org/en/v0.8.2/control-structures.html?highlight=Error(string)
* #panic-via-assert-and-error-via-require
* @param _reason Reason for the reversion.
* @return Standard solidity revert data for the given reason.
*/
function encodeRevertString(
string memory _reason
)
internal
pure
returns (
bytes memory
)
{
return abi.encodeWithSignature(
"Error(string)",
_reason
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/**
* @title Lib_PredeployAddresses
*/
library Lib_PredeployAddresses {
address internal constant L2_TO_L1_MESSAGE_PASSER = 0x4200000000000000000000000000000000000000;
address internal constant L1_MESSAGE_SENDER = 0x4200000000000000000000000000000000000001;
address internal constant DEPLOYER_WHITELIST = 0x4200000000000000000000000000000000000002;
address internal constant ECDSA_CONTRACT_ACCOUNT = 0x4200000000000000000000000000000000000003;
address internal constant SEQUENCER_ENTRYPOINT = 0x4200000000000000000000000000000000000005;
address payable internal constant NVM_ETH = 0x4200000000000000000000000000000000000006;
// solhint-disable-next-line max-line-length
address internal constant L2_CROSS_DOMAIN_MESSENGER = 0x4200000000000000000000000000000000000007;
address internal constant LIB_ADDRESS_MANAGER = 0x4200000000000000000000000000000000000008;
address internal constant PROXY_EOA = 0x4200000000000000000000000000000000000009;
// solhint-disable-next-line max-line-length
address internal constant EXECUTION_MANAGER_WRAPPER = 0x420000000000000000000000000000000000000B;
address internal constant SEQUENCER_FEE_WALLET = 0x4200000000000000000000000000000000000011;
address internal constant ERC1820_REGISTRY = 0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24;
address internal constant L2_STANDARD_BRIDGE = 0x4200000000000000000000000000000000000010;
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_NVMCodec } from "../../libraries/codec/Lib_NVMCodec.sol";
interface iNVM_ExecutionManager {
/**********
* Enums *
*********/
enum RevertFlag {
OUT_OF_GAS,
INTENTIONAL_REVERT,
EXCEEDS_NUISANCE_GAS,
INVALID_STATE_ACCESS,
UNSAFE_BYTECODE,
CREATE_COLLISION,
STATIC_VIOLATION,
CREATOR_NOT_ALLOWED
}
enum GasMetadataKey {
CURRENT_EPOCH_START_TIMESTAMP,
CUMULATIVE_SEQUENCER_QUEUE_GAS,
CUMULATIVE_L1TOL2_QUEUE_GAS,
PREV_EPOCH_SEQUENCER_QUEUE_GAS,
PREV_EPOCH_L1TOL2_QUEUE_GAS
}
enum MessageType {
ovmCALL,
ovmSTATICCALL,
ovmDELEGATECALL,
ovmCREATE,
ovmCREATE2
}
/***********
* Structs *
***********/
struct GasMeterConfig {
uint256 minTransactionGasLimit;
uint256 maxTransactionGasLimit;
uint256 maxGasPerQueuePerEpoch;
uint256 secondsPerEpoch;
}
struct GlobalContext {
uint256 ovmCHAINID;
}
struct TransactionContext {
Lib_NVMCodec.QueueOrigin ovmL1QUEUEORIGIN;
uint256 ovmTIMESTAMP;
uint256 ovmNUMBER;
uint256 ovmGASLIMIT;
uint256 ovmTXGASLIMIT;
address ovmL1TXORIGIN;
}
struct TransactionRecord {
uint256 ovmGasRefund;
}
struct MessageContext {
address ovmCALLER;
address ovmADDRESS;
uint256 ovmCALLVALUE;
bool isStatic;
}
struct MessageRecord {
uint256 nuisanceGasLeft;
}
/************************************
* Transaction Execution Entrypoint *
************************************/
function run(
Lib_NVMCodec.Transaction calldata _transaction,
address _txStateManager
) external returns (bytes memory);
/*******************
* Context Opcodes *
*******************/
function ovmCALLER() external view returns (address _caller);
function ovmADDRESS() external view returns (address _address);
function ovmCALLVALUE() external view returns (uint _callValue);
function ovmTIMESTAMP() external view returns (uint256 _timestamp);
function ovmNUMBER() external view returns (uint256 _number);
function ovmGASLIMIT() external view returns (uint256 _gasLimit);
function ovmCHAINID() external view returns (uint256 _chainId);
/**********************
* L2 Context Opcodes *
**********************/
function ovmL1QUEUEORIGIN() external view returns (Lib_NVMCodec.QueueOrigin _queueOrigin);
function ovmL1TXORIGIN() external view returns (address _l1TxOrigin);
/*******************
* Halting Opcodes *
*******************/
function ovmREVERT(bytes memory _data) external;
/*****************************
* Contract Creation Opcodes *
*****************************/
function ovmCREATE(bytes memory _bytecode) external
returns (address _contract, bytes memory _revertdata);
function ovmCREATE2(bytes memory _bytecode, bytes32 _salt) external
returns (address _contract, bytes memory _revertdata);
/*******************************
* Account Abstraction Opcodes *
******************************/
function ovmGETNONCE() external returns (uint256 _nonce);
function ovmINCREMENTNONCE() external;
function ovmCREATEEOA(bytes32 _messageHash, uint8 _v, bytes32 _r, bytes32 _s) external;
/****************************
* Contract Calling Opcodes *
****************************/
// Valueless ovmCALL for maintaining backwards compatibility with legacy OVM bytecode.
function ovmCALL(uint256 _gasLimit, address _address, bytes memory _calldata) external
returns (bool _success, bytes memory _returndata);
function ovmCALL(uint256 _gasLimit, address _address, uint256 _value, bytes memory _calldata)
external returns (bool _success, bytes memory _returndata);
function ovmSTATICCALL(uint256 _gasLimit, address _address, bytes memory _calldata) external
returns (bool _success, bytes memory _returndata);
function ovmDELEGATECALL(uint256 _gasLimit, address _address, bytes memory _calldata) external
returns (bool _success, bytes memory _returndata);
/****************************
* Contract Storage Opcodes *
****************************/
function ovmSLOAD(bytes32 _key) external returns (bytes32 _value);
function ovmSSTORE(bytes32 _key, bytes32 _value) external;
/*************************
* Contract Code Opcodes *
*************************/
function ovmEXTCODECOPY(address _contract, uint256 _offset, uint256 _length) external
returns (bytes memory _code);
function ovmEXTCODESIZE(address _contract) external returns (uint256 _size);
function ovmEXTCODEHASH(address _contract) external returns (bytes32 _hash);
/*********************
* ETH Value Opcodes *
*********************/
function ovmBALANCE(address _contract) external returns (uint256 _balance);
function ovmSELFBALANCE() external returns (uint256 _balance);
/***************************************
* Public Functions: Execution Context *
***************************************/
function getMaxTransactionGasLimit() external view returns (uint _maxTransactionGasLimit);
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_NVMCodec } from "../../libraries/codec/Lib_NVMCodec.sol";
/**
* @title iNVM_StateManager
*/
interface iNVM_StateManager {
/*******************
* Data Structures *
*******************/
enum ItemState {
ITEM_UNTOUCHED,
ITEM_LOADED,
ITEM_CHANGED,
ITEM_COMMITTED
}
/***************************
* Public Functions: Misc *
***************************/
function isAuthenticated(address _address) external view returns (bool);
/***************************
* Public Functions: Setup *
***************************/
function owner() external view returns (address _owner);
function nvmExecutionManager() external view returns (address _nvmExecutionManager);
function setExecutionManager(address _nvmExecutionManager) external;
/************************************
* Public Functions: Account Access *
************************************/
function putAccount(address _address, Lib_NVMCodec.Account memory _account) external;
function putEmptyAccount(address _address) external;
function getAccount(address _address) external view
returns (Lib_NVMCodec.Account memory _account);
function hasAccount(address _address) external view returns (bool _exists);
function hasEmptyAccount(address _address) external view returns (bool _exists);
function setAccountNonce(address _address, uint256 _nonce) external;
function getAccountNonce(address _address) external view returns (uint256 _nonce);
function getAccountEthAddress(address _address) external view returns (address _ethAddress);
function getAccountStorageRoot(address _address) external view returns (bytes32 _storageRoot);
function initPendingAccount(address _address) external;
function commitPendingAccount(address _address, address _ethAddress, bytes32 _codeHash)
external;
function testAndSetAccountLoaded(address _address) external
returns (bool _wasAccountAlreadyLoaded);
function testAndSetAccountChanged(address _address) external
returns (bool _wasAccountAlreadyChanged);
function commitAccount(address _address) external returns (bool _wasAccountCommitted);
function incrementTotalUncommittedAccounts() external;
function getTotalUncommittedAccounts() external view returns (uint256 _total);
function wasAccountChanged(address _address) external view returns (bool);
function wasAccountCommitted(address _address) external view returns (bool);
/************************************
* Public Functions: Storage Access *
************************************/
function putContractStorage(address _contract, bytes32 _key, bytes32 _value) external;
function getContractStorage(address _contract, bytes32 _key) external view
returns (bytes32 _value);
function hasContractStorage(address _contract, bytes32 _key) external view
returns (bool _exists);
function testAndSetContractStorageLoaded(address _contract, bytes32 _key) external
returns (bool _wasContractStorageAlreadyLoaded);
function testAndSetContractStorageChanged(address _contract, bytes32 _key) external
returns (bool _wasContractStorageAlreadyChanged);
function commitContractStorage(address _contract, bytes32 _key) external
returns (bool _wasContractStorageCommitted);
function incrementTotalUncommittedContractStorage() external;
function getTotalUncommittedContractStorage() external view returns (uint256 _total);
function wasContractStorageChanged(address _contract, bytes32 _key) external view
returns (bool);
function wasContractStorageCommitted(address _contract, bytes32 _key) external view
returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/**
* @title iNVM_SafetyChecker
*/
interface iNVM_SafetyChecker {
/********************
* Public Functions *
********************/
function isBytecodeSafe(bytes calldata _bytecode) external pure returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/* Interface Imports */
import { iNVM_DeployerWhitelist } from "../../iNVM/predeploys/iNVM_DeployerWhitelist.sol";
/**
* @title NVM_DeployerWhitelist
* @dev The Deployer Whitelist is a temporary predeploy used to provide additional safety during the
* initial phases of our mainnet roll out. It is owned by the Optimism team, and defines accounts
* which are allowed to deploy contracts on Layer2. The Execution Manager will only allow an
* ovmCREATE or ovmCREATE2 operation to proceed if the deployer's address whitelisted.
*
* Compiler used: optimistic-solc
* Runtime target: OVM
*/
contract NVM_DeployerWhitelist is iNVM_DeployerWhitelist {
/**********************
* Contract Constants *
**********************/
bool public initialized;
bool public allowArbitraryDeployment;
address override public owner;
mapping (address => bool) public whitelist;
/**********************
* Function Modifiers *
**********************/
/**
* Blocks functions to anyone except the contract owner.
*/
modifier onlyOwner() {
require(
msg.sender == owner,
"Function can only be called by the owner of this contract."
);
_;
}
/********************
* Public Functions *
********************/
/**
* Initializes the whitelist.
* @param _owner Address of the owner for this contract.
* @param _allowArbitraryDeployment Whether or not to allow arbitrary contract deployment.
*/
function initialize(
address _owner,
bool _allowArbitraryDeployment
)
override
external
{
if (initialized == true) {
return;
}
initialized = true;
allowArbitraryDeployment = _allowArbitraryDeployment;
owner = _owner;
}
/**
* Adds or removes an address from the deployment whitelist.
* @param _deployer Address to update permissions for.
* @param _isWhitelisted Whether or not the address is whitelisted.
*/
function setWhitelistedDeployer(
address _deployer,
bool _isWhitelisted
)
override
external
onlyOwner
{
whitelist[_deployer] = _isWhitelisted;
}
/**
* Updates the owner of this contract.
* @param _owner Address of the new owner.
*/
function setOwner(
address _owner
)
override
public
onlyOwner
{
owner = _owner;
}
/**
* Updates the arbitrary deployment flag.
* @param _allowArbitraryDeployment Whether or not to allow arbitrary contract deployment.
*/
function setAllowArbitraryDeployment(
bool _allowArbitraryDeployment
)
override
public
onlyOwner
{
allowArbitraryDeployment = _allowArbitraryDeployment;
}
/**
* Permanently enables arbitrary contract deployment and deletes the owner.
*/
function enableArbitraryContractDeployment()
override
external
onlyOwner
{
setAllowArbitraryDeployment(true);
setOwner(address(0));
}
/**
* Checks whether an address is allowed to deploy contracts.
* @param _deployer Address to check.
* @return _allowed Whether or not the address can deploy contracts.
*/
function isDeployerAllowed(
address _deployer
)
override
external
returns (
bool
)
{
return (
initialized == false
|| allowArbitraryDeployment == true
|| whitelist[_deployer]
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/**
* @title iNVM_DeployerWhitelist
*/
interface iNVM_DeployerWhitelist {
/********************
* Public Functions *
********************/
function initialize(address _owner, bool _allowArbitraryDeployment) external;
function owner() external returns (address _owner);
function setWhitelistedDeployer(address _deployer, bool _isWhitelisted) external;
function setOwner(address _newOwner) external;
function setAllowArbitraryDeployment(bool _allowArbitraryDeployment) external;
function enableArbitraryContractDeployment() external;
function isDeployerAllowed(address _deployer) external returns (bool _allowed);
}
|
Validates the gas limit for a given transaction. _gasLimit Gas limit provided by the transaction. param _queueOrigin Queue from which the transaction originated. return _valid Whether or not the gas limit is valid./ Always have to be below the maximum gas limit. Always have to be above the minimum gas limit.
|
function _isValidGasLimit(
uint256 _gasLimit,
)
view
internal
returns (
bool _valid
)
{
if (_gasLimit > gasMeterConfig.maxTransactionGasLimit) {
return false;
}
if (_gasLimit < gasMeterConfig.minTransactionGasLimit) {
return false;
}
| 139,114 |
/**
*Submitted for verification at Etherscan.io on 2022-04-08
*/
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// 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;
}
/**
* @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);
}
// 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);
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// 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;
}
}
/*import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";*/
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
contract MintNft is ERC721, Ownable, ReentrancyGuard{
using Counters for Counters.Counter;
Counters.Counter _tokenIdTracker;
mapping(uint256 => string) public _tokenURIs; //returns uris for particular token id
mapping(uint256 => address) public minter; //returs minter of a token id
mapping(uint256 => uint256) public royalty; //returns royalty of a token id
mapping(address => uint256[]) public mintedByUser;
uint256 public maximumRoyalty = 100;
constructor(string memory NAME, string memory SYMBOL) ERC721(NAME,SYMBOL) {
}
event minted (uint256 _NftId, string msg);
event BatchMint(uint256 _totalNft, string msg);
function _mintNft(address creator, string memory _TokenURI, uint256 _royaltyPercentage)
internal
returns (uint256)
{
uint256 NftId = _tokenIdTracker.current();
_safeMint(creator, NftId);
mintedByUser[creator].push(NftId);
royalty[NftId] = _royaltyPercentage;
minter[NftId] = creator;
_setTokenURI(NftId,_TokenURI);
_tokenIdTracker.increment();
emit minted (NftId,"succesfully minted");
return (NftId);
}
// function to mint multiple nfts
function batchMint( string[] memory _uri, uint256[] memory _royalty) external nonReentrant returns (bool) {
require(_uri.length == _royalty.length,"Length of Uri and Royalty should be same");
uint256 _totalNft = _uri.length;
for(uint i = 0; i< _totalNft; i++) {
require(_royalty[i]< maximumRoyalty,"Royalty cannnot be 100 or more");
_mintNft(msg.sender, _uri[i], _royalty[i]);
}
emit BatchMint(_totalNft, "Batch Mint Success");
return true;
}
// returns royalty
function royaltyForToken(uint256 tokenId) external view isValidId(tokenId) returns (uint256 percentage){
return(royalty[tokenId]);
}
// returns minter of a token
function minterOfToken(uint256 tokenId) external view returns (address _minter){
return(minter[tokenId]);
}
// sets uri for a token
function _setTokenURI(uint256 tokenId, string memory _tokenURI)
internal isValidId(tokenId)
virtual
{
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
// returns the total amount of NFTs minted
function getTokenCounter() external view returns (uint256 tracker){
return(_tokenIdTracker.current());
}
function setMaxRoyalty(uint256 _royalty) external onlyOwner{
maximumRoyalty = _royalty;
}
function getNFTMintedByUser(address user) external view returns (uint256[] memory ids){
return(mintedByUser[user]);
}
// returns uri of a particular token
function tokenURI(uint256 tokenId)
public
view
override isValidId(tokenId)
returns (string memory)
{
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
return _tokenURI;
}
// update uri of a token
function UpdateTokenURI(uint256 tokenId, string memory _TokenURI)
external isValidId(tokenId)
{ require(
_exists(tokenId),
"ERC721Metadata: URI set of nonexistent token"
);
require(
ownerOf(tokenId) == msg.sender,
"NFT_Minter: Only Owner Can update a NFT"
);
_setTokenURI(tokenId,_TokenURI);
}
// modifier to check id tokenid exists or not
modifier isValidId( uint256 nftId){
require(nftId <= _tokenIdTracker.current());
_;
}
}
// NFT SALE CONTRACT
contract NFTMarket is IERC721Receiver, ReentrancyGuard, Ownable{
using Counters for Counters.Counter;
using SafeMath for uint;
Counters.Counter private _itemIds; //count of sale items
Counters.Counter private _itemsSold; //count of sold items
Counters.Counter private _itemsinActive;
address payable treasury; // to transfer listingPrice
address payable _seller;
address payable _minter;
MintNft public pangeaNft;
address pangeaNftAddress;
uint256 public treasuryRoyalty = 3;
constructor(address _nftContract,address _treasury) {
pangeaNftAddress = _nftContract; //nft contract for pangea platform
pangeaNft = MintNft(_nftContract);
treasury = payable(_treasury);
}
//struct for each market item
struct MarketItem {
uint itemId;
address nftContract;
uint256 tokenId;
address payable seller;
address payable owner;
address payable minter;
uint256 royalty;
uint256 price;
bool sold;
bool isActive;
}
mapping(uint256 => MarketItem) public idToMarketItem;
event saleCreated (
uint indexed itemId,
address indexed nftContract,
uint256 indexed tokenId,
address seller,
address owner,
address minter,
uint256 royalty,
uint256 price,
bool sold,
bool isActive
);
event ItemBought(
uint indexed itemId,
address indexed nftContract,
uint256 indexed tokenId,
address buyer,
uint256 price,
bool sold,
bool isActive
);
/*get price of a particular item */
function getPrice(uint256 itemid) external view returns (uint256) {
return idToMarketItem[itemid].price;
}
function setTreasuryRoyalty(uint256 royalty) external onlyOwner {
treasuryRoyalty = royalty;
}
function setTreasury(address _treasury) external onlyOwner {
treasury = payable(_treasury);
}
function onERC721Received(address, address, uint256, bytes memory) public virtual override returns (bytes4) {
return this.onERC721Received.selector;
}
/* Places an item for sale on the marketplace */
function createSale(
address nftContract,
uint256 tokenId,
uint256 price
) external nonReentrant {
require(nftContract!=address(0),"zero address cannot be an input");
require(price > 0, "Price must be at least 1 wei");
address tokenOwner = IERC721(nftContract).ownerOf(tokenId);
require(msg.sender == IERC721(nftContract).getApproved(tokenId) || msg.sender == tokenOwner,
"Caller must be approved or owner for token id");
address minter = address(0);
uint256 royalty = 0;
_itemIds.increment();
uint256 itemId = _itemIds.current();
if( nftContract == pangeaNftAddress){
minter = pangeaNft.minterOfToken(tokenId);
royalty = pangeaNft.royaltyForToken(tokenId);
}
idToMarketItem[itemId] = MarketItem(
itemId,
nftContract,
tokenId,
payable(msg.sender),
payable(treasury),
payable(minter),
royalty,
price,
false,
true
);
IERC721(nftContract).safeTransferFrom(msg.sender, address(this), tokenId); //nft gets transferred to the contract
emit saleCreated(
itemId,
nftContract,
tokenId,
msg.sender,
treasury,
minter,
royalty,
price,
false,
true
);
}
/* Creates the sale of a marketplace item */
/* Transfers treasuryship of the item, as well as funds between parties */
//function to buyItem
function buyItem(
uint256 itemId
) external payable nonReentrant {
require(itemId <= _itemIds.current(), " Enter a valid Id");
require( idToMarketItem[itemId].isActive==true,"the sale is not active");
require(msg.sender!= idToMarketItem[itemId].seller,"seller cannot buy");
uint price = idToMarketItem[itemId].price;
uint tokenId = idToMarketItem[itemId].tokenId;
require(msg.value == price, "Please submit the asking price in order to complete the purchase");
require( idToMarketItem[itemId].sold == false,"Already Sold");
_seller = idToMarketItem[itemId].seller;
_minter = idToMarketItem[itemId].minter;
uint256 royalty = idToMarketItem[itemId].royalty;
if(royalty !=0){
uint256 amountToadmin = ((msg.value).mul((treasuryRoyalty))).div(100) ;
uint256 remainingAmount = (msg.value).sub(amountToadmin);
uint256 amountTominter = ((remainingAmount).mul((royalty))).div(100) ;
uint256 amountToSeller = (remainingAmount).sub(amountTominter);
payable(_minter).transfer(amountTominter);
payable(treasury).transfer(amountToadmin);
payable(_seller).transfer(amountToSeller);
}
else{
uint256 amountToadmin = ((msg.value).mul((treasuryRoyalty))).div(100) ;
uint256 remainingAmount = (msg.value).sub(amountToadmin);
payable(treasury).transfer(amountToadmin);
payable(_seller).transfer(remainingAmount);
}
IERC721(idToMarketItem[itemId].nftContract).approve(0x0000000000000000000000000000000000000000,idToMarketItem[itemId].tokenId);
IERC721(idToMarketItem[itemId].nftContract).safeTransferFrom(address(this), msg.sender, tokenId);
idToMarketItem[itemId].owner = payable(msg.sender);
idToMarketItem[itemId].sold = true;
idToMarketItem[itemId].isActive = false;
_itemsSold.increment();
_itemsinActive.increment();
emit ItemBought(
itemId,
idToMarketItem[itemId].nftContract,
tokenId,
msg.sender,
msg.value,
true,
false
);
}
//function to end the sale
function EndSale(uint256 itemId) external nonReentrant {
require(itemId <= _itemIds.current(), " Enter a valid Id");
require(msg.sender==idToMarketItem[itemId].seller && idToMarketItem[itemId].sold == false && idToMarketItem[itemId].isActive == true );
idToMarketItem[itemId].isActive = false;
_itemsinActive.increment();
IERC721(idToMarketItem[itemId].nftContract).approve(0x0000000000000000000000000000000000000000,idToMarketItem[itemId].tokenId);
IERC721(idToMarketItem[itemId].nftContract).transferFrom(address(this), msg.sender, idToMarketItem[itemId].tokenId);
}
//returns royalty for a specific item
function royaltyForItem(uint256 item) external view returns(uint256){
require(item <= _itemIds.current(), " Enter a valid Id");
return(idToMarketItem[item].royalty);
}
/* Returns all unsold market items */
function fetchMarketItems() public view returns (MarketItem[] memory) {
uint itemCount = _itemIds.current();
uint unsoldItemCount = _itemIds.current().sub(_itemsinActive.current());
uint currentIndex = 0;
MarketItem[] memory items = new MarketItem[](unsoldItemCount);
for (uint i = 0; i < itemCount; i++) {
if ( idToMarketItem[i.add(1)].isActive ==true )
{
uint currentId = i.add(1);
MarketItem storage currentItem = idToMarketItem[currentId];
items[currentIndex] = currentItem;
currentIndex = currentIndex.add(1);
}
}
return items;
}
/* Returns items that a user has purchased */
function fetchMyNFTs() public view returns (MarketItem[] memory) {
uint totalItemCount = _itemIds.current();
uint itemCount = 0;
uint currentIndex = 0;
for (uint i = 0; i < totalItemCount; i++) {
if (idToMarketItem[i.add(1)].owner == msg.sender) {
itemCount = itemCount.add(1) ;
}
}
MarketItem[] memory items = new MarketItem[](itemCount);
for (uint i = 0; i < totalItemCount; i++) {
if (idToMarketItem[i.add(1)].owner == msg.sender) {
uint currentId = i.add(1);
MarketItem storage currentItem = idToMarketItem[currentId];
items[currentIndex] = currentItem;
currentIndex = currentIndex.add(1);
}
}
return items;
}
/* Returns only items a user has created */
function fetchItemsCreated() public view returns (MarketItem[] memory) {
uint totalItemCount = _itemIds.current();
uint itemCount = 0;
uint currentIndex = 0;
for (uint i = 0; i < totalItemCount; i++) {
if (idToMarketItem[i.add(1)].seller == msg.sender) {
itemCount = itemCount.add(1);
}
}
MarketItem[] memory items = new MarketItem[](itemCount);
for (uint i = 0; i < totalItemCount; i++) {
if (idToMarketItem[i.add(1)].seller == msg.sender) {
uint currentId = i.add(1);
MarketItem storage currentItem = idToMarketItem[currentId];
items[currentIndex] = currentItem;
currentIndex = currentIndex.add(1) ;
}
}
return items;
}
receive() external payable {}
fallback() external payable {}
}
|
Places an item for sale on the marketplace /
|
function createSale(
address nftContract,
uint256 tokenId,
uint256 price
) external nonReentrant {
require(nftContract!=address(0),"zero address cannot be an input");
require(price > 0, "Price must be at least 1 wei");
address tokenOwner = IERC721(nftContract).ownerOf(tokenId);
require(msg.sender == IERC721(nftContract).getApproved(tokenId) || msg.sender == tokenOwner,
"Caller must be approved or owner for token id");
address minter = address(0);
uint256 royalty = 0;
_itemIds.increment();
uint256 itemId = _itemIds.current();
if( nftContract == pangeaNftAddress){
minter = pangeaNft.minterOfToken(tokenId);
royalty = pangeaNft.royaltyForToken(tokenId);
}
idToMarketItem[itemId] = MarketItem(
itemId,
nftContract,
tokenId,
payable(msg.sender),
payable(treasury),
payable(minter),
royalty,
price,
false,
true
);
emit saleCreated(
itemId,
nftContract,
tokenId,
msg.sender,
treasury,
minter,
royalty,
price,
false,
true
);
}
| 6,512,418 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.6;
import "../interfaces/IDeFiPlazaGov.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title DeFi Plaza governance token (DFPgov)
* @author Jazzer 9F
* @notice Implements lean on gas liquidity reward program for DeFi Plaza
*/
contract DFPgov is IDeFiPlazaGov, Ownable, ERC20 {
// global staking contract state parameters squeezed in 256 bits
struct StakingState {
uint96 totalStake; // Total LP tokens currently staked
uint96 rewardsAccumulatedPerLP; // Rewards accumulated per staked LP token (16.80 bits)
uint32 lastUpdate; // Timestamp of last update
uint32 startTime; // Timestamp rewards started
}
// data per staker, some bits remaining available
struct StakeData {
uint96 stake; // Amount of LPs staked for this staker
uint96 rewardsPerLPAtTimeStaked; // Baseline rewards at the time these LPs were staked
}
address public founder;
address public multisig;
address public indexToken;
StakingState public stakingState;
mapping(address => StakeData) public stakerData;
uint256 public multisigAllocationClaimed;
uint256 public founderAllocationClaimed;
/**
* Basic setup
*/
constructor(address founderAddress, uint256 mintAmount, uint32 startTime) ERC20("Defi Plaza governance", "DFP2") {
// contains the global state of the staking progress
StakingState memory state;
state.startTime = startTime;
stakingState = state;
// generate the initial 4M founder allocation
founder = founderAddress;
_mint(founderAddress, mintAmount);
}
/**
* For staking LPs to accumulate governance token rewards.
* Maintains a single stake per user, but allows to add on top of existing stake.
*/
function stake(uint96 LPamount)
external
override
returns(bool success)
{
// Collect LPs
require(
IERC20(indexToken).transferFrom(msg.sender, address(this), LPamount),
"DFP: Transfer failed"
);
// Update global staking state
StakingState memory state = stakingState;
if ((block.timestamp >= state.startTime) && (state.lastUpdate < 365 days)) {
uint256 t1 = block.timestamp - state.startTime; // calculate time relative to start time
uint256 t0 = uint256(state.lastUpdate);
t1 = (t1 > 365 days) ? 365 days : t1; // clamp at 1 year
uint256 R1 = 100e24 * t1 / 365 days - 50e24 * t1 * t1 / (365 days)**2;
uint256 R0 = 100e24 * t0 / 365 days - 50e24 * t0 * t0 / (365 days)**2;
uint256 totalStake = (state.totalStake < 1600e18) ? 1600e18 : state.totalStake; // Clamp at 1600 for numerical reasons
state.rewardsAccumulatedPerLP += uint96(((R1 - R0) << 80) / totalStake);
state.lastUpdate = uint32(t1);
}
state.totalStake += LPamount;
stakingState = state;
// Update staker data for this user
StakeData memory staker = stakerData[msg.sender];
if (staker.stake == 0) {
staker.stake = LPamount;
staker.rewardsPerLPAtTimeStaked = state.rewardsAccumulatedPerLP;
} else {
uint256 LP1 = staker.stake + LPamount;
uint256 RLP0_ = (uint256(LPamount) * state.rewardsAccumulatedPerLP + uint256(staker.stake) * staker.rewardsPerLPAtTimeStaked) / LP1;
staker.stake = uint96(LP1);
staker.rewardsPerLPAtTimeStaked = uint96(RLP0_);
}
stakerData[msg.sender] = staker;
// Emit staking event
emit Staked(msg.sender, LPamount);
return true;
}
/**
* For unstaking LPs and collecting rewards accumulated up to this point.
* Any unstake action distributes and resets rewards. Simply claiming rewards
* without unstaking can be done by unstaking zero LPs.
*/
function unstake(uint96 LPamount)
external
override
returns(uint256 rewards)
{
// Collect data for this user
StakeData memory staker = stakerData[msg.sender];
require(
staker.stake >= LPamount,
"DFP: Insufficient stake"
);
// Update the global staking state
StakingState memory state = stakingState;
if ((block.timestamp >= state.startTime) && (state.lastUpdate < 365 days)) {
uint256 t1 = block.timestamp - state.startTime; // calculate time relative to start time
uint256 t0 = uint256(state.lastUpdate);
t1 = (t1 > 365 days) ? 365 days : t1; // clamp at 1 year
uint256 R1 = 100e24 * t1 / 365 days - 50e24 * t1 * t1 / (365 days)**2;
uint256 R0 = 100e24 * t0 / 365 days - 50e24 * t0 * t0 / (365 days)**2;
uint256 totalStake = (state.totalStake < 1600e18) ? 1600e18 : state.totalStake; // Clamp at 1600 for numerical reasons
state.rewardsAccumulatedPerLP += uint96(((R1 - R0) << 80) / totalStake);
state.lastUpdate = uint32(t1);
}
state.totalStake -= LPamount;
stakingState = state;
// Calculate rewards
rewards = ((uint256(state.rewardsAccumulatedPerLP) - staker.rewardsPerLPAtTimeStaked) * staker.stake) >> 80;
// Update user data
if (LPamount == staker.stake) delete stakerData[msg.sender];
else {
staker.stake -= LPamount;
staker.rewardsPerLPAtTimeStaked = state.rewardsAccumulatedPerLP;
stakerData[msg.sender] = staker;
}
// Distribute reward and emit event
_mint(msg.sender, rewards);
require(
IERC20(indexToken).transfer(msg.sender, LPamount),
"DFP: Kernel panic"
);
emit Unstaked(msg.sender, LPamount, rewards);
}
/**
* Helper function to check unclaimed rewards for any address
*/
function rewardsQuote(address stakerAddress)
external
view
override
returns(uint256 rewards)
{
// Collect user data
StakeData memory staker = stakerData[stakerAddress];
// Calculate distribution since last on chain update
StakingState memory state = stakingState;
if ((block.timestamp >= state.startTime) && (state.lastUpdate < 365 days)) {
uint256 t1 = block.timestamp - state.startTime; // calculate time relative to start time
uint256 t0 = uint256(state.lastUpdate);
t1 = (t1 > 365 days) ? 365 days : t1; // clamp at 1 year
uint256 R1 = 100e24 * t1 / 365 days - 50e24 * t1 * t1 / (365 days)**2;
uint256 R0 = 100e24 * t0 / 365 days - 50e24 * t0 * t0 / (365 days)**2;
uint256 totalStake = (state.totalStake < 1600e18) ? 1600e18 : state.totalStake; // Clamp at 1600 for numerical reasons
state.rewardsAccumulatedPerLP += uint96(((R1 - R0) << 80) / totalStake);
}
// Calculate unclaimed rewards
rewards = ((uint256(state.rewardsAccumulatedPerLP) - staker.rewardsPerLPAtTimeStaked) * staker.stake) >> 80;
}
/**
* Configure which token is accepted as stake. Can only be done once.
*/
function setIndexToken(address indexTokenAddress)
external
onlyOwner
returns(bool success)
{
require(indexToken==address(0), "Already configured");
indexToken = indexTokenAddress;
_mint(indexTokenAddress, 36e23);
return true;
}
/**
* Set community multisig address
*/
function setMultisigAddress(address multisigAddress)
external
onlyOwner
returns(bool success)
{
multisig = multisigAddress;
return true;
}
/**
* Community is allocated 5M governance tokens which are released on the same
* curve as the tokens that users can stake for. No staking required for this.
* Rewards accumulated can be claimed into the multisig address anytime.
*/
function claimMultisigAllocation()
external
returns(uint256 amountReleased)
{
// Collect global staking state
StakingState memory state = stakingState;
require(block.timestamp > state.startTime, "Too early guys");
// Calculate total community allocation until now
uint256 t1 = block.timestamp - state.startTime; // calculate time relative to start time
t1 = (t1 > 365 days) ? 365 days : t1; // clamp at 1 year
uint256 R1 = 5e24 * t1 / 365 days - 25e23 * t1 * t1 / (365 days)**2;
// Calculate how much is to be released now & update released counter
amountReleased = R1 - multisigAllocationClaimed;
multisigAllocationClaimed = R1;
// Grant rewards and emit event for logging
_mint(multisig, amountReleased);
emit MultisigClaim(multisig, amountReleased);
}
/**
* Founder is granted 5M governance tokens after 1 year.
*/
function claimFounderAllocation(uint256 amount, address destination)
external
returns(uint256 actualAmount)
{
// Basic validity checks
require(msg.sender == founder, "Not yours man");
StakingState memory state = stakingState;
require(block.timestamp - state.startTime >= 365 days, "Too early man");
// Calculate how many rewards are still available & update claimed counter
uint256 availableAmount = 25e23 - founderAllocationClaimed;
actualAmount = (amount > availableAmount) ? availableAmount : amount;
founderAllocationClaimed += actualAmount;
// Grant rewards and emit event for logging
_mint(destination, actualAmount);
emit FounderClaim(destination, actualAmount);
}
/**
* Freeze program (makes it easier to migrate if required)
* This is a one-way thing, only to be used in case of migration.
*/
function stopProgram()
external
onlyOwner()
{
// Update the global staking state
StakingState memory state = stakingState;
if ((block.timestamp >= state.startTime) && (state.lastUpdate < 365 days)) {
uint256 t1 = block.timestamp - state.startTime; // calculate time relative to start time
uint256 t0 = uint256(state.lastUpdate);
t1 = (t1 > 365 days) ? 365 days : t1; // clamp at 1 year
uint256 R1 = 100e24 * t1 / 365 days - 50e24 * t1 * t1 / (365 days)**2;
uint256 R0 = 100e24 * t0 / 365 days - 50e24 * t0 * t0 / (365 days)**2;
uint256 totalStake = (state.totalStake < 1600e18) ? 1600e18 : state.totalStake; // Clamp at 1600 for numerical reasons
state.rewardsAccumulatedPerLP += uint96(((R1 - R0) << 80) / totalStake);
state.lastUpdate = uint32(t1);
}
// Freeze by setting the startTime when we're all going to be dead
state.startTime = type(uint32).max;
stakingState = state;
}
}
|
Freeze program (makes it easier to migrate if required) This is a one-way thing, only to be used in case of migration./ Update the global staking state
|
function stopProgram()
external
onlyOwner()
{
StakingState memory state = stakingState;
if ((block.timestamp >= state.startTime) && (state.lastUpdate < 365 days)) {
uint256 t0 = uint256(state.lastUpdate);
uint256 R1 = 100e24 * t1 / 365 days - 50e24 * t1 * t1 / (365 days)**2;
uint256 R0 = 100e24 * t0 / 365 days - 50e24 * t0 * t0 / (365 days)**2;
state.rewardsAccumulatedPerLP += uint96(((R1 - R0) << 80) / totalStake);
state.lastUpdate = uint32(t1);
}
stakingState = state;
}
| 5,391,078 |
./full_match/3/0x677cD880f777b25229eaFc84980f1683E8955e39/sources/browser/temp.sol
|
This function when activated will burn every token that have existed for a set period of time.
|
function burnReddo() internal {
for (uint i = 0; i < reddosArray.length; i++) {
if (now >= startTime[reddosArray[i]] + 2 minutes) {
_burn(reddosArray[i]);
for (uint j = 0; j < reddosArray.length - 1; j++){
reddosArray[i] = reddosArray[i + 1];
}
reddosArray.pop();
}
}
}
| 8,235,968 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
interface IHarvest {
function setHarvestRewardVault(address _harvestRewardVault) external;
function setHarvestRewardPool(address _harvestRewardPool) external;
function setHarvestPoolToken(address _harvestfToken) external;
function setFarmToken(address _farmToken) external;
function updateReward() external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
interface IHarvestVault {
function deposit(uint256 amount) external;
function withdraw(uint256 numberOfShares) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
interface IMintNoRewardPool {
function stake(uint256 amount) external;
function withdraw(uint256 amount) external;
function earned(address account) external view returns (uint256);
function lastTimeRewardApplicable() external view returns (uint256);
function rewardPerToken() external view returns (uint256);
function rewards(address account) external view returns (uint256);
function userRewardPerTokenPaid(address account)
external
view
returns (uint256);
function lastUpdateTime() external view returns (uint256);
function rewardRate() external view returns (uint256);
function totalSupply() external view returns (uint256);
function rewardPerTokenStored() external view returns (uint256);
function periodFinish() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function getReward() external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
interface IStrategy {
function setTreasury(address payable _feeAddress) external;
function setCap(uint256 _cap) external;
function setLockTime(uint256 _lockTime) external;
function setFeeAddress(address payable _feeAddress) external;
function setFee(uint256 _fee) external;
function rescueDust() external;
function rescueAirdroppedTokens(address _token, address to) external;
function setSushiswapRouter(address _sushiswapRouter) external;
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.4;
// Interface declarations
/* solhint-disable func-order */
interface IUniswapRouter {
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 removeLiquidityETH(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountToken, uint256 amountETH);
function removeLiquidity(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) external returns (uint256 amountA, uint256 amountB);
function getAmountsOut(uint256 amountIn, address[] calldata path)
external
view
returns (uint256[] memory amounts);
function swapExactETHForTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function swapExactTokensForETH(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import "./base/HarvestSCBase.sol";
import "../base/StrategyBase.sol";
/*
|Strategy Flow|
- User shows up with Token and we deposit it in Havest's Vault.
- After this we have fToken that we add in Harvest's Reward Pool which gives FARM as rewards
- Withdrawal flow does same thing, but backwards
- User can obtain extra Token when withdrawing. 50% of them goes to the user, 50% goes to the treasury in ETH
- User can obtain FARM tokens when withdrawing. 50% of them goes to the user in Token, 50% goes to the treasury in ETH
*/
contract HarvestSC is StrategyBase, HarvestSCBase, ReentrancyGuardUpgradeable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
/**
* @notice Create a new HarvestDAI contract
* @param _harvestRewardVault VaultDAI address
* @param _harvestRewardPool NoMintRewardPool address
* @param _sushiswapRouter Sushiswap Router address
* @param _harvestfToken Pool's underlying token address
* @param _farmToken Farm address
* @param _token Token address
* @param _weth WETH address
* @param _treasuryAddress treasury address
* @param _feeAddress fee address
*/
function initialize(
address _harvestRewardVault,
address _harvestRewardPool,
address _sushiswapRouter,
address _harvestfToken,
address _farmToken,
address _token,
address _weth,
address payable _treasuryAddress,
address payable _feeAddress
) external initializer {
__ReentrancyGuard_init();
__HarvestBase_init(
_harvestRewardVault,
_harvestRewardPool,
_sushiswapRouter,
_harvestfToken,
_farmToken,
_token,
_weth,
_treasuryAddress,
_feeAddress,
5000000 * (10**18)
);
}
/**
* @notice Deposit to this strategy for rewards
* @param tokenAmount Amount of Token investment
* @param deadline Number of blocks until transaction expires
* @return Amount of fToken
*/
function deposit(
uint256 tokenAmount,
uint256 deadline,
uint256 slippage
) public nonReentrant returns (uint256) {
// -----
// validate
// -----
_validateDeposit(deadline, tokenAmount, totalToken, slippage);
_updateRewards(msg.sender);
IERC20(token).safeTransferFrom(msg.sender, address(this), tokenAmount);
DepositData memory results;
UserInfo storage user = userInfo[msg.sender];
user.timestamp = block.timestamp;
totalToken = totalToken.add(tokenAmount);
user.amountToken = user.amountToken.add(tokenAmount);
results.obtainedToken = tokenAmount;
// -----
// deposit Token into harvest and get fToken
// -----
results.obtainedfToken = _depositTokenToHarvestVault(
results.obtainedToken
);
// -----
// stake fToken into the NoMintRewardPool
// -----
_stakefTokenToHarvestPool(results.obtainedfToken);
user.amountfToken = user.amountfToken.add(results.obtainedfToken);
// -----
// mint parachain tokens
// -----
_mintParachainAuctionTokens(results.obtainedfToken);
emit Deposit(
msg.sender,
tx.origin,
results.obtainedToken,
results.obtainedfToken
);
user.underlyingRatio = _getRatio(
user.amountfToken,
user.amountToken,
18
);
return results.obtainedfToken;
}
/**
* @notice Withdraw tokens and claim rewards
* @param deadline Number of blocks until transaction expires
* @return Amount of ETH obtained
*/
function withdraw(
uint256 amount,
uint256 deadline,
uint256 slippage,
uint256 ethPerToken,
uint256 ethPerFarm,
uint256 tokensPerEth //no of tokens per 1 eth
) public nonReentrant returns (uint256) {
// -----
// validation
// -----
UserInfo storage user = userInfo[msg.sender];
uint256 receiptBalance = receiptToken.balanceOf(msg.sender);
_validateWithdraw(
deadline,
amount,
user.amountfToken,
receiptBalance,
user.timestamp,
slippage
);
_updateRewards(msg.sender);
WithdrawData memory results;
results.initialAmountfToken = user.amountfToken;
results.prevDustEthBalance = address(this).balance;
// -----
// withdraw from HarvestRewardPool (get fToken back)
// -----
results.obtainedfToken = _unstakefTokenFromHarvestPool(amount);
// -----
// get rewards
// -----
harvestRewardPool.getReward(); //transfers FARM to this contract
// -----
// calculate rewards and do the accounting for fTokens
// -----
uint256 transferableRewards =
_calculateRewards(msg.sender, amount, results.initialAmountfToken);
(user.amountfToken, results.burnAmount) = _calculatefTokenRemainings(
amount,
results.initialAmountfToken
);
_burnParachainAuctionTokens(results.burnAmount);
// -----
// withdraw from HarvestRewardVault (return fToken and get Token back)
// -----
results.obtainedToken = _withdrawTokenFromHarvestVault(
results.obtainedfToken
);
emit ObtainedInfo(
msg.sender,
results.obtainedToken,
results.obtainedfToken
);
// -----
// calculate feeable tokens (extra Token obtained by returning fToken)
// - feeableToken/2 (goes to the treasury in ETH)
// - results.totalToken = obtainedToken + 1/2*feeableToken (goes to the user)
// -----
results.auctionedToken = 0;
(results.feeableToken, results.earnedTokens) = _calculateFeeableTokens(
results.initialAmountfToken,
results.obtainedToken,
user.amountToken,
results.obtainedfToken,
user.underlyingRatio
);
user.earnedTokens = user.earnedTokens.add(results.earnedTokens);
results.calculatedTokenAmount = (amount.mul(10**18)).div(
user.underlyingRatio
);
if (user.amountfToken == 0) {
user.amountToken = 0;
} else {
if (results.calculatedTokenAmount <= user.amountToken) {
user.amountToken = user.amountToken.sub(
results.calculatedTokenAmount
);
} else {
user.amountToken = 0;
}
}
results.obtainedToken = results.obtainedToken.sub(results.feeableToken);
if (results.feeableToken > 0) {
//min
results.auctionedToken = results.feeableToken.div(2);
results.feeableToken = results.feeableToken.sub(
results.auctionedToken
);
}
results.totalToken = results.obtainedToken.add(results.feeableToken);
// -----
// swap auctioned Token to ETH
// -----
address[] memory swapPath = new address[](2);
swapPath[0] = token;
swapPath[1] = weth;
if (results.auctionedToken > 0) {
uint256 swapAuctionedTokenResult =
_swapTokenToEth(
swapPath,
results.auctionedToken,
deadline,
slippage,
ethPerToken
);
results.auctionedEth = results.auctionedEth.add(
swapAuctionedTokenResult
);
emit ExtraTokensExchanged(
msg.sender,
results.auctionedToken,
swapAuctionedTokenResult
);
}
// -----
// check & swap FARM rewards with ETH (50% for treasury) and with Token by going through ETH first (the other 50% for user)
// -----
if (transferableRewards > 0) {
emit RewardsEarned(msg.sender, transferableRewards);
user.earnedRewards = user.earnedRewards.add(transferableRewards);
swapPath[0] = farmToken;
results.rewardsInEth = _swapTokenToEth(
swapPath,
transferableRewards,
deadline,
slippage,
ethPerFarm
);
results.auctionedRewardsInEth = results.rewardsInEth.div(2);
//50% goes to treasury in ETH
results.userRewardsInEth = results.rewardsInEth.sub(
results.auctionedRewardsInEth
);
//50% goes to user in Token (swapped below)
results.auctionedEth = results.auctionedEth.add(
results.auctionedRewardsInEth
);
emit RewardsExchanged(
msg.sender,
"ETH",
transferableRewards,
results.rewardsInEth
);
}
if (results.userRewardsInEth > 0) {
swapPath[0] = weth;
swapPath[1] = token;
uint256 userRewardsEthToTokenResult =
_swapEthToToken(
swapPath,
results.userRewardsInEth,
deadline,
slippage,
tokensPerEth
);
results.totalToken = results.totalToken.add(
userRewardsEthToTokenResult
);
emit RewardsExchanged(
msg.sender,
"Token",
transferableRewards.div(2),
userRewardsEthToTokenResult
);
}
user.rewards = user.rewards.sub(transferableRewards);
// -----
// final accounting
// -----
if (results.calculatedTokenAmount <= totalToken) {
totalToken = totalToken.sub(results.calculatedTokenAmount);
} else {
totalToken = 0;
}
user.underlyingRatio = _getRatio(
user.amountfToken,
user.amountToken,
18
);
// -----
// transfer Token to user, ETH to fee address and ETH to the treasury address
// -----
if (fee > 0) {
uint256 feeToken = _calculateFee(results.totalToken);
results.totalToken = results.totalToken.sub(feeToken);
swapPath[0] = token;
swapPath[1] = weth;
uint256 feeTokenInEth =
_swapTokenToEth(
swapPath,
feeToken,
deadline,
slippage,
ethPerToken
);
safeTransferETH(feeAddress, feeTokenInEth);
user.userCollectedFees = user.userCollectedFees.add(feeTokenInEth);
}
IERC20(token).safeTransfer(msg.sender, results.totalToken);
safeTransferETH(treasuryAddress, results.auctionedEth);
user.userTreasuryEth = user.userTreasuryEth.add(results.auctionedEth);
emit Withdraw(
msg.sender,
tx.origin,
results.obtainedToken,
results.obtainedfToken,
results.auctionedEth
);
// -----
// dust check
// -----
if (address(this).balance > results.prevDustEthBalance) {
ethDust = ethDust.add(
address(this).balance.sub(results.prevDustEthBalance)
);
}
return results.totalToken;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "../../../interfaces/IUniswapRouter.sol";
import "../../../interfaces/IHarvestVault.sol";
import "../../../interfaces/IMintNoRewardPool.sol";
import "../../../interfaces/IHarvest.sol";
import "../../../interfaces/IStrategy.sol";
import "../../base/StrategyBase.sol";
import "./HarvestStorage.sol";
contract HarvestBase is
HarvestStorage,
OwnableUpgradeable,
StrategyBase,
IHarvest,
IStrategy
{
using SafeMath for uint256;
struct UserDeposits {
uint256 timestamp;
uint256 amountfToken;
}
/// @notice Used internally for avoiding "stack-too-deep" error when depositing
struct DepositData {
address[] swapPath;
uint256[] swapAmounts;
uint256 obtainedToken;
uint256 obtainedfToken;
uint256 prevfTokenBalance;
}
/// @notice Used internally for avoiding "stack-too-deep" error when withdrawing
struct WithdrawData {
uint256 prevDustEthBalance;
uint256 prevfTokenBalance;
uint256 prevTokenBalance;
uint256 obtainedfToken;
uint256 obtainedToken;
uint256 feeableToken;
uint256 feeableEth;
uint256 totalEth;
uint256 totalToken;
uint256 auctionedEth;
uint256 auctionedToken;
uint256 rewards;
uint256 farmBalance;
uint256 burnAmount;
uint256 earnedTokens;
uint256 rewardsInEth;
uint256 auctionedRewardsInEth;
uint256 userRewardsInEth;
uint256 initialAmountfToken;
uint256 calculatedTokenAmount;
}
//-----------------------------------------------------------------------------------------------------------------//
//------------------------------------ Events -------------------------------------------------//
//-----------------------------------------------------------------------------------------------------------------//
event ExtraTokensExchanged(
address indexed user,
uint256 tokensAmount,
uint256 obtainedEth
);
event ObtainedInfo(
address indexed user,
uint256 underlying,
uint256 underlyingReceipt
);
event RewardsEarned(address indexed user, uint256 amount);
event ExtraTokens(address indexed user, uint256 amount);
/// @notice Event emitted when owner makes a rescue dust request
event RescuedDust(string indexed dustType, uint256 amount);
/// @notice Event emitted when owner changes any contract address
event ChangedAddress(
string indexed addressType,
address indexed oldAddress,
address indexed newAddress
);
/// @notice Event emitted when owner changes any contract address
event ChangedValue(
string indexed valueType,
uint256 indexed oldValue,
uint256 indexed newValue
);
/**
* @notice Create a new HarvestDAI contract
* @param _harvestRewardVault VaultToken address
* @param _harvestRewardPool NoMintRewardPool address
* @param _sushiswapRouter Sushiswap Router address
* @param _harvestfToken Pool's underlying token address
* @param _farmToken Farm address
* @param _token Token address
* @param _weth WETH address
* @param _treasuryAddress treasury address
* @param _feeAddress fee address
*/
function __HarvestBase_init(
address _harvestRewardVault,
address _harvestRewardPool,
address _sushiswapRouter,
address _harvestfToken,
address _farmToken,
address _token,
address _weth,
address payable _treasuryAddress,
address payable _feeAddress,
uint256 _cap
) internal initializer {
require(_harvestRewardVault != address(0), "VAULT_0x0");
require(_harvestRewardPool != address(0), "POOL_0x0");
require(_harvestfToken != address(0), "fTOKEN_0x0");
require(_farmToken != address(0), "FARM_0x0");
__Ownable_init();
__StrategyBase_init(
_sushiswapRouter,
_token,
_weth,
_treasuryAddress,
_feeAddress,
_cap
);
harvestRewardVault = IHarvestVault(_harvestRewardVault);
harvestRewardPool = IMintNoRewardPool(_harvestRewardPool);
harvestfToken = _harvestfToken;
farmToken = _farmToken;
receiptToken = new ReceiptToken(token, address(this));
}
//-----------------------------------------------------------------------------------------------------------------//
//------------------------------------ Setters -------------------------------------------------//
//-----------------------------------------------------------------------------------------------------------------//
/**
* @notice Update the address of VaultDAI
* @dev Can only be called by the owner
* @param _harvestRewardVault Address of VaultDAI
*/
function setHarvestRewardVault(address _harvestRewardVault)
external
override
onlyOwner
{
require(_harvestRewardVault != address(0), "VAULT_0x0");
emit ChangedAddress(
"VAULT",
address(harvestRewardVault),
_harvestRewardVault
);
harvestRewardVault = IHarvestVault(_harvestRewardVault);
}
/**
* @notice Update the address of NoMintRewardPool
* @dev Can only be called by the owner
* @param _harvestRewardPool Address of NoMintRewardPool
*/
function setHarvestRewardPool(address _harvestRewardPool)
external
override
onlyOwner
{
require(_harvestRewardPool != address(0), "POOL_0x0");
emit ChangedAddress(
"POOL",
address(harvestRewardPool),
_harvestRewardPool
);
harvestRewardPool = IMintNoRewardPool(_harvestRewardPool);
}
/**
* @notice Update the address of Sushiswap Router
* @dev Can only be called by the owner
* @param _sushiswapRouter Address of Sushiswap Router
*/
function setSushiswapRouter(address _sushiswapRouter)
external
override
onlyOwner
{
require(_sushiswapRouter != address(0), "0x0");
emit ChangedAddress(
"SUSHISWAP_ROUTER",
address(sushiswapRouter),
_sushiswapRouter
);
sushiswapRouter = IUniswapRouter(_sushiswapRouter);
}
/**
* @notice Update the address of Pool's underlying token
* @dev Can only be called by the owner
* @param _harvestfToken Address of Pool's underlying token
*/
function setHarvestPoolToken(address _harvestfToken)
external
override
onlyOwner
{
require(_harvestfToken != address(0), "TOKEN_0x0");
emit ChangedAddress("TOKEN", harvestfToken, _harvestfToken);
harvestfToken = _harvestfToken;
}
/**
* @notice Update the address of FARM
* @dev Can only be called by the owner
* @param _farmToken Address of FARM
*/
function setFarmToken(address _farmToken) external override onlyOwner {
require(_farmToken != address(0), "FARM_0x0");
emit ChangedAddress("FARM", farmToken, _farmToken);
farmToken = _farmToken;
}
/**
* @notice Update the address for fees
* @dev Can only be called by the owner
* @param _feeAddress Fee's address
*/
function setTreasury(address payable _feeAddress)
external
override
onlyOwner
{
require(_feeAddress != address(0), "0x0");
emit ChangedAddress(
"TREASURY",
address(treasuryAddress),
address(_feeAddress)
);
treasuryAddress = _feeAddress;
}
/**
* @notice Set max ETH cap for this strategy
* @dev Can only be called by the owner
* @param _cap ETH amount
*/
function setCap(uint256 _cap) external override onlyOwner {
emit ChangedValue("CAP", cap, _cap);
cap = _cap;
}
/**
* @notice Set lock time
* @dev Can only be called by the owner
* @param _lockTime lock time in seconds
*/
function setLockTime(uint256 _lockTime) external override onlyOwner {
require(_lockTime > 0, "TIME_0");
emit ChangedValue("LOCKTIME", lockTime, _lockTime);
lockTime = _lockTime;
}
function setFeeAddress(address payable _feeAddress)
external
override
onlyOwner
{
emit ChangedAddress("FEE", address(feeAddress), address(_feeAddress));
feeAddress = _feeAddress;
}
function setFee(uint256 _fee) external override onlyOwner {
require(_fee <= uint256(9000), "FEE_TOO_HIGH");
emit ChangedValue("FEE", fee, _fee);
}
/**
* @notice Rescue dust resulted from swaps/liquidity
* @dev Can only be called by the owner
*/
function rescueDust() external override onlyOwner {
if (ethDust > 0) {
safeTransferETH(treasuryAddress, ethDust);
treasueryEthDust = treasueryEthDust.add(ethDust);
emit RescuedDust("ETH", ethDust);
ethDust = 0;
}
}
/**
* @notice Rescue any non-reward token that was airdropped to this contract
* @dev Can only be called by the owner
*/
function rescueAirdroppedTokens(address _token, address to)
external
override
onlyOwner
{
require(_token != farmToken, "rescue_reward_error");
uint256 balanceOfToken = IERC20(_token).balanceOf(address(this));
require(balanceOfToken > 0, "balance_0");
require(IERC20(_token).transfer(to, balanceOfToken), "rescue_failed");
}
/// @notice Transfer rewards to this strategy
function updateReward() external override onlyOwner {
harvestRewardPool.getReward();
}
//-----------------------------------------------------------------------------------------------------------------//
//------------------------------------ View methods -------------------------------------------------//
//-----------------------------------------------------------------------------------------------------------------//
/**
* @notice Check if user can withdraw based on current lock time
* @param user Address of the user
* @return true or false
*/
function isWithdrawalAvailable(address user) public view returns (bool) {
if (lockTime > 0) {
return userInfo[user].timestamp.add(lockTime) <= block.timestamp;
}
return true;
}
/**
* @notice View function to see pending rewards for account.
* @param account user account to check
* @return pending rewards
*/
function getPendingRewards(address account) public view returns (uint256) {
if (account != address(0)) {
if (userInfo[account].amountfToken == 0) {
return 0;
}
return
_earned(
userInfo[account].amountfToken,
userInfo[account].userRewardPerTokenPaid,
userInfo[account].rewards
);
}
return 0;
}
//-----------------------------------------------------------------------------------------------------------------//
//------------------------------------ Internal methods -------------------------------------------------//
//-----------------------------------------------------------------------------------------------------------------//
function _calculateRewards(
address account,
uint256 amount,
uint256 amountfToken
) internal view returns (uint256) {
uint256 rewards = userInfo[account].rewards;
uint256 farmBalance = IERC20(farmToken).balanceOf(address(this));
if (amount == 0) {
if (rewards < farmBalance) {
return rewards;
}
return farmBalance;
}
return (amount.mul(rewards)).div(amountfToken);
}
function _updateRewards(address account) internal {
if (account != address(0)) {
UserInfo storage user = userInfo[account];
uint256 _stored = harvestRewardPool.rewardPerToken();
user.rewards = _earned(
user.amountfToken,
user.userRewardPerTokenPaid,
user.rewards
);
user.userRewardPerTokenPaid = _stored;
}
}
function _earned(
uint256 _amountfToken,
uint256 _userRewardPerTokenPaid,
uint256 _rewards
) internal view returns (uint256) {
return
_amountfToken
.mul(
harvestRewardPool.rewardPerToken().sub(_userRewardPerTokenPaid)
)
.div(1e18)
.add(_rewards);
}
function _validateWithdraw(
uint256 deadline,
uint256 amount,
uint256 amountfToken,
uint256 receiptBalance,
uint256 timestamp,
uint256 slippage
) internal view {
_validateCommon(deadline, amount, slippage);
require(amountfToken >= amount, "AMOUNT_GREATER_THAN_BALANCE");
require(receiptBalance >= amountfToken, "RECEIPT_AMOUNT");
if (lockTime > 0) {
require(timestamp.add(lockTime) <= block.timestamp, "LOCK_TIME");
}
}
function _depositTokenToHarvestVault(uint256 amount)
internal
returns (uint256)
{
_increaseAllowance(token, address(harvestRewardVault), amount);
uint256 prevfTokenBalance = _getBalance(harvestfToken);
harvestRewardVault.deposit(amount);
uint256 currentfTokenBalance = _getBalance(harvestfToken);
require(
currentfTokenBalance > prevfTokenBalance,
"DEPOSIT_VAULT_ERROR"
);
return currentfTokenBalance.sub(prevfTokenBalance);
}
function _withdrawTokenFromHarvestVault(uint256 amount)
internal
returns (uint256)
{
_increaseAllowance(harvestfToken, address(harvestRewardVault), amount);
uint256 prevTokenBalance = _getBalance(token);
harvestRewardVault.withdraw(amount);
uint256 currentTokenBalance = _getBalance(token);
require(currentTokenBalance > prevTokenBalance, "WITHDRAW_VAULT_ERROR");
return currentTokenBalance.sub(prevTokenBalance);
}
function _stakefTokenToHarvestPool(uint256 amount) internal {
_increaseAllowance(harvestfToken, address(harvestRewardPool), amount);
harvestRewardPool.stake(amount);
}
function _unstakefTokenFromHarvestPool(uint256 amount)
internal
returns (uint256)
{
_increaseAllowance(harvestfToken, address(harvestRewardPool), amount);
uint256 prevfTokenBalance = _getBalance(harvestfToken);
harvestRewardPool.withdraw(amount);
uint256 currentfTokenBalance = _getBalance(harvestfToken);
require(
currentfTokenBalance > prevfTokenBalance,
"WITHDRAW_POOL_ERROR"
);
return currentfTokenBalance.sub(prevfTokenBalance);
}
function _calculatefTokenRemainings(uint256 amount, uint256 amountfToken)
internal
pure
returns (uint256, uint256)
{
uint256 burnAmount = amount;
if (amount < amountfToken) {
amountfToken = amountfToken.sub(amount);
} else {
burnAmount = amountfToken;
amountfToken = 0;
}
return (amountfToken, burnAmount);
}
function _calculateFeeableTokens(
uint256 amountfToken,
uint256 obtainedToken,
uint256 amountToken,
uint256 obtainedfToken,
uint256 underlyingRatio
) internal returns (uint256 feeableToken, uint256 earnedTokens) {
if (obtainedfToken == amountfToken) {
//there is no point to do the ratio math as we can just get the difference between current obtained tokens and initial obtained tokens
if (obtainedToken > amountToken) {
feeableToken = obtainedToken.sub(amountToken);
}
} else {
uint256 currentRatio = _getRatio(obtainedfToken, obtainedToken, 18);
if (currentRatio < underlyingRatio) {
uint256 noOfOriginalTokensForCurrentAmount =
(obtainedfToken.mul(10**18)).div(underlyingRatio);
if (noOfOriginalTokensForCurrentAmount < obtainedToken) {
feeableToken = obtainedToken.sub(
noOfOriginalTokensForCurrentAmount
);
}
}
}
if (feeableToken > 0) {
uint256 extraTokensFee = _calculateFee(feeableToken);
emit ExtraTokens(msg.sender, feeableToken.sub(extraTokensFee));
earnedTokens = feeableToken.sub(extraTokensFee);
}
}
receive() external payable {}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
import "./HarvestBase.sol";
contract HarvestSCBase is StrategyBase, HarvestBase {
//-----------------------------------------------------------------------------------------------------------------//
//------------------------------------ Events -------------------------------------------------//
//-----------------------------------------------------------------------------------------------------------------//
/// @notice Event emitted when rewards are exchanged to ETH or to a specific Token
event RewardsExchanged(
address indexed user,
string exchangeType, //ETH or Token
uint256 rewardsAmount,
uint256 obtainedAmount
);
/// @notice Event emitted when user makes a deposit
event Deposit(
address indexed user,
address indexed origin,
uint256 amountToken,
uint256 amountfToken
);
/// @notice Event emitted when user withdraws
event Withdraw(
address indexed user,
address indexed origin,
uint256 amountToken,
uint256 amountfToken,
uint256 treasuryAmountEth
);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
import "../../../interfaces/IMintNoRewardPool.sol";
import "../../../interfaces/IHarvestVault.sol";
contract HarvestStorage {
/// @notice Info of each user.
struct UserInfo {
uint256 amountEth; //how much ETH the user entered with; should be 0 for HarvestSC
uint256 amountToken; //how much Token was obtained by swapping user's ETH
uint256 amountfToken; //how much fToken was obtained after deposit to vault
uint256 underlyingRatio; //ratio between obtained fToken and token
uint256 userTreasuryEth; //how much eth the user sent to treasury
uint256 userCollectedFees; //how much eth the user sent to fee address
uint256 timestamp; //first deposit timestamp; used for withdrawal lock time check
uint256 earnedTokens;
uint256 earnedRewards; //before fees
//----
uint256 rewards;
uint256 userRewardPerTokenPaid;
}
uint256 public totalToken;
address public farmToken;
address public harvestfToken;
uint256 public ethDust;
uint256 public treasueryEthDust;
IMintNoRewardPool public harvestRewardPool;
IHarvestVault public harvestRewardVault;
mapping(address => UserInfo) public userInfo;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
import "../../tokens/ReceiptToken.sol";
import "../../interfaces/IUniswapRouter.sol";
contract Storage{
address public weth;
address payable public treasuryAddress;
address payable public feeAddress;
address public token;
IUniswapRouter public sushiswapRouter;
ReceiptToken public receiptToken;
uint256 internal _minSlippage;
uint256 public lockTime;
uint256 public fee;
uint256 constant feeFactor = uint256(10000);
uint256 public cap;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "../../tokens/ReceiptToken.sol";
import "../../interfaces/IUniswapRouter.sol";
import "./Storage.sol";
contract StrategyBase is Storage, Initializable, UUPSUpgradeable, OwnableUpgradeable{
using SafeMath for uint256;
using SafeERC20 for IERC20;
/// @notice Event emitted when user makes a deposit and receipt token is minted
event ReceiptMinted(address indexed user, uint256 amount);
/// @notice Event emitted when user withdraws and receipt token is burned
event ReceiptBurned(address indexed user, uint256 amount);
/**
* @notice Create a new strategy contract
* @param _sushiswapRouter Sushiswap Router address
* @param _token Token address
* @param _weth WETH address
* @param _treasuryAddress treasury address
* @param _feeAddress fee address
*/
function __StrategyBase_init(
address _sushiswapRouter, address _token,
address _weth,
address payable _treasuryAddress,
address payable _feeAddress,
uint256 _cap) internal initializer {
require(_sushiswapRouter != address(0), "ROUTER_0x0");
require(_token != address(0), "TOKEN_0x0");
require(_weth != address(0), "WETH_0x0");
require(_treasuryAddress != address(0), "TREASURY_0x0");
require(_feeAddress != address(0), "FEE_0x0");
sushiswapRouter = IUniswapRouter(_sushiswapRouter);
token = _token;
weth = _weth;
treasuryAddress = _treasuryAddress;
feeAddress = _feeAddress;
cap = _cap;
_minSlippage = 10; //0.1%
lockTime = 1;
fee = uint256(100);
__Ownable_init();
}
function _authorizeUpgrade(address) internal override onlyOwner {
}
function _validateCommon(
uint256 deadline,
uint256 amount,
uint256 _slippage
) internal view {
require(deadline >= block.timestamp, "DEADLINE_ERROR");
require(amount > 0, "AMOUNT_0");
require(_slippage >= _minSlippage, "SLIPPAGE_ERROR");
require(_slippage <= feeFactor, "MAX_SLIPPAGE_ERROR");
}
function _validateDeposit(
uint256 deadline,
uint256 amount,
uint256 total,
uint256 slippage
) internal view {
_validateCommon(deadline, amount, slippage);
require(total.add(amount) <= cap, "CAP_REACHED");
}
function _mintParachainAuctionTokens(uint256 _amount) internal {
receiptToken.mint(msg.sender, _amount);
emit ReceiptMinted(msg.sender, _amount);
}
function _burnParachainAuctionTokens(uint256 _amount) internal {
receiptToken.burn(msg.sender, _amount);
emit ReceiptBurned(msg.sender, _amount);
}
function _calculateFee(uint256 _amount) internal view returns (uint256) {
return _calculatePortion(_amount, fee);
}
function _getBalance(address _token) internal view returns (uint256) {
return IERC20(_token).balanceOf(address(this));
}
function _increaseAllowance(
address _token,
address _contract,
uint256 _amount
) internal {
IERC20(_token).safeIncreaseAllowance(address(_contract), _amount);
}
function _getRatio(
uint256 numerator,
uint256 denominator,
uint256 precision
) internal pure returns (uint256) {
if (numerator == 0 || denominator == 0) {
return 0;
}
uint256 _numerator = numerator * 10**(precision + 1);
uint256 _quotient = ((_numerator / denominator) + 5) / 10;
return (_quotient);
}
function _swapTokenToEth(
address[] memory swapPath,
uint256 exchangeAmount,
uint256 deadline,
uint256 slippage,
uint256 ethPerToken
) internal returns (uint256) {
uint256[] memory amounts =
sushiswapRouter.getAmountsOut(exchangeAmount, swapPath);
uint256 sushiAmount = amounts[amounts.length - 1]; //amount of ETH
uint256 portion = _calculatePortion(sushiAmount, slippage);
uint256 calculatedPrice = (exchangeAmount.mul(ethPerToken)).div(10**18);
uint256 decimals = ERC20(swapPath[0]).decimals();
if (decimals < 18) {
calculatedPrice = calculatedPrice.mul(10**(18 - decimals));
}
if (sushiAmount > calculatedPrice) {
require(
sushiAmount.sub(calculatedPrice) <= portion,
"PRICE_ERROR_1"
);
} else {
require(
calculatedPrice.sub(sushiAmount) <= portion,
"PRICE_ERROR_2"
);
}
_increaseAllowance(
swapPath[0],
address(sushiswapRouter),
exchangeAmount
);
uint256[] memory tokenSwapAmounts =
sushiswapRouter.swapExactTokensForETH(
exchangeAmount,
_getMinAmount(sushiAmount, slippage),
swapPath,
address(this),
deadline
);
return tokenSwapAmounts[tokenSwapAmounts.length - 1];
}
function _swapEthToToken(
address[] memory swapPath,
uint256 exchangeAmount,
uint256 deadline,
uint256 slippage,
uint256 tokensPerEth
) internal returns (uint256) {
uint256[] memory amounts =
sushiswapRouter.getAmountsOut(exchangeAmount, swapPath);
uint256 sushiAmount = amounts[amounts.length - 1];
uint256 portion = _calculatePortion(sushiAmount, slippage);
uint256 calculatedPrice =
(exchangeAmount.mul(tokensPerEth)).div(10**18);
uint256 decimals = ERC20(swapPath[0]).decimals();
if (decimals < 18) {
calculatedPrice = calculatedPrice.mul(10**(18 - decimals));
}
if (sushiAmount > calculatedPrice) {
require(
sushiAmount.sub(calculatedPrice) <= portion,
"PRICE_ERROR_1"
);
} else {
require(
calculatedPrice.sub(sushiAmount) <= portion,
"PRICE_ERROR_2"
);
}
uint256[] memory swapResult =
sushiswapRouter.swapExactETHForTokens{value: exchangeAmount}(
_getMinAmount(sushiAmount, slippage),
swapPath,
address(this),
deadline
);
return swapResult[swapResult.length - 1];
}
function _getMinAmount(uint256 amount, uint256 slippage)
private
pure
returns (uint256)
{
uint256 portion = _calculatePortion(amount, slippage);
return amount.sub(portion);
}
function _calculatePortion(uint256 _amount, uint256 _fee)
private
pure
returns (uint256)
{
return (_amount.mul(_fee)).div(feeFactor);
}
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, "TransferHelper: ETH_TRANSFER_FAILED");
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
// This contract is used for printing receipt tokens
// Whenever someone joins a pool, a receipt token will be printed for that person
contract ReceiptToken is ERC20, Ownable {
ERC20 public underlyingToken;
address public underlyingStrategy;
constructor(address underlyingAddress, address strategy)
ERC20(
string(abi.encodePacked("pAT-", ERC20(underlyingAddress).name())),
string(abi.encodePacked("pAT-", ERC20(underlyingAddress).symbol()))
)
{
underlyingToken = ERC20(underlyingAddress);
underlyingStrategy = strategy;
}
/**
* @notice Mint new receipt tokens to some user
* @param to Address of the user that gets the receipt tokens
* @param amount Amount of receipt tokens that will get minted
*/
function mint(address to, uint256 amount) public onlyOwner {
_mint(to, amount);
}
/**
* @notice Burn receipt tokens from some user
* @param from Address of the user that gets the receipt tokens burne
* @param amount Amount of receipt tokens that will get burned
*/
function burn(address from, uint256 amount) public onlyOwner {
_burn(from, amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.2;
import "../beacon/IBeaconUpgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/StorageSlotUpgradeable.sol";
import "../utils/Initializable.sol";
/**
* @dev This abstract contract provides getters and event emitting update functions for
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
*
* _Available since v4.1._
*
* @custom:oz-upgrades-unsafe-allow delegatecall
*/
abstract contract ERC1967UpgradeUpgradeable is Initializable {
function __ERC1967Upgrade_init() internal initializer {
__ERC1967Upgrade_init_unchained();
}
function __ERC1967Upgrade_init_unchained() internal initializer {
}
// This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1
bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Returns the current implementation address.
*/
function _getImplementation() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
require(AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract");
StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
}
/**
* @dev Perform implementation upgrade
*
* Emits an {Upgraded} event.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Perform implementation upgrade with additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCall(address newImplementation, bytes memory data, bool forceCall) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
if (data.length > 0 || forceCall) {
_functionDelegateCall(newImplementation, data);
}
}
/**
* @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCallSecure(address newImplementation, bytes memory data, bool forceCall) internal {
address oldImplementation = _getImplementation();
// Initial upgrade and setup call
_setImplementation(newImplementation);
if (data.length > 0 || forceCall) {
_functionDelegateCall(newImplementation, data);
}
// Perform rollback test if not already in progress
StorageSlotUpgradeable.BooleanSlot storage rollbackTesting = StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT);
if (!rollbackTesting.value) {
// Trigger rollback using upgradeTo from the new implementation
rollbackTesting.value = true;
_functionDelegateCall(
newImplementation,
abi.encodeWithSignature(
"upgradeTo(address)",
oldImplementation
)
);
rollbackTesting.value = false;
// Check rollback was effective
require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades");
// Finally reset to the new implementation and log the upgrade
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
}
/**
* @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does
* not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).
*
* Emits a {BeaconUpgraded} event.
*/
function _upgradeBeaconToAndCall(address newBeacon, bytes memory data, bool forceCall) internal {
_setBeacon(newBeacon);
emit BeaconUpgraded(newBeacon);
if (data.length > 0 || forceCall) {
_functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data);
}
}
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Returns the current admin.
*/
function _getAdmin() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
require(newAdmin != address(0), "ERC1967: new admin is the zero address");
StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {AdminChanged} event.
*/
function _changeAdmin(address newAdmin) internal {
emit AdminChanged(_getAdmin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
* This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.
*/
bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/**
* @dev Emitted when the beacon is upgraded.
*/
event BeaconUpgraded(address indexed beacon);
/**
* @dev Returns the current beacon.
*/
function _getBeacon() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value;
}
/**
* @dev Stores a new beacon in the EIP1967 beacon slot.
*/
function _setBeacon(address newBeacon) private {
require(
AddressUpgradeable.isContract(newBeacon),
"ERC1967: new beacon is not a contract"
);
require(
AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()),
"ERC1967: beacon implementation is not a contract"
);
StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon;
}
/*
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function _functionDelegateCall(address target, bytes memory data) private returns (bytes memory) {
require(AddressUpgradeable.isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, "Address: low-level delegate call failed");
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev This is the interface that {BeaconProxy} expects of its beacon.
*/
interface IBeaconUpgradeable {
/**
* @dev Must return an address that can be used as a delegate call target.
*
* {BeaconProxy} will check that this address is a contract.
*/
function implementation() external view returns (address);
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC1967/ERC1967UpgradeUpgradeable.sol";
import "./Initializable.sol";
/**
* @dev Base contract for building openzeppelin-upgrades compatible implementations for the {ERC1967Proxy}. It includes
* publicly available upgrade functions that are called by the plugin and by the secure upgrade mechanism to verify
* continuation of the upgradability.
*
* The {_authorizeUpgrade} function MUST be overridden to include access restriction to the upgrade mechanism.
*
* _Available since v4.1._
*/
abstract contract UUPSUpgradeable is Initializable, ERC1967UpgradeUpgradeable {
function __UUPSUpgradeable_init() internal initializer {
__ERC1967Upgrade_init_unchained();
__UUPSUpgradeable_init_unchained();
}
function __UUPSUpgradeable_init_unchained() internal initializer {
}
function upgradeTo(address newImplementation) external virtual {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallSecure(newImplementation, bytes(""), false);
}
function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallSecure(newImplementation, data, true);
}
function _authorizeUpgrade(address newImplementation) internal virtual;
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
function __ReentrancyGuard_init() internal initializer {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal initializer {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC1967 implementation slot:
* ```
* contract ERC1967 {
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._
*/
library StorageSlotUpgradeable {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
assembly {
r.slot := slot
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
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 defaut 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");
_approve(sender, _msgSender(), currentAllowance - amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
_balances[sender] = senderBalance - amount;
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
_balances[account] = accountBalance - amount;
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// 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 "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev 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.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
|
Create a new HarvestDAI contract _harvestRewardVault VaultToken address _harvestRewardPool NoMintRewardPool address _sushiswapRouter Sushiswap Router address _harvestfToken Pool's underlying token address _farmToken Farm address _token Token address _weth WETH address _treasuryAddress treasury address _feeAddress fee address/
|
function __HarvestBase_init(
address _harvestRewardVault,
address _harvestRewardPool,
address _sushiswapRouter,
address _harvestfToken,
address _farmToken,
address _token,
address _weth,
address payable _treasuryAddress,
address payable _feeAddress,
uint256 _cap
) internal initializer {
require(_harvestRewardVault != address(0), "VAULT_0x0");
require(_harvestRewardPool != address(0), "POOL_0x0");
require(_harvestfToken != address(0), "fTOKEN_0x0");
require(_farmToken != address(0), "FARM_0x0");
__Ownable_init();
__StrategyBase_init(
_sushiswapRouter,
_token,
_weth,
_treasuryAddress,
_feeAddress,
_cap
);
harvestRewardVault = IHarvestVault(_harvestRewardVault);
harvestRewardPool = IMintNoRewardPool(_harvestRewardPool);
harvestfToken = _harvestfToken;
farmToken = _farmToken;
receiptToken = new ReceiptToken(token, address(this));
}
| 11,767,002 |
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.7.5;
pragma abicoder v2;
import './TimelockExecutorBase.sol';
contract ArcTimelock is TimelockExecutorBase {
address private _ethereumGovernanceExecutor;
event EthereumGovernanceExecutorUpdate(
address previousEthereumGovernanceExecutor,
address newEthereumGovernanceExecutor
);
modifier onlyEthereumGovernanceExecutor() {
require(msg.sender == _ethereumGovernanceExecutor, 'UNAUTHORIZED_EXECUTOR');
_;
}
constructor(
address ethereumGovernanceExecutor,
uint256 delay,
uint256 gracePeriod,
uint256 minimumDelay,
uint256 maximumDelay,
address guardian
) TimelockExecutorBase(delay, gracePeriod, minimumDelay, maximumDelay, guardian) {
_ethereumGovernanceExecutor = ethereumGovernanceExecutor;
}
/**
* @dev Queue the message in the Executor
* @param targets list of contracts called by each action's associated transaction
* @param values list of value in wei for each action's associated transaction
* @param signatures list of function signatures (can be empty) to be used when created the callData
* @param calldatas list of calldatas: if associated signature empty, calldata ready, else calldata is arguments
* @param withDelegatecalls boolean, true = transaction delegatecalls the taget, else calls the target
**/
function queue(
address[] memory targets,
uint256[] memory values,
string[] memory signatures,
bytes[] memory calldatas,
bool[] memory withDelegatecalls
) external onlyEthereumGovernanceExecutor {
_queue(targets, values, signatures, calldatas, withDelegatecalls);
}
/**
* @dev Update the address of the Ethereum Governance Executor contract responsible for sending transactions to ARC
* @param ethereumGovernanceExecutor the address of the Ethereum Governance Executor contract
**/
function updateEthereumGovernanceExecutor(address ethereumGovernanceExecutor) external onlyThis {
emit EthereumGovernanceExecutorUpdate(_ethereumGovernanceExecutor, ethereumGovernanceExecutor);
_ethereumGovernanceExecutor = ethereumGovernanceExecutor;
}
/**
* @dev get the current address of ethereumGovernanceExecutor
* @return the address of the Ethereum Governance Executor contract
**/
function getEthereumGovernanceExecutor() external view returns (address) {
return _ethereumGovernanceExecutor;
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.7.5;
pragma abicoder v2;
import '../dependencies/SafeMath.sol';
import '../interfaces/ITimelockExecutor.sol';
abstract contract TimelockExecutorBase is ITimelockExecutor {
using SafeMath for uint256;
uint256 private _delay;
uint256 private _gracePeriod;
uint256 private _minimumDelay;
uint256 private _maximumDelay;
address private _guardian;
uint256 private _actionsSetCounter;
mapping(uint256 => ActionsSet) private _actionsSets;
mapping(bytes32 => bool) private _queuedActions;
modifier onlyGuardian() {
require(msg.sender == _guardian, 'ONLY_BY_GUARDIAN');
_;
}
modifier onlyThis() {
require(msg.sender == address(this), 'UNAUTHORIZED_ORIGIN_ONLY_THIS');
_;
}
constructor(
uint256 delay,
uint256 gracePeriod,
uint256 minimumDelay,
uint256 maximumDelay,
address guardian
) {
require(delay >= minimumDelay, 'DELAY_SHORTER_THAN_MINIMUM');
require(delay <= maximumDelay, 'DELAY_LONGER_THAN_MAXIMUM');
_delay = delay;
_gracePeriod = gracePeriod;
_minimumDelay = minimumDelay;
_maximumDelay = maximumDelay;
_guardian = guardian;
}
/// @inheritdoc ITimelockExecutor
function execute(uint256 actionsSetId) external payable override {
require(getCurrentState(actionsSetId) == ActionsSetState.Queued, 'ONLY_QUEUED_ACTIONS');
ActionsSet storage actionsSet = _actionsSets[actionsSetId];
require(block.timestamp >= actionsSet.executionTime, 'TIMELOCK_NOT_FINISHED');
actionsSet.executed = true;
uint256 actionCount = actionsSet.targets.length;
bytes[] memory returnedData = new bytes[](actionCount);
for (uint256 i = 0; i < actionCount; i++) {
returnedData[i] = _executeTransaction(
actionsSet.targets[i],
actionsSet.values[i],
actionsSet.signatures[i],
actionsSet.calldatas[i],
actionsSet.executionTime,
actionsSet.withDelegatecalls[i]
);
}
emit ActionsSetExecuted(actionsSetId, msg.sender, returnedData);
}
/// @inheritdoc ITimelockExecutor
function cancel(uint256 actionsSetId) external override onlyGuardian {
ActionsSetState state = getCurrentState(actionsSetId);
require(state == ActionsSetState.Queued, 'ONLY_BEFORE_EXECUTED');
ActionsSet storage actionsSet = _actionsSets[actionsSetId];
actionsSet.canceled = true;
for (uint256 i = 0; i < actionsSet.targets.length; i++) {
_cancelTransaction(
actionsSet.targets[i],
actionsSet.values[i],
actionsSet.signatures[i],
actionsSet.calldatas[i],
actionsSet.executionTime,
actionsSet.withDelegatecalls[i]
);
}
emit ActionsSetCanceled(actionsSetId);
}
/// @inheritdoc ITimelockExecutor
function getActionsSetById(uint256 actionsSetId)
external
view
override
returns (ActionsSet memory)
{
return _actionsSets[actionsSetId];
}
/// @inheritdoc ITimelockExecutor
function getCurrentState(uint256 actionsSetId) public view override returns (ActionsSetState) {
require(_actionsSetCounter >= actionsSetId, 'INVALID_ACTION_ID');
ActionsSet storage actionsSet = _actionsSets[actionsSetId];
if (actionsSet.canceled) {
return ActionsSetState.Canceled;
} else if (actionsSet.executed) {
return ActionsSetState.Executed;
} else if (block.timestamp > actionsSet.executionTime.add(_gracePeriod)) {
return ActionsSetState.Expired;
} else {
return ActionsSetState.Queued;
}
}
/// @inheritdoc ITimelockExecutor
function isActionQueued(bytes32 actionHash) public view override returns (bool) {
return _queuedActions[actionHash];
}
function receiveFunds() external payable {}
/// @inheritdoc ITimelockExecutor
function updateGuardian(address guardian) external override onlyThis {
emit GuardianUpdate(_guardian, guardian);
_guardian = guardian;
}
/// @inheritdoc ITimelockExecutor
function updateDelay(uint256 delay) external override onlyThis {
_validateDelay(delay);
emit DelayUpdate(_delay, delay);
_delay = delay;
}
/// @inheritdoc ITimelockExecutor
function updateGracePeriod(uint256 gracePeriod) external override onlyThis {
emit GracePeriodUpdate(_gracePeriod, gracePeriod);
_gracePeriod = gracePeriod;
}
/// @inheritdoc ITimelockExecutor
function updateMinimumDelay(uint256 minimumDelay) external override onlyThis {
uint256 previousMinimumDelay = _minimumDelay;
_minimumDelay = minimumDelay;
_validateDelay(_delay);
emit MinimumDelayUpdate(previousMinimumDelay, minimumDelay);
}
/// @inheritdoc ITimelockExecutor
function updateMaximumDelay(uint256 maximumDelay) external override onlyThis {
uint256 previousMaximumDelay = _maximumDelay;
_maximumDelay = maximumDelay;
_validateDelay(_delay);
emit MaximumDelayUpdate(previousMaximumDelay, maximumDelay);
}
/// @inheritdoc ITimelockExecutor
function getDelay() external view override returns (uint256) {
return _delay;
}
/// @inheritdoc ITimelockExecutor
function getGracePeriod() external view override returns (uint256) {
return _gracePeriod;
}
/// @inheritdoc ITimelockExecutor
function getMinimumDelay() external view override returns (uint256) {
return _minimumDelay;
}
/// @inheritdoc ITimelockExecutor
function getMaximumDelay() external view override returns (uint256) {
return _maximumDelay;
}
/// @inheritdoc ITimelockExecutor
function getGuardian() external view override returns (address) {
return _guardian;
}
/// @inheritdoc ITimelockExecutor
function getActionsSetCount() external view override returns (uint256) {
return _actionsSetCounter;
}
/**
* @dev target.delegatecall cannot be provided a value directly and is sent
* with the entire available msg.value. In this instance, we only want each proposed action
* to execute with exactly the value defined in the proposal. By splitting executeDelegateCall
* into a seperate function, it can be called from this contract with a defined amout of value,
* reducing the risk that a delegatecall is executed with more value than intended
* @return success - boolean indicating it the delegate call was successfull
* @return resultdata - bytes returned by the delegate call
**/
function executeDelegateCall(address target, bytes calldata data)
external
payable
onlyThis
returns (bool, bytes memory)
{
bool success;
bytes memory resultData;
// solium-disable-next-line security/no-call-value
(success, resultData) = target.delegatecall(data);
return (success, resultData);
}
/**
* @dev Queue the ActionsSet
* @param targets list of contracts called by each action's associated transaction
* @param values list of value in wei for each action's associated transaction
* @param signatures list of function signatures (can be empty) to be used when created the callData
* @param calldatas list of calldatas: if associated signature empty, calldata ready, else calldata is arguments
* @param withDelegatecalls boolean, true = transaction delegatecalls the taget, else calls the target
**/
function _queue(
address[] memory targets,
uint256[] memory values,
string[] memory signatures,
bytes[] memory calldatas,
bool[] memory withDelegatecalls
) internal {
require(targets.length != 0, 'INVALID_EMPTY_TARGETS');
require(
targets.length == values.length &&
targets.length == signatures.length &&
targets.length == calldatas.length &&
targets.length == withDelegatecalls.length,
'INCONSISTENT_PARAMS_LENGTH'
);
uint256 actionsSetId = _actionsSetCounter;
uint256 executionTime = block.timestamp.add(_delay);
_actionsSetCounter++;
for (uint256 i = 0; i < targets.length; i++) {
bytes32 actionHash =
keccak256(
abi.encode(
targets[i],
values[i],
signatures[i],
calldatas[i],
executionTime,
withDelegatecalls[i]
)
);
require(!isActionQueued(actionHash), 'DUPLICATED_ACTION');
_queuedActions[actionHash] = true;
}
ActionsSet storage actionsSet = _actionsSets[actionsSetId];
actionsSet.targets = targets;
actionsSet.values = values;
actionsSet.signatures = signatures;
actionsSet.calldatas = calldatas;
actionsSet.withDelegatecalls = withDelegatecalls;
actionsSet.executionTime = executionTime;
emit ActionsSetQueued(
actionsSetId,
targets,
values,
signatures,
calldatas,
withDelegatecalls,
executionTime
);
}
function _executeTransaction(
address target,
uint256 value,
string memory signature,
bytes memory data,
uint256 executionTime,
bool withDelegatecall
) internal returns (bytes memory) {
require(address(this).balance >= value, 'NOT_ENOUGH_CONTRACT_BALANCE');
bytes32 actionHash =
keccak256(abi.encode(target, value, signature, data, executionTime, withDelegatecall));
_queuedActions[actionHash] = false;
bytes memory callData;
if (bytes(signature).length == 0) {
callData = data;
} else {
callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), data);
}
bool success;
bytes memory resultData;
if (withDelegatecall) {
(success, resultData) = this.executeDelegateCall{value: value}(target, callData);
} else {
// solium-disable-next-line security/no-call-value
(success, resultData) = target.call{value: value}(callData);
}
return _verifyCallResult(success, resultData);
}
function _cancelTransaction(
address target,
uint256 value,
string memory signature,
bytes memory data,
uint256 executionTime,
bool withDelegatecall
) internal {
bytes32 actionHash =
keccak256(abi.encode(target, value, signature, data, executionTime, withDelegatecall));
_queuedActions[actionHash] = false;
}
function _validateDelay(uint256 delay) internal view {
require(delay >= _minimumDelay, 'DELAY_SHORTER_THAN_MINIMUM');
require(delay <= _maximumDelay, 'DELAY_LONGER_THAN_MAXIMUM');
}
function _verifyCallResult(bool success, bytes memory returndata)
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('FAILED_ACTION_EXECUTION');
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
/**
* @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) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, 'SafeMath: modulo by zero');
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
//SPDX-License-Identifier: Unlicense
pragma solidity 0.7.5;
pragma abicoder v2;
interface ITimelockExecutor {
enum ActionsSetState {
Queued,
Executed,
Canceled,
Expired
}
struct ActionsSet {
address[] targets;
uint256[] values;
string[] signatures;
bytes[] calldatas;
bool[] withDelegatecalls;
uint256 executionTime;
bool executed;
bool canceled;
}
/**
* @dev emitted when an ActionsSet is queued
* @param id Id of the ActionsSet
* @param targets list of contracts called by each action's associated transaction
* @param values list of value in wei for each action's associated transaction
* @param signatures list of function signatures (can be empty) to be used when created the callData
* @param calldatas list of calldatas: if associated signature empty, calldata ready, else calldata is arguments
* @param withDelegatecalls boolean, true = transaction delegatecalls the taget, else calls the target
* @param executionTime the time these actions can be executed
**/
event ActionsSetQueued(
uint256 id,
address[] targets,
uint256[] values,
string[] signatures,
bytes[] calldatas,
bool[] withDelegatecalls,
uint256 executionTime
);
/**
* @dev emitted when an ActionsSet is executed successfully
* @param id Id of the ActionsSet
* @param initiatorExecution address that triggered the ActionsSet execution
* @param returnedData returned data from the ActionsSet execution
**/
event ActionsSetExecuted(uint256 id, address indexed initiatorExecution, bytes[] returnedData);
/**
* @dev emitted when an ActionsSet is cancelled by the guardian
* @param id Id of the ActionsSet
**/
event ActionsSetCanceled(uint256 id);
/**
* @dev emitted when a new guardian is set
* @param previousGuardian previous guardian
* @param newGuardian new guardian
**/
event GuardianUpdate(address previousGuardian, address newGuardian);
/**
* @dev emitted when a new delay (between queueing and execution) is set
* @param previousDelay previous delay
* @param newDelay new delay
**/
event DelayUpdate(uint256 previousDelay, uint256 newDelay);
/**
* @dev emitted when a GracePeriod is updated
* @param previousGracePeriod previous grace period
* @param newGracePeriod new grace period
**/
event GracePeriodUpdate(uint256 previousGracePeriod, uint256 newGracePeriod);
/**
* @dev emitted when a Minimum Delay is updated
* @param previousMinimumDelay previous minimum delay
* @param newMinimumDelay new minimum delay
**/
event MinimumDelayUpdate(uint256 previousMinimumDelay, uint256 newMinimumDelay);
/**
* @dev emitted when a Maximum Delay is updated
* @param previousMaximumDelay previous maximum delay
* @param newMaximumDelay new maximum delay
**/
event MaximumDelayUpdate(uint256 previousMaximumDelay, uint256 newMaximumDelay);
/**
* @dev Execute the ActionsSet
* @param actionsSetId id of the ActionsSet to execute
**/
function execute(uint256 actionsSetId) external payable;
/**
* @dev Cancel the ActionsSet
* @param actionsSetId id of the ActionsSet to cancel
**/
function cancel(uint256 actionsSetId) external;
/**
* @dev Get the ActionsSet by Id
* @param actionsSetId id of the ActionsSet
* @return the ActionsSet requested
**/
function getActionsSetById(uint256 actionsSetId) external view returns (ActionsSet memory);
/**
* @dev Get the current state of an ActionsSet
* @param actionsSetId id of the ActionsSet
* @return The current state of the ActionsSet
**/
function getCurrentState(uint256 actionsSetId) external view returns (ActionsSetState);
/**
* @dev Returns whether an action (via actionHash) is queued
* @param actionHash hash of the action to be checked
* keccak256(abi.encode(target, value, signature, data, executionTime, withDelegatecall))
* @return true if underlying action of actionHash is queued
**/
function isActionQueued(bytes32 actionHash) external view returns (bool);
/**
* @dev Update guardian
* @param guardian address of the new guardian
**/
function updateGuardian(address guardian) external;
/**
* @dev Update the delay
* @param delay delay between queue and execution of an ActionSet
**/
function updateDelay(uint256 delay) external;
/**
* @dev Set the grace period - time before a queued action will expire
* @param gracePeriod The gracePeriod in seconds
**/
function updateGracePeriod(uint256 gracePeriod) external;
/**
* @dev Set the minimum allowed delay between queing and exection
* @param minimumDelay The minimum delay in seconds
**/
function updateMinimumDelay(uint256 minimumDelay) external;
/**
* @dev Set the maximum allowed delay between queing and exection
* @param maximumDelay The maximum delay in seconds
**/
function updateMaximumDelay(uint256 maximumDelay) external;
/**
* @dev Getter of the delay between queuing and execution
* @return The delay in seconds
**/
function getDelay() external view returns (uint256);
/**
* @dev Getter of grace period constant
* @return grace period in seconds
**/
function getGracePeriod() external view returns (uint256);
/**
* @dev Getter of minimum delay constant
* @return minimum delay in seconds
**/
function getMinimumDelay() external view returns (uint256);
/**
* @dev Getter of maximum delay constant
* @return maximum delay in seconds
**/
function getMaximumDelay() external view returns (uint256);
/**
* @dev Get guardian address
* @return guardian address
**/
function getGuardian() external view returns (address);
/**
* @dev Get ActionSet count
* @return current count of action sets processed
**/
function getActionsSetCount() external view returns (uint256);
}
|
@inheritdoc ITimelockExecutor
|
function getActionsSetById(uint256 actionsSetId)
external
view
override
returns (ActionsSet memory)
{
return _actionsSets[actionsSetId];
}
| 148,724 |
// Flattener_Cratos_Jay
// File: @chainlink/contracts/src/v0.8/interfaces/KeeperCompatibleInterface.sol
pragma solidity ^0.8.0;
interface KeeperCompatibleInterface {
/**
* @notice method that is simulated by the keepers to see if any work actually
* needs to be performed. This method does does not actually need to be
* executable, and since it is only ever simulated it can consume lots of gas.
* @dev To ensure that it is never called, you may want to add the
* cannotExecute modifier from KeeperBase to your implementation of this
* method.
* @param checkData specified in the upkeep registration so it is always the
* same for a registered upkeep. This can easily be broken down into specific
* arguments using `abi.decode`, so multiple upkeeps can be registered on the
* same contract and easily differentiated by the contract.
* @return upkeepNeeded boolean to indicate whether the keeper should call
* performUpkeep or not.
* @return performData bytes that the keeper should call performUpkeep with, if
* upkeep is needed. If you would like to encode data to decode later, try
* `abi.encode`.
*/
function checkUpkeep(bytes calldata checkData) external returns (bool upkeepNeeded, bytes memory performData);
/**
* @notice method that is actually executed by the keepers, via the registry.
* The data returned by the checkUpkeep simulation will be passed into
* this method to actually be executed.
* @dev The input to this method should not be trusted, and the caller of the
* method should not even be restricted to any single registry. Anyone should
* be able call it, and the input should be validated, there is no guarantee
* that the data passed in is the performData returned from checkUpkeep. This
* could happen due to malicious keepers, racing keepers, or simply a state
* change while the performUpkeep transaction is waiting for confirmation.
* Always validate the data passed in.
* @param performData is the data which was passed back from the checkData
* simulation. If it is encoded, it can easily be decoded into other types by
* calling `abi.decode`. This data should not be trusted, and should be
* validated against the contract's current state.
*/
function performUpkeep(bytes calldata performData) external;
}
// File: @chainlink/contracts/src/v0.8/KeeperBase.sol
pragma solidity ^0.8.0;
contract KeeperBase {
error OnlySimulatedBackend();
/**
* @notice method that allows it to be simulated via eth_call by checking that
* the sender is the zero address.
*/
function preventExecution() internal view {
if (tx.origin != address(0)) {
revert OnlySimulatedBackend();
}
}
/**
* @notice modifier that allows it to be simulated via eth_call by checking
* that the sender is the zero address.
*/
modifier cannotExecute() {
preventExecution();
_;
}
}
// File: @chainlink/contracts/src/v0.8/KeeperCompatible.sol
pragma solidity ^0.8.0;
abstract contract KeeperCompatible is KeeperBase, KeeperCompatibleInterface {}
// File: @openzeppelin/contracts/utils/math/SafeMath.sol
// 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;
}
}
}
// File: @openzeppelin/contracts/utils/math/Math.sol
// 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 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.
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);
}
}
// File: @openzeppelin/contracts/utils/Context.sol
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File: @openzeppelin/contracts/security/ReentrancyGuard.sol
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// File: @openzeppelin/contracts/utils/Address.sol
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
// 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);
}
// File: @openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using 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");
}
}
}
// File: 3_Chainlink_Test/00.CRTS_Automation_Vesting_Keepers.sol
// contracts/TokenVesting.sol
pragma solidity 0.8.11;
/**
* @title TokenVesting
*/
contract CRTS_Token_Vesting is Ownable, ReentrancyGuard, KeeperCompatibleInterface{
using SafeMath for uint256;
using SafeERC20 for IERC20;
struct VestingSchedule{
bool initialized;
// beneficiary of tokens after they are released
address beneficiary;
// cliff period in seconds
uint256 cliff;
// start time of the vesting period
uint256 start;
// duration of the vesting period in seconds
uint256 duration;
// duration of a slice period for the vesting in seconds
uint256 slicePeriodSeconds;
// whether or not the vesting is revocable
bool revocable;
// total amount of tokens to be released at the end of the vesting
uint256 amountTotal;
// amount of tokens released
uint256 released;
// whether or not the vesting has been revoked
bool revoked;
}
// address of the ERC20 token
IERC20 immutable private _token;
bytes32[] private vestingSchedulesIds;
mapping(bytes32 => VestingSchedule) private vestingSchedules;
uint256 private vestingSchedulesTotalAmount;
mapping(address => uint256) private holdersVestingCount;
uint256 keeperInterval;
uint256 keeperLastUpdatedTime;
event Released(uint256 amount);
event Revoked();
/**
* @dev Reverts if no vesting schedule matches the passed identifier.
*/
modifier onlyIfVestingScheduleExists(bytes32 vestingScheduleId) {
require(vestingSchedules[vestingScheduleId].initialized == true);
_;
}
/**
* @dev Reverts if the vesting schedule does not exist or has been revoked.
*/
modifier onlyIfVestingScheduleNotRevoked(bytes32 vestingScheduleId) {
require(vestingSchedules[vestingScheduleId].initialized == true);
require(vestingSchedules[vestingScheduleId].revoked == false);
_;
}
/**
* @dev Creates a vesting contract.
* @param token_ address of the ERC20 token contract
*/
constructor(address token_) {
require(token_ != address(0x0));
_token = IERC20(token_);
keeperLastUpdatedTime = block.timestamp;
keeperInterval = 2592000; // 30 days GG_CO
}
receive() external payable {}
fallback() external payable {}
/**
* @dev Returns the number of vesting schedules associated to a beneficiary.
* @return the number of vesting schedules
*/
function getVestingSchedulesCountByBeneficiary(address _beneficiary)
external
view
returns(uint256){
return holdersVestingCount[_beneficiary];
}
/**
* @dev Returns the vesting schedule id at the given index.
* @return the vesting id
*/
function getVestingIdAtIndex(uint256 index)
external
view
returns(bytes32){
require(index < getVestingSchedulesCount(), "TokenVesting: index out of bounds");
return vestingSchedulesIds[index];
}
/**
* @notice Returns the vesting schedule information for a given holder and index.
* @return the vesting schedule structure information
*/
function getVestingScheduleByAddressAndIndex(address holder, uint256 index)
external
view
returns(VestingSchedule memory){
return getVestingSchedule(computeVestingScheduleIdForAddressAndIndex(holder, index));
}
/**
* @notice Returns the total amount of vesting schedules.
* @return the total amount of vesting schedules
*/
function getVestingSchedulesTotalAmount()
external
view
returns(uint256){
return vestingSchedulesTotalAmount;
}
/**
* @dev Returns the address of the ERC20 token managed by the vesting contract.
*/
function getToken()
external
view
returns(address){
return address(_token);
}
function addUserDetails(
address[] memory _to,
uint256[] memory _amount,
uint256 _start,
uint256 _cliff,
uint256 _duration,
uint256 _slicePeriodSeconds
) public onlyOwner returns (bool) {
require(_to.length == _amount.length, "Invalid data");
uint256 tokens;
for (uint256 i = 0; i < _to.length; i++) {
require(_to[i] != address(0), "Invalid address");
createVestingSchedule(_to[i],_start,_cliff,_duration, _slicePeriodSeconds,true,_amount[i]);
tokens = tokens.add(_amount[i]);
}
_token.safeTransferFrom(
msg.sender,
address(this),
tokens
);
return true;
}
function checkUpkeep(bytes calldata /* checkData */) external view override returns (bool upkeepNeeded, bytes memory /* performData */) {
upkeepNeeded = block.timestamp> keeperLastUpdatedTime && (block.timestamp.sub(keeperLastUpdatedTime) > keeperInterval);
// if(block.timestamp> keeperLastUpdatedTime && (block.timestamp.sub(keeperLastUpdatedTime) > keeperInterval)){
// upkeepNeeded = true;
// }
// We don't use the checkData in this example. The checkData is defined when the Upkeep was registered.
}
function performUpkeep(bytes calldata /* performData */) external override {
//We highly recommend revalidating the upkeep in the performUpkeep function
if (block.timestamp> keeperLastUpdatedTime && (block.timestamp.sub(keeperLastUpdatedTime) > keeperInterval)) {
for(uint256 i=0; i<vestingSchedulesIds.length; i++){
uint256 _releasableAmount = computeReleasableAmount(vestingSchedulesIds[i]);
release(vestingSchedulesIds[i], _releasableAmount);
}
}
keeperLastUpdatedTime = block.timestamp;
// We don't use the performData in this example. The performData is generated by the Keeper's call to your checkUpkeep function
}
/**
* @notice Creates a new vesting schedule for a beneficiary.
* @param _beneficiary address of the beneficiary to whom vested tokens are transferred
* @param _start start time of the vesting period
* @param _cliff duration in seconds of the cliff in which tokens will begin to vest
* @param _duration duration in seconds of the period in which the tokens will vest
* @param _slicePeriodSeconds duration of a slice period for the vesting in seconds
* @param _revocable whether the vesting is revocable or not
* @param _amount total amount of tokens to be released at the end of the vesting
*/
function createVestingSchedule(
address _beneficiary,
uint256 _start,
uint256 _cliff,
uint256 _duration,
uint256 _slicePeriodSeconds,
bool _revocable,
uint256 _amount
)
public
onlyOwner{
require(
this.getWithdrawableAmount() >= _amount,
"TokenVesting: cannot create vesting schedule because not sufficient tokens"
);
require(_duration > 0, "TokenVesting: duration must be > 0");
require(_amount > 0, "TokenVesting: amount must be > 0");
require(_slicePeriodSeconds >= 1, "TokenVesting: slicePeriodSeconds must be >= 1");
bytes32 vestingScheduleId = this.computeNextVestingScheduleIdForHolder(_beneficiary);
uint256 cliff = _start.add(_cliff);
vestingSchedules[vestingScheduleId] = VestingSchedule(
true,
_beneficiary,
cliff,
_start,
_duration,
_slicePeriodSeconds,
_revocable,
_amount,
0,
false
);
vestingSchedulesTotalAmount = vestingSchedulesTotalAmount.add(_amount);
vestingSchedulesIds.push(vestingScheduleId);
uint256 currentVestingCount = holdersVestingCount[_beneficiary];
holdersVestingCount[_beneficiary] = currentVestingCount.add(1);
}
/**
* @notice Revokes the vesting schedule for given identifier.
* @param vestingScheduleId the vesting schedule identifier
*/
function revoke(bytes32 vestingScheduleId)
public
onlyOwner
onlyIfVestingScheduleNotRevoked(vestingScheduleId){
VestingSchedule storage vestingSchedule = vestingSchedules[vestingScheduleId];
require(vestingSchedule.revocable == true, "TokenVesting: vesting is not revocable");
uint256 vestedAmount = _computeReleasableAmount(vestingSchedule);
if(vestedAmount > 0){
release(vestingScheduleId, vestedAmount);
}
uint256 unreleased = vestingSchedule.amountTotal.sub(vestingSchedule.released);
vestingSchedulesTotalAmount = vestingSchedulesTotalAmount.sub(unreleased);
vestingSchedule.revoked = true;
}
/**
* @notice Withdraw the specified amount if possible.
* @param amount the amount to withdraw
*/
function withdraw(uint256 amount)
public
nonReentrant
onlyOwner{
require(this.getWithdrawableAmount() >= amount, "TokenVesting: not enough withdrawable funds");
_token.safeTransfer(owner(), amount);
}
/**
* @notice Release vested amount of tokens.
* @param vestingScheduleId the vesting schedule identifier
* @param amount the amount to release
*/
function release(
bytes32 vestingScheduleId,
uint256 amount
)
public
nonReentrant
onlyIfVestingScheduleNotRevoked(vestingScheduleId){
VestingSchedule storage vestingSchedule = vestingSchedules[vestingScheduleId];
// bool isBeneficiary = msg.sender == vestingSchedule.beneficiary;
// bool isOwner = msg.sender == owner();
// require(
// isBeneficiary || isOwner,
// "TokenVesting: only beneficiary and owner can release vested tokens"
// );
uint256 vestedAmount = _computeReleasableAmount(vestingSchedule);
require(vestedAmount >= amount, "TokenVesting: cannot release tokens, not enough vested tokens");
vestingSchedule.released = vestingSchedule.released.add(amount);
address payable beneficiaryPayable = payable(vestingSchedule.beneficiary);
vestingSchedulesTotalAmount = vestingSchedulesTotalAmount.sub(amount);
_token.safeTransfer(beneficiaryPayable, amount);
}
/**
* @dev Returns the number of vesting schedules managed by this contract.
* @return the number of vesting schedules
*/
function getVestingSchedulesCount()
public
view
returns(uint256){
return vestingSchedulesIds.length;
}
/**
* @notice Computes the vested amount of tokens for the given vesting schedule identifier.
* @return the vested amount
*/
function computeReleasableAmount(bytes32 vestingScheduleId)
public
onlyIfVestingScheduleNotRevoked(vestingScheduleId)
view
returns(uint256){
VestingSchedule storage vestingSchedule = vestingSchedules[vestingScheduleId];
return _computeReleasableAmount(vestingSchedule);
}
/**
* @notice Returns the vesting schedule information for a given identifier.
* @return the vesting schedule structure information
*/
function getVestingSchedule(bytes32 vestingScheduleId)
public
view
returns(VestingSchedule memory){
return vestingSchedules[vestingScheduleId];
}
/**
* @dev Returns the amount of tokens that can be withdrawn by the owner.
* @return the amount of tokens
*/
function getWithdrawableAmount()
public
view
returns(uint256){
return _token.balanceOf(address(this)).sub(vestingSchedulesTotalAmount);
}
/**
* @dev Computes the next vesting schedule identifier for a given holder address.
*/
function computeNextVestingScheduleIdForHolder(address holder)
public
view
returns(bytes32){
return computeVestingScheduleIdForAddressAndIndex(holder, holdersVestingCount[holder]);
}
/**
* @dev Returns the last vesting schedule for a given holder address.
*/
function getLastVestingScheduleForHolder(address holder)
public
view
returns(VestingSchedule memory){
return vestingSchedules[computeVestingScheduleIdForAddressAndIndex(holder, holdersVestingCount[holder] - 1)];
}
/**
* @dev Computes the vesting schedule identifier for an address and an index.
*/
function computeVestingScheduleIdForAddressAndIndex(address holder, uint256 index)
public
pure
returns(bytes32){
return keccak256(abi.encodePacked(holder, index));
}
/**
* @dev Computes the releasable amount of tokens for a vesting schedule.
* @return the amount of releasable tokens
*/
function _computeReleasableAmount(VestingSchedule memory vestingSchedule)
internal
view
returns(uint256){
uint256 currentTime = getCurrentTime();
if ((currentTime < vestingSchedule.cliff) || vestingSchedule.revoked == true) {
return 0;
} else if (currentTime >= vestingSchedule.start.add(vestingSchedule.duration)) {
return vestingSchedule.amountTotal.sub(vestingSchedule.released);
} else {
uint256 timeFromStart = currentTime.sub(vestingSchedule.start);
uint secondsPerSlice = vestingSchedule.slicePeriodSeconds;
uint256 vestedSlicePeriods = timeFromStart.div(secondsPerSlice);
uint256 vestedSeconds = vestedSlicePeriods.mul(secondsPerSlice);
uint256 vestedAmount = vestingSchedule.amountTotal.mul(vestedSeconds).div(vestingSchedule.duration);
vestedAmount = vestedAmount.sub(vestingSchedule.released);
return vestedAmount;
}
}
function getCurrentTime()
internal
virtual
view
returns(uint256){
return block.timestamp;
}
}
|
Release vested amount of tokens. vestingScheduleId the vesting schedule identifier amount the amount to release/ bool isBeneficiary = msg.sender == vestingSchedule.beneficiary; bool isOwner = msg.sender == owner(); require( isBeneficiary || isOwner, "TokenVesting: only beneficiary and owner can release vested tokens" );
|
function release(
bytes32 vestingScheduleId,
uint256 amount
)
public
nonReentrant
onlyIfVestingScheduleNotRevoked(vestingScheduleId){
VestingSchedule storage vestingSchedule = vestingSchedules[vestingScheduleId];
uint256 vestedAmount = _computeReleasableAmount(vestingSchedule);
require(vestedAmount >= amount, "TokenVesting: cannot release tokens, not enough vested tokens");
vestingSchedule.released = vestingSchedule.released.add(amount);
address payable beneficiaryPayable = payable(vestingSchedule.beneficiary);
vestingSchedulesTotalAmount = vestingSchedulesTotalAmount.sub(amount);
_token.safeTransfer(beneficiaryPayable, amount);
}
| 498,908 |
./full_match/42220/0x063F1C3C43a147C5877398f39c8DB30E053FBB72/sources/celo/LimitOrders.sol
|
Get this contract's balance of token or Ether _token - Address of the input token return uint256 - this contract's balance of _token/
|
function _getBalance(IERC20 _token) internal view returns (uint256) {
if (address(_token) == ETH_ADDRESS) {
return address(this).balance;
return _token.balanceOf(address(this));
}
}
| 16,343,814 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.