file_name
stringlengths 71
779k
| comments
stringlengths 0
29.4k
| code_string
stringlengths 20
7.69M
| __index_level_0__
int64 2
17.2M
|
---|---|---|---|
pragma solidity ^0.7.0;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
/**
* @title InvertedInuCoterie contract
* @dev Extends ERC721 Non-Fungible Token Standard basic implementation
*/
contract InvertedInuCoterie is ERC721, Ownable {
using SafeMath for uint256;
/**
* @dev Emitted when `tokenId` token is sold from `from` to `to`.
*/
event Sold(address indexed from, address indexed to, uint256 indexed tokenId, uint256 price);
string public INVERTED_PROVENANCE = "";
uint256 public constant dogPrice = 10000000000000000; // 0.01 ETH
uint public constant MAX_DOGS = 10000;
address public BAKC_ADDRESS;
address public IAPE_ADDRESS;
// Mapping from tokenId to sale price.
mapping(uint256 => uint256) public tokenPrices;
// Mapping from tokenId to token owner that set the sale price.
mapping(uint256 => address) public priceSetters;
constructor(string memory name, string memory symbol, address ogAddress, address invertedAddress) ERC721(name, symbol) {
BAKC_ADDRESS = ogAddress;
IAPE_ADDRESS = invertedAddress;
_setBaseURI('ipfs://QmaV8sZ6oc9YFyADPg8U87irpniXmDAbHXup1JEGcdpUKv/');
}
function withdraw() public onlyOwner {
uint balance = address(this).balance;
msg.sender.transfer(balance);
}
/*
* Set provenance once it's calculated
*/
function setProvenanceHash(string memory provenanceHash) public onlyOwner {
INVERTED_PROVENANCE = provenanceHash;
}
/**
* Mints
*/
function mintDog(uint256[] memory tokenIds) public payable {
require(totalSupply().add(tokenIds.length) <= MAX_DOGS, "would exceed max supply of Dogs");
ERC721 bakc = ERC721(BAKC_ADDRESS);
for (uint i=0; i < tokenIds.length; i++) {
require(
(bakc.ownerOf(tokenIds[i]) == msg.sender),
"must own the BAKC dog rights"
);
}
ERC721 invertedApeClub = ERC721(IAPE_ADDRESS);
if (invertedApeClub.balanceOf(msg.sender) == 0) {
require(dogPrice.mul(tokenIds.length) <= msg.value, "Ether value sent is not correct");
}
for (uint i=0; i < tokenIds.length; i++) {
if (totalSupply() < MAX_DOGS) {
_safeMint(msg.sender, tokenIds[i]);
}
}
}
/*
* @dev Checks that the token owner or the token ID is approved for the Market
* @param _tokenId uint256 ID of the token
*/
modifier ownerMustHaveMarketplaceApproved(uint256 _tokenId) {
address owner = ownerOf(_tokenId);
address marketplace = address(this);
require(
isApprovedForAll(owner, marketplace) ||
getApproved(_tokenId) == marketplace,
"owner must have approved marketplace"
);
_;
}
/*
* @dev Checks that the token is owned by the sender
* @param _tokenId uint256 ID of the token
*/
modifier senderMustBeTokenOwner(uint256 _tokenId) {
address tokenOwner = ownerOf(_tokenId);
require(
tokenOwner == msg.sender,
"sender must be the token owner"
);
_;
}
/*
* @dev Checks that the token is owned by the same person who set the sale price.
* @param _tokenId address of the contract storing the token.
*/
function _priceSetterStillOwnsTheDog(uint256 _tokenId)
internal view returns (bool)
{
return ownerOf(_tokenId) == priceSetters[_tokenId];
}
/*
* @dev Set the token for sale
* @param _tokenId uint256 ID of the token
* @param _amount uint256 wei value that the item is for sale
*/
function setWeiSalePrice(uint256 _tokenId, uint256 _amount)
public
ownerMustHaveMarketplaceApproved(_tokenId)
senderMustBeTokenOwner(_tokenId)
{
tokenPrices[_tokenId] = _amount;
priceSetters[_tokenId] = msg.sender;
}
/*
* @dev Purchases the token if it is for sale.
* @param _tokenId uint256 ID of the token.
*/
function buy(uint256 _tokenId)
public payable
ownerMustHaveMarketplaceApproved(_tokenId)
{
// Check that the person who set the price still owns the ape.
require(
_priceSetterStillOwnsTheDog(_tokenId),
"Current token owner must be the person to have the latest price."
);
// Check that token is for sale.
uint256 tokenPrice = tokenPrices[_tokenId];
require(tokenPrice > 0, "Tokens priced at 0 are not for sale.");
// Check that the correct ether was sent.
require(
tokenPrice == msg.value,
"Must purchase the token for the correct price"
);
address tokenOwner = ownerOf(_tokenId);
// Payout all parties.
_payout(tokenPrice, payable(tokenOwner), _tokenId);
// Transfer token.
_transfer(tokenOwner, msg.sender, _tokenId);
// Wipe the token price.
_resetTokenPrice(_tokenId);
emit Sold(msg.sender, tokenOwner, tokenPrice, _tokenId);
}
/* @dev Internal function to set token price to 0 for a give contract.
* @param _tokenId uint256 id of the token.
*/
function _resetTokenPrice(uint256 _tokenId)
internal
{
tokenPrices[_tokenId] = 0;
priceSetters[_tokenId] = address(0);
}
/* @dev Internal function to retrieve the invertedApe Owner if it exists
* @param _tokenId uint256 ID of the inverted ape token.
*/
function iapeAddress(uint _tokenId) internal returns (address apeOwner) {
ERC721 iape = ERC721(IAPE_ADDRESS);
try iape.ownerOf(_tokenId) returns (address a) {
return a;
} catch Error(string memory) {
return address(0);
}
}
/* @dev Internal function to pay the seller and yacht ape owner.
* @param _amount uint256 value to be split.
* @param _seller address seller of the token.
* @param _tokenId uint256 ID of the token.
*/
function _payout(uint256 _amount, address payable _seller, uint256 _tokenId)
private
{
ERC721 bakc = ERC721(BAKC_ADDRESS);
address payable bakcDogOwner = payable(bakc.ownerOf(_tokenId));
address payable invertedApeOwner = payable(iapeAddress(_tokenId));
uint256 invertedApePayment = 0;
if (invertedApeOwner != address(0)) {
invertedApePayment = _calcProportion(1, _amount); // 1%
}
uint256 bakcDogOwnerPayment = _calcProportion(1, _amount); // 1%
uint256 sellerPayment = _amount - bakcDogOwnerPayment - invertedApePayment;
if (invertedApePayment > 0) {
invertedApeOwner.transfer(invertedApePayment);
}
if (bakcDogOwnerPayment > 0) {
bakcDogOwner.transfer(bakcDogOwnerPayment);
}
if (sellerPayment > 0) {
_seller.transfer(sellerPayment);
}
}
/*
* @dev Internal function calculate proportion of a fee for a given amount.
* _amount * fee / 100
* @param _amount uint256 value to be split.
*/
function _calcProportion(uint256 fee, uint256 _amount)
internal pure returns (uint256)
{
return _amount.mul(fee).div(100);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../utils/Context.sol";
import "./IERC721.sol";
import "./IERC721Metadata.sol";
import "./IERC721Enumerable.sol";
import "./IERC721Receiver.sol";
import "../../introspection/ERC165.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
import "../../utils/EnumerableSet.sol";
import "../../utils/EnumerableMap.sol";
import "../../utils/Strings.sol";
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable {
using SafeMath for uint256;
using Address for address;
using EnumerableSet for EnumerableSet.UintSet;
using EnumerableMap for EnumerableMap.UintToAddressMap;
using Strings for uint256;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
// Mapping from holder address to their (enumerable) set of owned tokens
mapping (address => EnumerableSet.UintSet) private _holderTokens;
// Enumerable mapping from token ids to their owners
EnumerableMap.UintToAddressMap private _tokenOwners;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Optional mapping for token URIs
mapping (uint256 => string) private _tokenURIs;
// Base URI
string private _baseURI;
/*
* bytes4(keccak256('balanceOf(address)')) == 0x70a08231
* bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e
* bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3
* bytes4(keccak256('getApproved(uint256)')) == 0x081812fc
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde
*
* => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^
* 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd
*/
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
/*
* bytes4(keccak256('name()')) == 0x06fdde03
* bytes4(keccak256('symbol()')) == 0x95d89b41
* bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
*
* => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f
*/
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
/*
* bytes4(keccak256('totalSupply()')) == 0x18160ddd
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59
* bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7
*
* => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63
*/
bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor (string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721);
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _holderTokens[owner].length();
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token");
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
// If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
return string(abi.encodePacked(base, tokenId.toString()));
}
/**
* @dev Returns the base URI set via {_setBaseURI}. This will be
* automatically added as a prefix in {tokenURI} to each token's URI, or
* to the token ID if no specific URI is set for that token ID.
*/
function baseURI() public view virtual returns (string memory) {
return _baseURI;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
return _holderTokens[owner].at(index);
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
// _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds
return _tokenOwners.length();
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
(uint256 tokenId, ) = _tokenOwners.at(index);
return tokenId;
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(_msgSender() == owner || ERC721.isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(address from, address to, uint256 tokenId) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _tokenOwners.contains(tokenId);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || ERC721.isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
d*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual {
_mint(to, tokenId);
require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId); // internal owner
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
_holderTokens[owner].remove(tokenId);
_tokenOwners.remove(tokenId);
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(address from, address to, uint256 tokenId) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); // internal owner
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_holderTokens[from].remove(tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(from, to, tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Internal function to set the base URI for all token IDs. It is
* automatically added as a prefix to the value returned in {tokenURI},
* or to the token ID if {tokenURI} is empty.
*/
function _setBaseURI(string memory baseURI_) internal virtual {
_baseURI = baseURI_;
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
private returns (bool)
{
if (!to.isContract()) {
return true;
}
bytes memory returndata = to.functionCall(abi.encodeWithSelector(
IERC721Receiver(to).onERC721Received.selector,
_msgSender(),
from,
tokenId,
_data
), "ERC721: transfer to non ERC721Receiver implementer");
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC721_RECEIVED);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits an {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { }
}
// 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 Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev 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.2 <0.8.0;
import "../../introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "./IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "./IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
abstract contract ERC165 is IERC165 {
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
constructor () internal {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing an enumerable variant of Solidity's
* https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`]
* type.
*
* Maps have the following properties:
*
* - Entries are added, removed, and checked for existence in constant time
* (O(1)).
* - Entries are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableMap for EnumerableMap.UintToAddressMap;
*
* // Declare a set state variable
* EnumerableMap.UintToAddressMap private myMap;
* }
* ```
*
* As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are
* supported.
*/
library EnumerableMap {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// The Map implementation uses private functions, and user-facing
// implementations (such as Uint256ToAddressMap) are just wrappers around
// the underlying Map.
// This means that we can only create new EnumerableMaps for types that fit
// in bytes32.
struct MapEntry {
bytes32 _key;
bytes32 _value;
}
struct Map {
// Storage of map keys and values
MapEntry[] _entries;
// Position of the entry defined by a key in the `entries` array, plus 1
// because index 0 means a key is not in the map.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) { // Equivalent to !contains(map, key)
map._entries.push(MapEntry({ _key: key, _value: value }));
// The entry is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
map._indexes[key] = map._entries.length;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function _remove(Map storage map, bytes32 key) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex != 0) { // Equivalent to contains(map, key)
// To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one
// in the array, and then remove the last entry (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._entries.length - 1;
// When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
MapEntry storage lastEntry = map._entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map._entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
map._entries.pop();
// Delete the index for the deleted slot
delete map._indexes[key];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function _contains(Map storage map, bytes32 key) private view returns (bool) {
return map._indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._entries.length;
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) {
require(map._entries.length > index, "EnumerableMap: index out of bounds");
MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/
function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) {
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key)
return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {_tryGet}.
*/
function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
// UintToAddressMap
struct UintToAddressMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) {
return _remove(map._inner, bytes32(key));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) {
return _contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(UintToAddressMap storage map) internal view returns (uint256) {
return _length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) {
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint256(key), address(uint160(uint256(value))));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*
* _Available since v3.4._
*/
function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) {
(bool success, bytes32 value) = _tryGet(map._inner, bytes32(key));
return (success, address(uint160(uint256(value))));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(UintToAddressMap storage map, uint256 key) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key)))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryGet}.
*/
function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage))));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev String operations.
*/
library Strings {
/**
* @dev Converts a `uint256` to its ASCII `string` representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
uint256 index = digits - 1;
temp = value;
while (temp != 0) {
buffer[index--] = bytes1(uint8(48 + temp % 10));
temp /= 10;
}
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
| Set the token for sale _tokenId uint256 ID of the token _amount uint256 wei value that the item is for sale/ | function setWeiSalePrice(uint256 _tokenId, uint256 _amount)
public
ownerMustHaveMarketplaceApproved(_tokenId)
senderMustBeTokenOwner(_tokenId)
{
tokenPrices[_tokenId] = _amount;
priceSetters[_tokenId] = msg.sender;
}
| 11,862,711 |
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);
}
} | Function to check the amount of tokens that an owner allowed to a spender. _owner address The address which owns the funds. _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];
}
| 7,275,052 |
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.6.0;
/************************************************************************************************
Originally from https://github.com/balancer-labs/balancer-core/blob/master/contracts/BConst.sol
This source code has been modified from the original, which was copied from the github repository
at commit hash f4ed5d65362a8d6cec21662fb6eae233b0babc1f.
Subject to the GPL-3.0 license
*************************************************************************************************/
contract BConst {
uint256 public constant VERSION_NUMBER = 1;
/* --- Weight Updates --- */
// Minimum time passed between each weight update for a token.
uint256 internal constant WEIGHT_UPDATE_DELAY = 30 minutes;
// Maximum percent by which a weight can adjust at a time
// relative to the current weight.
// The number of iterations needed to move from weight A to weight B is the floor of:
// (A > B): (ln(A) - ln(B)) / ln(1.01)
// (B > A): (ln(A) - ln(B)) / ln(0.99)
uint256 internal constant WEIGHT_CHANGE_PCT = BONE/100;
uint256 internal constant BONE = 10**18;
uint256 internal constant MIN_BOUND_TOKENS = 2;
uint256 internal constant MAX_BOUND_TOKENS = 10;
// Minimum swap fee.
uint256 internal constant MIN_FEE = BONE / 10**6;
// Maximum swap or exit fee.
uint256 internal constant MAX_FEE = BONE / 10;
// Actual exit fee.
uint256 internal constant EXIT_FEE = 5e15;
// Default total of all desired weights. Can differ by up to BONE.
uint256 internal constant DEFAULT_TOTAL_WEIGHT = BONE * 25;
// Minimum weight for any token (1/100).
uint256 internal constant MIN_WEIGHT = BONE / 4;
uint256 internal constant MAX_WEIGHT = BONE * 25;
// Maximum total weight.
uint256 internal constant MAX_TOTAL_WEIGHT = 27e18;
// Minimum balance for a token (only applied at initialization)
uint256 internal constant MIN_BALANCE = BONE / 10**12;
// Initial pool tokens
uint256 internal constant INIT_POOL_SUPPLY = BONE * 100;
uint256 internal constant MIN_BPOW_BASE = 1 wei;
uint256 internal constant MAX_BPOW_BASE = (2 * BONE) - 1 wei;
uint256 internal constant BPOW_PRECISION = BONE / 10**10;
// Maximum ratio of input tokens to balance for swaps.
uint256 internal constant MAX_IN_RATIO = BONE / 2;
// Maximum ratio of output tokens to balance for swaps.
uint256 internal constant MAX_OUT_RATIO = (BONE / 3) + 1 wei;
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.6.0;
import "./BNum.sol";
/************************************************************************************************
Originally from https://github.com/balancer-labs/balancer-core/blob/master/contracts/BMath.sol
This source code has been modified from the original, which was copied from the github repository
at commit hash f4ed5d65362a8d6cec21662fb6eae233b0babc1f.
Subject to the GPL-3.0 license
*************************************************************************************************/
contract BMath is BConst, BNum {
/**********************************************************************************************
// calcSpotPrice //
// sP = spotPrice //
// bI = tokenBalanceIn ( bI / wI ) 1 //
// bO = tokenBalanceOut sP = ----------- * ---------- //
// wI = tokenWeightIn ( bO / wO ) ( 1 - sF ) //
// wO = tokenWeightOut //
// sF = swapFee //
**********************************************************************************************/
function calcSpotPrice(
uint256 tokenBalanceIn,
uint256 tokenWeightIn,
uint256 tokenBalanceOut,
uint256 tokenWeightOut,
uint256 swapFee
) internal pure returns (uint256 spotPrice) {
uint256 numer = bdiv(tokenBalanceIn, tokenWeightIn);
uint256 denom = bdiv(tokenBalanceOut, tokenWeightOut);
uint256 ratio = bdiv(numer, denom);
uint256 scale = bdiv(BONE, bsub(BONE, swapFee));
return (spotPrice = bmul(ratio, scale));
}
/**********************************************************************************************
// calcOutGivenIn //
// aO = tokenAmountOut //
// bO = tokenBalanceOut //
// bI = tokenBalanceIn / / bI \ (wI / wO) \ //
// aI = tokenAmountIn aO = bO * | 1 - | -------------------------- | ^ | //
// wI = tokenWeightIn \ \ ( bI + ( aI * ( 1 - sF )) / / //
// wO = tokenWeightOut //
// sF = swapFee //
**********************************************************************************************/
function calcOutGivenIn(
uint256 tokenBalanceIn,
uint256 tokenWeightIn,
uint256 tokenBalanceOut,
uint256 tokenWeightOut,
uint256 tokenAmountIn,
uint256 swapFee
) internal pure returns (uint256 tokenAmountOut) {
uint256 weightRatio = bdiv(tokenWeightIn, tokenWeightOut);
uint256 adjustedIn = bsub(BONE, swapFee);
adjustedIn = bmul(tokenAmountIn, adjustedIn);
uint256 y = bdiv(tokenBalanceIn, badd(tokenBalanceIn, adjustedIn));
uint256 foo = bpow(y, weightRatio);
uint256 bar = bsub(BONE, foo);
tokenAmountOut = bmul(tokenBalanceOut, bar);
return tokenAmountOut;
}
/**********************************************************************************************
// calcInGivenOut //
// aI = tokenAmountIn //
// bO = tokenBalanceOut / / bO \ (wO / wI) \ //
// bI = tokenBalanceIn bI * | | ------------ | ^ - 1 | //
// aO = tokenAmountOut aI = \ \ ( bO - aO ) / / //
// wI = tokenWeightIn -------------------------------------------- //
// wO = tokenWeightOut ( 1 - sF ) //
// sF = swapFee //
**********************************************************************************************/
function calcInGivenOut(
uint256 tokenBalanceIn,
uint256 tokenWeightIn,
uint256 tokenBalanceOut,
uint256 tokenWeightOut,
uint256 tokenAmountOut,
uint256 swapFee
) internal pure returns (uint256 tokenAmountIn) {
uint256 weightRatio = bdiv(tokenWeightOut, tokenWeightIn);
uint256 diff = bsub(tokenBalanceOut, tokenAmountOut);
uint256 y = bdiv(tokenBalanceOut, diff);
uint256 foo = bpow(y, weightRatio);
foo = bsub(foo, BONE);
tokenAmountIn = bsub(BONE, swapFee);
tokenAmountIn = bdiv(bmul(tokenBalanceIn, foo), tokenAmountIn);
return tokenAmountIn;
}
/**********************************************************************************************
// calcPoolOutGivenSingleIn //
// pAo = poolAmountOut / \ //
// tAi = tokenAmountIn /// / // wI \ \\ \ wI \ //
// wI = tokenWeightIn //| tAi *| 1 - || 1 - -- | * sF || + tBi \ -- \ //
// tW = totalWeight pAo=|| \ \ \\ tW / // | ^ tW | * pS - pS //
// tBi = tokenBalanceIn \\ ------------------------------------- / / //
// pS = poolSupply \\ tBi / / //
// sF = swapFee \ / //
**********************************************************************************************/
function calcPoolOutGivenSingleIn(
uint256 tokenBalanceIn,
uint256 tokenWeightIn,
uint256 poolSupply,
uint256 totalWeight,
uint256 tokenAmountIn,
uint256 swapFee
) internal pure returns (uint256 poolAmountOut) {
// Charge the trading fee for the proportion of tokenAi
/// which is implicitly traded to the other pool tokens.
// That proportion is (1- weightTokenIn)
// tokenAiAfterFee = tAi * (1 - (1-weightTi) * poolFee);
uint256 normalizedWeight = bdiv(tokenWeightIn, totalWeight);
uint256 zaz = bmul(bsub(BONE, normalizedWeight), swapFee);
uint256 tokenAmountInAfterFee = bmul(tokenAmountIn, bsub(BONE, zaz));
uint256 newTokenBalanceIn = badd(tokenBalanceIn, tokenAmountInAfterFee);
uint256 tokenInRatio = bdiv(newTokenBalanceIn, tokenBalanceIn);
// uint newPoolSupply = (ratioTi ^ weightTi) * poolSupply;
uint256 poolRatio = bpow(tokenInRatio, normalizedWeight);
uint256 newPoolSupply = bmul(poolRatio, poolSupply);
poolAmountOut = bsub(newPoolSupply, poolSupply);
return poolAmountOut;
}
/**********************************************************************************************
// calcSingleInGivenPoolOut //
// tAi = tokenAmountIn //(pS + pAo)\ / 1 \\ //
// pS = poolSupply || --------- | ^ | --------- || * bI - bI //
// pAo = poolAmountOut \\ pS / \(wI / tW)// //
// bI = balanceIn tAi = -------------------------------------------- //
// wI = weightIn / wI \ //
// tW = totalWeight | 1 - ---- | * sF //
// sF = swapFee \ tW / //
**********************************************************************************************/
function calcSingleInGivenPoolOut(
uint256 tokenBalanceIn,
uint256 tokenWeightIn,
uint256 poolSupply,
uint256 totalWeight,
uint256 poolAmountOut,
uint256 swapFee
) internal pure returns (uint256 tokenAmountIn) {
uint256 normalizedWeight = bdiv(tokenWeightIn, totalWeight);
uint256 newPoolSupply = badd(poolSupply, poolAmountOut);
uint256 poolRatio = bdiv(newPoolSupply, poolSupply);
//uint newBalTi = poolRatio^(1/weightTi) * balTi;
uint256 boo = bdiv(BONE, normalizedWeight);
uint256 tokenInRatio = bpow(poolRatio, boo);
uint256 newTokenBalanceIn = bmul(tokenInRatio, tokenBalanceIn);
uint256 tokenAmountInAfterFee = bsub(newTokenBalanceIn, tokenBalanceIn);
// Do reverse order of fees charged in joinswap_ExternAmountIn, this way
// ``` pAo == joinswap_ExternAmountIn(Ti, joinswap_PoolAmountOut(pAo, Ti)) ```
//uint tAi = tAiAfterFee / (1 - (1-weightTi) * swapFee) ;
uint256 zar = bmul(bsub(BONE, normalizedWeight), swapFee);
tokenAmountIn = bdiv(tokenAmountInAfterFee, bsub(BONE, zar));
return tokenAmountIn;
}
/**********************************************************************************************
// calcSingleOutGivenPoolIn //
// tAo = tokenAmountOut / / \\ //
// bO = tokenBalanceOut / // pS - (pAi * (1 - eF)) \ / 1 \ \\ //
// pAi = poolAmountIn | bO - || ----------------------- | ^ | --------- | * b0 || //
// ps = poolSupply \ \\ pS / \(wO / tW)/ // //
// wI = tokenWeightIn tAo = \ \ // //
// tW = totalWeight / / wO \ \ //
// sF = swapFee * | 1 - | 1 - ---- | * sF | //
// eF = exitFee \ \ tW / / //
**********************************************************************************************/
function calcSingleOutGivenPoolIn(
uint256 tokenBalanceOut,
uint256 tokenWeightOut,
uint256 poolSupply,
uint256 totalWeight,
uint256 poolAmountIn,
uint256 swapFee
) internal pure returns (uint256 tokenAmountOut) {
uint256 normalizedWeight = bdiv(tokenWeightOut, totalWeight);
// charge exit fee on the pool token side
// pAiAfterExitFee = pAi*(1-exitFee)
uint256 poolAmountInAfterExitFee = bmul(poolAmountIn, bsub(BONE, EXIT_FEE));
uint256 newPoolSupply = bsub(poolSupply, poolAmountInAfterExitFee);
uint256 poolRatio = bdiv(newPoolSupply, poolSupply);
// newBalTo = poolRatio^(1/weightTo) * balTo;
uint256 tokenOutRatio = bpow(poolRatio, bdiv(BONE, normalizedWeight));
uint256 newTokenBalanceOut = bmul(tokenOutRatio, tokenBalanceOut);
uint256 tokenAmountOutBeforeSwapFee = bsub(
tokenBalanceOut,
newTokenBalanceOut
);
// charge swap fee on the output token side
//uint tAo = tAoBeforeSwapFee * (1 - (1-weightTo) * swapFee)
uint256 zaz = bmul(bsub(BONE, normalizedWeight), swapFee);
tokenAmountOut = bmul(tokenAmountOutBeforeSwapFee, bsub(BONE, zaz));
return tokenAmountOut;
}
/**********************************************************************************************
// calcPoolInGivenSingleOut //
// pAi = poolAmountIn // / tAo \\ / wO \ \ //
// bO = tokenBalanceOut // | bO - -------------------------- |\ | ---- | \ //
// tAo = tokenAmountOut pS - || \ 1 - ((1 - (tO / tW)) * sF)/ | ^ \ tW / * pS | //
// ps = poolSupply \\ -----------------------------------/ / //
// wO = tokenWeightOut pAi = \\ bO / / //
// tW = totalWeight ------------------------------------------------------------- //
// sF = swapFee ( 1 - eF ) //
// eF = exitFee //
**********************************************************************************************/
function calcPoolInGivenSingleOut(
uint256 tokenBalanceOut,
uint256 tokenWeightOut,
uint256 poolSupply,
uint256 totalWeight,
uint256 tokenAmountOut,
uint256 swapFee
) internal pure returns (uint256 poolAmountIn) {
// charge swap fee on the output token side
uint256 normalizedWeight = bdiv(tokenWeightOut, totalWeight);
//uint tAoBeforeSwapFee = tAo / (1 - (1-weightTo) * swapFee) ;
uint256 zoo = bsub(BONE, normalizedWeight);
uint256 zar = bmul(zoo, swapFee);
uint256 tokenAmountOutBeforeSwapFee = bdiv(tokenAmountOut, bsub(BONE, zar));
uint256 newTokenBalanceOut = bsub(
tokenBalanceOut,
tokenAmountOutBeforeSwapFee
);
uint256 tokenOutRatio = bdiv(newTokenBalanceOut, tokenBalanceOut);
//uint newPoolSupply = (ratioTo ^ weightTo) * poolSupply;
uint256 poolRatio = bpow(tokenOutRatio, normalizedWeight);
uint256 newPoolSupply = bmul(poolRatio, poolSupply);
uint256 poolAmountInAfterExitFee = bsub(poolSupply, newPoolSupply);
// charge exit fee on the pool token side
// pAi = pAiAfterExitFee/(1-exitFee)
poolAmountIn = bdiv(poolAmountInAfterExitFee, bsub(BONE, EXIT_FEE));
return poolAmountIn;
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.6.0;
import "./BConst.sol";
/************************************************************************************************
Originally from https://github.com/balancer-labs/balancer-core/blob/master/contracts/BNum.sol
This source code has been modified from the original, which was copied from the github repository
at commit hash f4ed5d65362a8d6cec21662fb6eae233b0babc1f.
Subject to the GPL-3.0 license
*************************************************************************************************/
contract BNum is BConst {
function btoi(uint256 a) internal pure returns (uint256) {
return a / BONE;
}
function bfloor(uint256 a) internal pure returns (uint256) {
return btoi(a) * BONE;
}
function badd(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "ERR_ADD_OVERFLOW");
return c;
}
function bsub(uint256 a, uint256 b) internal pure returns (uint256) {
(uint256 c, bool flag) = bsubSign(a, b);
require(!flag, "ERR_SUB_UNDERFLOW");
return c;
}
function bsubSign(uint256 a, uint256 b)
internal
pure
returns (uint256, bool)
{
if (a >= b) {
return (a - b, false);
} else {
return (b - a, true);
}
}
function bmul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c0 = a * b;
require(a == 0 || c0 / a == b, "ERR_MUL_OVERFLOW");
uint256 c1 = c0 + (BONE / 2);
require(c1 >= c0, "ERR_MUL_OVERFLOW");
uint256 c2 = c1 / BONE;
return c2;
}
function bdiv(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "ERR_DIV_ZERO");
uint256 c0 = a * BONE;
require(a == 0 || c0 / a == BONE, "ERR_DIV_INTERNAL"); // bmul overflow
uint256 c1 = c0 + (b / 2);
require(c1 >= c0, "ERR_DIV_INTERNAL"); // badd require
uint256 c2 = c1 / b;
return c2;
}
// DSMath.wpow
function bpowi(uint256 a, uint256 n) internal pure returns (uint256) {
uint256 z = n % 2 != 0 ? a : BONE;
for (n /= 2; n != 0; n /= 2) {
a = bmul(a, a);
if (n % 2 != 0) {
z = bmul(z, a);
}
}
return z;
}
// Compute b^(e.w) by splitting it into (b^e)*(b^0.w).
// Use `bpowi` for `b^e` and `bpowK` for k iterations
// of approximation of b^0.w
function bpow(uint256 base, uint256 exp) internal pure returns (uint256) {
require(base >= MIN_BPOW_BASE, "ERR_BPOW_BASE_TOO_LOW");
require(base <= MAX_BPOW_BASE, "ERR_BPOW_BASE_TOO_HIGH");
uint256 whole = bfloor(exp);
uint256 remain = bsub(exp, whole);
uint256 wholePow = bpowi(base, btoi(whole));
if (remain == 0) {
return wholePow;
}
uint256 partialResult = bpowApprox(base, remain, BPOW_PRECISION);
return bmul(wholePow, partialResult);
}
function bpowApprox(
uint256 base,
uint256 exp,
uint256 precision
) internal pure returns (uint256) {
// term 0:
uint256 a = exp;
(uint256 x, bool xneg) = bsubSign(base, BONE);
uint256 term = BONE;
uint256 sum = term;
bool negative = false;
// term(k) = numer / denom
// = (product(a - i - 1, i=1-->k) * x^k) / (k!)
// each iteration, multiply previous term by (a-(k-1)) * x / k
// continue until term is less than precision
for (uint256 i = 1; term >= precision; i++) {
uint256 bigK = i * BONE;
(uint256 c, bool cneg) = bsubSign(a, bsub(bigK, BONE));
term = bmul(term, bmul(c, x));
term = bdiv(term, bigK);
if (term == 0) break;
if (xneg) negative = !negative;
if (cneg) negative = !negative;
if (negative) {
sum = bsub(sum, term);
} else {
sum = badd(sum, term);
}
}
return sum;
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.6.0;
import "./BNum.sol";
/************************************************************************************************
Originally from https://github.com/balancer-labs/balancer-core/blob/master/contracts/BToken.sol
This source code has been modified from the original, which was copied from the github repository
at commit hash f4ed5d65362a8d6cec21662fb6eae233b0babc1f.
Subject to the GPL-3.0 license
*************************************************************************************************/
// Highly opinionated token implementation
interface IERC20 {
event Approval(address indexed src, address indexed dst, uint256 amt);
event Transfer(address indexed src, address indexed dst, uint256 amt);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint256);
function balanceOf(address whom) external view returns (uint256);
function allowance(address src, address dst) external view returns (uint256);
function approve(address dst, uint256 amt) external returns (bool);
function transfer(address dst, uint256 amt) external returns (bool);
function transferFrom(
address src,
address dst,
uint256 amt
) external returns (bool);
}
contract BTokenBase is BNum {
mapping(address => uint256) internal _balance;
mapping(address => mapping(address => uint256)) internal _allowance;
uint256 internal _totalSupply;
event Approval(address indexed src, address indexed dst, uint256 amt);
event Transfer(address indexed src, address indexed dst, uint256 amt);
function _mint(uint256 amt) internal {
_balance[address(this)] = badd(_balance[address(this)], amt);
_totalSupply = badd(_totalSupply, amt);
emit Transfer(address(0), address(this), amt);
}
function _burn(uint256 amt) internal {
require(_balance[address(this)] >= amt, "ERR_INSUFFICIENT_BAL");
_balance[address(this)] = bsub(_balance[address(this)], amt);
_totalSupply = bsub(_totalSupply, amt);
emit Transfer(address(this), address(0), amt);
}
function _move(
address src,
address dst,
uint256 amt
) internal {
require(_balance[src] >= amt, "ERR_INSUFFICIENT_BAL");
_balance[src] = bsub(_balance[src], amt);
_balance[dst] = badd(_balance[dst], amt);
emit Transfer(src, dst, amt);
}
function _push(address to, uint256 amt) internal {
_move(address(this), to, amt);
}
function _pull(address from, uint256 amt) internal {
_move(from, address(this), amt);
}
}
contract BToken is BTokenBase, IERC20 {
uint8 private constant DECIMALS = 18;
string private _name;
string private _symbol;
function _initializeToken(string memory name, string memory symbol) internal {
require(
bytes(_name).length == 0 &&
bytes(name).length != 0 &&
bytes(symbol).length != 0,
"ERR_BTOKEN_INITIALIZED"
);
_name = name;
_symbol = symbol;
}
function name()
external
override
view
returns (string memory)
{
return _name;
}
function symbol()
external
override
view
returns (string memory)
{
return _symbol;
}
function decimals()
external
override
view
returns (uint8)
{
return DECIMALS;
}
function allowance(address src, address dst)
external
override
view
returns (uint256)
{
return _allowance[src][dst];
}
function balanceOf(address whom) external override view returns (uint256) {
return _balance[whom];
}
function totalSupply() public override view returns (uint256) {
return _totalSupply;
}
function approve(address dst, uint256 amt) external override returns (bool) {
_allowance[msg.sender][dst] = amt;
emit Approval(msg.sender, dst, amt);
return true;
}
function increaseApproval(address dst, uint256 amt) external returns (bool) {
_allowance[msg.sender][dst] = badd(_allowance[msg.sender][dst], amt);
emit Approval(msg.sender, dst, _allowance[msg.sender][dst]);
return true;
}
function decreaseApproval(address dst, uint256 amt) external returns (bool) {
uint256 oldValue = _allowance[msg.sender][dst];
if (amt > oldValue) {
_allowance[msg.sender][dst] = 0;
} else {
_allowance[msg.sender][dst] = bsub(oldValue, amt);
}
emit Approval(msg.sender, dst, _allowance[msg.sender][dst]);
return true;
}
function transfer(address dst, uint256 amt) external override returns (bool) {
_move(msg.sender, dst, amt);
return true;
}
function transferFrom(
address src,
address dst,
uint256 amt
) external override returns (bool) {
require(
msg.sender == src || amt <= _allowance[src][msg.sender],
"ERR_BTOKEN_BAD_CALLER"
);
_move(src, dst, amt);
if (msg.sender != src && _allowance[src][msg.sender] != uint256(-1)) {
_allowance[src][msg.sender] = bsub(_allowance[src][msg.sender], amt);
emit Approval(msg.sender, dst, _allowance[src][msg.sender]);
}
return true;
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
/* ========== Internal Inheritance ========== */
import "./BToken.sol";
import "./BMath.sol";
/* ========== Internal Interfaces ========== */
import "../interfaces/IIndexPool.sol";
import "../interfaces/ICompLikeToken.sol";
/************************************************************************************************
Originally from https://github.com/balancer-labs/balancer-core/blob/master/contracts/BPool.sol
This source code has been modified from the original, which was copied from the github repository
at commit hash f4ed5d65362a8d6cec21662fb6eae233b0babc1f.
Subject to the GPL-3.0 license
*************************************************************************************************/
contract SigmaIndexPoolV1 is BToken, BMath, IIndexPool {
/* ========== Modifiers ========== */
modifier _lock_ {
require(!_mutex, "ERR_REENTRY");
_mutex = true;
_;
_mutex = false;
}
modifier _viewlock_() {
require(!_mutex, "ERR_REENTRY");
_;
}
modifier _control_ {
require(msg.sender == _controller, "ERR_NOT_CONTROLLER");
_;
}
modifier _public_ {
require(_publicSwap, "ERR_NOT_PUBLIC");
_;
}
/* ========== Storage ========== */
bool internal _mutex;
// Account with CONTROL role. Able to modify the swap fee,
// adjust token weights, bind and unbind tokens and lock
// public swaps & joins.
address internal _controller;
// Contract that handles unbound tokens.
TokenUnbindHandler internal _unbindHandler;
// True if PUBLIC can call SWAP & JOIN functions
bool internal _publicSwap;
// `setSwapFee` requires CONTROL
uint256 internal _swapFee;
// Array of underlying tokens in the pool.
address[] internal _tokens;
// Internal records of the pool's underlying tokens
mapping(address => Record) internal _records;
// Total denormalized weight of the pool.
uint256 internal _totalWeight;
// Minimum balances for tokens which have been added without the
// requisite initial balance.
mapping(address => uint256) internal _minimumBalances;
// Recipient for exit fees
address internal _exitFeeRecipient;
/* ========== Controls ========== */
/**
* @dev Sets the controller address and the token name & symbol.
*
* Note: This saves on storage costs for multi-step pool deployment.
*
* @param controller Controller of the pool
* @param name Name of the pool token
* @param symbol Symbol of the pool token
*/
function configure(
address controller,
string calldata name,
string calldata symbol
) external override {
require(_controller == address(0), "ERR_CONFIGURED");
require(controller != address(0), "ERR_NULL_ADDRESS");
_controller = controller;
// default fee is 2%
_swapFee = BONE / 50;
_initializeToken(name, symbol);
}
/**
* @dev Sets up the initial assets for the pool.
*
* Note: `tokenProvider` must have approved the pool to transfer the
* corresponding `balances` of `tokens`.
*
* @param tokens Underlying tokens to initialize the pool with
* @param balances Initial balances to transfer
* @param denorms Initial denormalized weights for the tokens
* @param tokenProvider Address to transfer the balances from
* @param unbindHandler Address that receives tokens removed from the pool
* @param exitFeeRecipient Address that receives exit fees
*/
function initialize(
address[] calldata tokens,
uint256[] calldata balances,
uint96[] calldata denorms,
address tokenProvider,
address unbindHandler,
address exitFeeRecipient
)
external
override
_control_
{
require(_tokens.length == 0, "ERR_INITIALIZED");
uint256 len = tokens.length;
require(len >= MIN_BOUND_TOKENS, "ERR_MIN_TOKENS");
require(len <= MAX_BOUND_TOKENS, "ERR_MAX_TOKENS");
require(balances.length == len && denorms.length == len, "ERR_ARR_LEN");
uint256 totalWeight = 0;
for (uint256 i = 0; i < len; i++) {
address token = tokens[i];
uint96 denorm = denorms[i];
uint256 balance = balances[i];
require(denorm >= MIN_WEIGHT, "ERR_MIN_WEIGHT");
require(denorm <= MAX_WEIGHT, "ERR_MAX_WEIGHT");
require(balance >= MIN_BALANCE, "ERR_MIN_BALANCE");
_records[token] = Record({
bound: true,
ready: true,
lastDenormUpdate: uint40(now),
denorm: denorm,
desiredDenorm: denorm,
index: uint8(i),
balance: balance
});
_tokens.push(token);
totalWeight = badd(totalWeight, denorm);
_pullUnderlying(token, tokenProvider, balance);
}
require(totalWeight <= MAX_TOTAL_WEIGHT, "ERR_MAX_TOTAL_WEIGHT");
_totalWeight = totalWeight;
_publicSwap = true;
emit LOG_PUBLIC_SWAP_TOGGLED(true);
_mintPoolShare(INIT_POOL_SUPPLY);
_pushPoolShare(tokenProvider, INIT_POOL_SUPPLY);
_unbindHandler = TokenUnbindHandler(unbindHandler);
_exitFeeRecipient = exitFeeRecipient;
}
/**
* @dev Set the swap fee.
* Note: Swap fee must be between 0.0001% and 10%
*/
function setSwapFee(uint256 swapFee) external override _control_ {
require(swapFee >= MIN_FEE && swapFee <= MAX_FEE, "ERR_INVALID_FEE");
_swapFee = swapFee;
emit LOG_SWAP_FEE_UPDATED(swapFee);
}
/**
* @dev Set the controller address.
*/
function setController(address controller) external override _control_ {
require(controller != address(0), "ERR_NULL_ADDRESS");
_controller = controller;
emit LOG_CONTROLLER_UPDATED(controller);
}
/**
* @dev Delegate a comp-like governance token to an address
* specified by the controller.
*/
function delegateCompLikeToken(address token, address delegatee)
external
override
_control_
{
ICompLikeToken(token).delegate(delegatee);
}
/**
* @dev Set the exit fee recipient address.
*/
function setExitFeeRecipient(address exitFeeRecipient) external override _control_ {
require(exitFeeRecipient != address(0), "ERR_NULL_ADDRESS");
_exitFeeRecipient = exitFeeRecipient;
emit LOG_EXIT_FEE_RECIPIENT_UPDATED(exitFeeRecipient);
}
/**
* @dev Toggle public trading for the index pool.
* This will enable or disable swaps and single-token joins and exits.
*/
function setPublicSwap(bool enabled) external override _control_ {
_publicSwap = enabled;
emit LOG_PUBLIC_SWAP_TOGGLED(enabled);
}
/* ========== Token Management Actions ========== */
/**
* @dev Sets the desired weights for the pool tokens, which
* will be adjusted over time as they are swapped.
*
* Note: This does not check for duplicate tokens or that the total
* of the desired weights is equal to the target total weight (25).
* Those assumptions should be met in the controller. Further, the
* provided tokens should only include the tokens which are not set
* for removal.
*/
function reweighTokens(
address[] calldata tokens,
uint96[] calldata desiredDenorms
)
external
override
_lock_
_control_
{
require(desiredDenorms.length == tokens.length, "ERR_ARR_LEN");
for (uint256 i = 0; i < tokens.length; i++)
_setDesiredDenorm(tokens[i], desiredDenorms[i]);
}
/**
* @dev Update the underlying assets held by the pool and their associated
* weights. Tokens which are not currently bound will be gradually added
* as they are swapped in to reach the provided minimum balances, which must
* be an amount of tokens worth the minimum weight of the total pool value.
* If a currently bound token is not received in this call, the token's
* desired weight will be set to 0.
*/
function reindexTokens(
address[] calldata tokens,
uint96[] calldata desiredDenorms,
uint256[] calldata minimumBalances
)
external
override
_lock_
_control_
{
require(
desiredDenorms.length == tokens.length && minimumBalances.length == tokens.length,
"ERR_ARR_LEN"
);
// This size may not be the same as the input size, as it is possible
// to temporarily exceed the index size while tokens are being phased in
// or out.
uint256 tLen = _tokens.length;
bool[] memory receivedIndices = new bool[](tLen);
// We need to read token records in two separate loops, so
// write them to memory to avoid duplicate storage reads.
Record[] memory records = new Record[](tokens.length);
// Read all the records from storage and mark which of the existing tokens
// were represented in the reindex call.
for (uint256 i = 0; i < tokens.length; i++) {
records[i] = _records[tokens[i]];
if (records[i].bound) receivedIndices[records[i].index] = true;
}
// If any bound tokens were not sent in this call, set their desired weights to 0.
for (uint256 i = 0; i < tLen; i++) {
if (!receivedIndices[i]) {
_setDesiredDenorm(_tokens[i], 0);
}
}
for (uint256 i = 0; i < tokens.length; i++) {
address token = tokens[i];
// If an input weight is less than the minimum weight, use that instead.
uint96 denorm = desiredDenorms[i];
if (denorm < MIN_WEIGHT) denorm = uint96(MIN_WEIGHT);
if (!records[i].bound) {
// If the token is not bound, bind it.
_bind(token, minimumBalances[i], denorm);
} else {
_setDesiredDenorm(token, denorm);
}
}
}
/**
* @dev Updates the minimum balance for an uninitialized token.
* This becomes useful if a token's external price significantly
* rises after being bound, since the pool can not send a token
* out until it reaches the minimum balance.
*/
function setMinimumBalance(
address token,
uint256 minimumBalance
)
external
override
_control_
{
Record storage record = _records[token];
require(record.bound, "ERR_NOT_BOUND");
require(!record.ready, "ERR_READY");
_minimumBalances[token] = minimumBalance;
emit LOG_MINIMUM_BALANCE_UPDATED(token, minimumBalance);
}
/* ========== Liquidity Provider Actions ========== */
/**
* @dev Mint new pool tokens by providing the proportional amount of each
* underlying token's balance relative to the proportion of pool tokens minted.
*
* For any underlying tokens which are not initialized, the caller must provide
* the proportional share of the minimum balance for the token rather than the
* actual balance.
*
* @param poolAmountOut Amount of pool tokens to mint
* @param maxAmountsIn Maximum amount of each token to pay in the same
* order as the pool's _tokens list.
*/
function joinPool(uint256 poolAmountOut, uint256[] calldata maxAmountsIn)
external
override
_lock_
_public_
{
uint256 poolTotal = totalSupply();
uint256 ratio = bdiv(poolAmountOut, poolTotal);
require(ratio != 0, "ERR_MATH_APPROX");
require(maxAmountsIn.length == _tokens.length, "ERR_ARR_LEN");
for (uint256 i = 0; i < maxAmountsIn.length; i++) {
address t = _tokens[i];
(Record memory record, uint256 realBalance) = _getInputToken(t);
uint256 tokenAmountIn = bmul(ratio, record.balance);
require(tokenAmountIn != 0, "ERR_MATH_APPROX");
require(tokenAmountIn <= maxAmountsIn[i], "ERR_LIMIT_IN");
_updateInputToken(t, record, badd(realBalance, tokenAmountIn));
emit LOG_JOIN(msg.sender, t, tokenAmountIn);
_pullUnderlying(t, msg.sender, tokenAmountIn);
}
_mintPoolShare(poolAmountOut);
_pushPoolShare(msg.sender, poolAmountOut);
}
/**
* @dev Pay `tokenAmountIn` of `tokenIn` to mint at least `minPoolAmountOut`
* pool tokens.
*
* The pool implicitly swaps `(1- weightTokenIn) * tokenAmountIn` to the other
* underlying tokens. Thus a swap fee is charged against the input tokens.
*
* @param tokenIn Token to send the pool
* @param tokenAmountIn Exact amount of `tokenIn` to pay
* @param minPoolAmountOut Minimum amount of pool tokens to mint
* @return poolAmountOut - Amount of pool tokens minted
*/
function joinswapExternAmountIn(
address tokenIn,
uint256 tokenAmountIn,
uint256 minPoolAmountOut
)
external
override
_lock_
_public_
returns (uint256/* poolAmountOut */)
{
(Record memory inRecord, uint256 realInBalance) = _getInputToken(tokenIn);
require(tokenAmountIn != 0, "ERR_ZERO_IN");
require(
tokenAmountIn <= bmul(inRecord.balance, MAX_IN_RATIO),
"ERR_MAX_IN_RATIO"
);
uint256 poolAmountOut = calcPoolOutGivenSingleIn(
inRecord.balance,
inRecord.denorm,
_totalSupply,
_totalWeight,
tokenAmountIn,
_swapFee
);
require(poolAmountOut >= minPoolAmountOut, "ERR_LIMIT_OUT");
_updateInputToken(tokenIn, inRecord, badd(realInBalance, tokenAmountIn));
emit LOG_JOIN(msg.sender, tokenIn, tokenAmountIn);
_mintPoolShare(poolAmountOut);
_pushPoolShare(msg.sender, poolAmountOut);
_pullUnderlying(tokenIn, msg.sender, tokenAmountIn);
return poolAmountOut;
}
/**
* @dev Pay up to `maxAmountIn` of `tokenIn` to mint exactly `poolAmountOut`.
*
* The pool implicitly swaps `(1- weightTokenIn) * tokenAmountIn` to the other
* underlying tokens. Thus a swap fee is charged against the input tokens.
*
* @param tokenIn Token to send the pool
* @param poolAmountOut Exact amount of pool tokens to mint
* @param maxAmountIn Maximum amount of `tokenIn` to pay
* @return tokenAmountIn - Amount of `tokenIn` paid
*/
function joinswapPoolAmountOut(
address tokenIn,
uint256 poolAmountOut,
uint256 maxAmountIn
)
external
override
_lock_
_public_
returns (uint256/* tokenAmountIn */)
{
(Record memory inRecord, uint256 realInBalance) = _getInputToken(tokenIn);
uint256 tokenAmountIn = calcSingleInGivenPoolOut(
inRecord.balance,
inRecord.denorm,
_totalSupply,
_totalWeight,
poolAmountOut,
_swapFee
);
require(tokenAmountIn != 0, "ERR_MATH_APPROX");
require(tokenAmountIn <= maxAmountIn, "ERR_LIMIT_IN");
require(
tokenAmountIn <= bmul(inRecord.balance, MAX_IN_RATIO),
"ERR_MAX_IN_RATIO"
);
_updateInputToken(tokenIn, inRecord, badd(realInBalance, tokenAmountIn));
emit LOG_JOIN(msg.sender, tokenIn, tokenAmountIn);
_mintPoolShare(poolAmountOut);
_pushPoolShare(msg.sender, poolAmountOut);
_pullUnderlying(tokenIn, msg.sender, tokenAmountIn);
return tokenAmountIn;
}
/**
* @dev Burns `poolAmountIn` pool tokens in exchange for the amounts of each
* underlying token's balance proportional to the ratio of tokens burned to
* total pool supply. The amount of each token transferred to the caller must
* be greater than or equal to the associated minimum output amount from the
* `minAmountsOut` array.
*
* @param poolAmountIn Exact amount of pool tokens to burn
* @param minAmountsOut Minimum amount of each token to receive, in the same
* order as the pool's _tokens list.
*/
function exitPool(uint256 poolAmountIn, uint256[] calldata minAmountsOut)
external
override
_lock_
{
require(minAmountsOut.length == _tokens.length, "ERR_ARR_LEN");
uint256 poolTotal = totalSupply();
uint256 exitFee = bmul(poolAmountIn, EXIT_FEE);
uint256 pAiAfterExitFee = bsub(poolAmountIn, exitFee);
uint256 ratio = bdiv(pAiAfterExitFee, poolTotal);
require(ratio != 0, "ERR_MATH_APPROX");
_pullPoolShare(msg.sender, poolAmountIn);
_pushPoolShare(_exitFeeRecipient, exitFee);
_burnPoolShare(pAiAfterExitFee);
for (uint256 i = 0; i < minAmountsOut.length; i++) {
address t = _tokens[i];
Record memory record = _records[t];
if (record.ready) {
uint256 tokenAmountOut = bmul(ratio, record.balance);
require(tokenAmountOut != 0, "ERR_MATH_APPROX");
require(tokenAmountOut >= minAmountsOut[i], "ERR_LIMIT_OUT");
_records[t].balance = bsub(record.balance, tokenAmountOut);
emit LOG_EXIT(msg.sender, t, tokenAmountOut);
_pushUnderlying(t, msg.sender, tokenAmountOut);
} else {
// If the token is not initialized, it can not exit the pool.
require(minAmountsOut[i] == 0, "ERR_OUT_NOT_READY");
}
}
}
/**
* @dev Burns `poolAmountIn` pool tokens in exchange for at least `minAmountOut`
* of `tokenOut`. Returns the number of tokens sent to the caller.
*
* The pool implicitly burns the tokens for all underlying tokens and swaps them
* to the desired output token. A swap fee is charged against the output tokens.
*
* @param tokenOut Token to receive
* @param poolAmountIn Exact amount of pool tokens to burn
* @param minAmountOut Minimum amount of `tokenOut` to receive
* @return tokenAmountOut - Amount of `tokenOut` received
*/
function exitswapPoolAmountIn(
address tokenOut,
uint256 poolAmountIn,
uint256 minAmountOut
)
external
override
_lock_
returns (uint256/* tokenAmountOut */)
{
Record memory outRecord = _getOutputToken(tokenOut);
uint256 tokenAmountOut = calcSingleOutGivenPoolIn(
outRecord.balance,
outRecord.denorm,
_totalSupply,
_totalWeight,
poolAmountIn,
_swapFee
);
require(tokenAmountOut >= minAmountOut, "ERR_LIMIT_OUT");
require(
tokenAmountOut <= bmul(outRecord.balance, MAX_OUT_RATIO),
"ERR_MAX_OUT_RATIO"
);
_pushUnderlying(tokenOut, msg.sender, tokenAmountOut);
_records[tokenOut].balance = bsub(outRecord.balance, tokenAmountOut);
_decreaseDenorm(outRecord, tokenOut);
uint256 exitFee = bmul(poolAmountIn, EXIT_FEE);
emit LOG_EXIT(msg.sender, tokenOut, tokenAmountOut);
_pullPoolShare(msg.sender, poolAmountIn);
_burnPoolShare(bsub(poolAmountIn, exitFee));
_pushPoolShare(_exitFeeRecipient, exitFee);
return tokenAmountOut;
}
/**
* @dev Burn up to `maxPoolAmountIn` for exactly `tokenAmountOut` of `tokenOut`.
* Returns the number of pool tokens burned.
*
* The pool implicitly burns the tokens for all underlying tokens and swaps them
* to the desired output token. A swap fee is charged against the output tokens.
*
* @param tokenOut Token to receive
* @param tokenAmountOut Exact amount of `tokenOut` to receive
* @param maxPoolAmountIn Maximum amount of pool tokens to burn
* @return poolAmountIn - Amount of pool tokens burned
*/
function exitswapExternAmountOut(
address tokenOut,
uint256 tokenAmountOut,
uint256 maxPoolAmountIn
)
external
override
_lock_
returns (uint256/* poolAmountIn */)
{
Record memory outRecord = _getOutputToken(tokenOut);
require(
tokenAmountOut <= bmul(outRecord.balance, MAX_OUT_RATIO),
"ERR_MAX_OUT_RATIO"
);
uint256 poolAmountIn = calcPoolInGivenSingleOut(
outRecord.balance,
outRecord.denorm,
_totalSupply,
_totalWeight,
tokenAmountOut,
_swapFee
);
require(poolAmountIn != 0, "ERR_MATH_APPROX");
require(poolAmountIn <= maxPoolAmountIn, "ERR_LIMIT_IN");
_pushUnderlying(tokenOut, msg.sender, tokenAmountOut);
_records[tokenOut].balance = bsub(outRecord.balance, tokenAmountOut);
_decreaseDenorm(outRecord, tokenOut);
uint256 exitFee = bmul(poolAmountIn, EXIT_FEE);
emit LOG_EXIT(msg.sender, tokenOut, tokenAmountOut);
_pullPoolShare(msg.sender, poolAmountIn);
_burnPoolShare(bsub(poolAmountIn, exitFee));
_pushPoolShare(_exitFeeRecipient, exitFee);
return poolAmountIn;
}
/* ========== Other ========== */
/**
* @dev Absorb any tokens that have been sent to the pool.
* If the token is not bound, it will be sent to the unbound
* token handler.
*/
function gulp(address token) external override _lock_ {
Record storage record = _records[token];
uint256 balance = IERC20(token).balanceOf(address(this));
if (record.bound) {
if (!record.ready) {
uint256 minimumBalance = _minimumBalances[token];
if (balance >= minimumBalance) {
_minimumBalances[token] = 0;
record.ready = true;
emit LOG_TOKEN_READY(token);
uint256 additionalBalance = bsub(balance, minimumBalance);
uint256 balRatio = bdiv(additionalBalance, minimumBalance);
uint96 newDenorm = uint96(badd(MIN_WEIGHT, bmul(MIN_WEIGHT, balRatio)));
record.denorm = newDenorm;
record.lastDenormUpdate = uint40(now);
_totalWeight = badd(_totalWeight, newDenorm);
emit LOG_DENORM_UPDATED(token, record.denorm);
}
}
_records[token].balance = balance;
} else {
_pushUnderlying(token, address(_unbindHandler), balance);
_unbindHandler.handleUnbindToken(token, balance);
}
}
/* ========== Token Swaps ========== */
/**
* @dev Execute a token swap with a specified amount of input
* tokens and a minimum amount of output tokens.
*
* Note: Will revert if `tokenOut` is uninitialized.
*
* @param tokenIn Token to swap in
* @param tokenAmountIn Exact amount of `tokenIn` to swap in
* @param tokenOut Token to swap out
* @param minAmountOut Minimum amount of `tokenOut` to receive
* @param maxPrice Maximum ratio of input to output tokens
* @return (tokenAmountOut, spotPriceAfter)
*/
function swapExactAmountIn(
address tokenIn,
uint256 tokenAmountIn,
address tokenOut,
uint256 minAmountOut,
uint256 maxPrice
)
external
override
_lock_
_public_
returns (uint256/* tokenAmountOut */, uint256/* spotPriceAfter */)
{
(Record memory inRecord, uint256 realInBalance) = _getInputToken(tokenIn);
Record memory outRecord = _getOutputToken(tokenOut);
require(
tokenAmountIn <= bmul(inRecord.balance, MAX_IN_RATIO),
"ERR_MAX_IN_RATIO"
);
uint256 spotPriceBefore = calcSpotPrice(
inRecord.balance,
inRecord.denorm,
outRecord.balance,
outRecord.denorm,
_swapFee
);
require(spotPriceBefore <= maxPrice, "ERR_BAD_LIMIT_PRICE");
uint256 tokenAmountOut = calcOutGivenIn(
inRecord.balance,
inRecord.denorm,
outRecord.balance,
outRecord.denorm,
tokenAmountIn,
_swapFee
);
require(tokenAmountOut >= minAmountOut, "ERR_LIMIT_OUT");
_pullUnderlying(tokenIn, msg.sender, tokenAmountIn);
_pushUnderlying(tokenOut, msg.sender, tokenAmountOut);
// Update the in-memory record for the spotPriceAfter calculation,
// then update the storage record with the local balance.
outRecord.balance = bsub(outRecord.balance, tokenAmountOut);
_records[tokenOut].balance = outRecord.balance;
// If needed, update the output token's weight.
_decreaseDenorm(outRecord, tokenOut);
realInBalance = badd(realInBalance, tokenAmountIn);
_updateInputToken(tokenIn, inRecord, realInBalance);
if (inRecord.ready) {
inRecord.balance = realInBalance;
}
uint256 spotPriceAfter = calcSpotPrice(
inRecord.balance,
inRecord.denorm,
outRecord.balance,
outRecord.denorm,
_swapFee
);
require(spotPriceAfter >= spotPriceBefore, "ERR_MATH_APPROX_2");
require(spotPriceAfter <= maxPrice, "ERR_LIMIT_PRICE");
require(
spotPriceBefore <= bdiv(tokenAmountIn, tokenAmountOut),
"ERR_MATH_APPROX"
);
emit LOG_SWAP(msg.sender, tokenIn, tokenOut, tokenAmountIn, tokenAmountOut);
return (tokenAmountOut, spotPriceAfter);
}
/**
* @dev Trades at most `maxAmountIn` of `tokenIn` for exactly `tokenAmountOut`
* of `tokenOut`.
*
* Returns the actual input amount and the new spot price after the swap,
* which can not exceed `maxPrice`.
*
* @param tokenIn Token to swap in
* @param maxAmountIn Maximum amount of `tokenIn` to pay
* @param tokenOut Token to swap out
* @param tokenAmountOut Exact amount of `tokenOut` to receive
* @param maxPrice Maximum ratio of input to output tokens
* @return (tokenAmountIn, spotPriceAfter)
*/
function swapExactAmountOut(
address tokenIn,
uint256 maxAmountIn,
address tokenOut,
uint256 tokenAmountOut,
uint256 maxPrice
)
external
override
_lock_
_public_
returns (uint256 /* tokenAmountIn */, uint256 /* spotPriceAfter */)
{
(Record memory inRecord, uint256 realInBalance) = _getInputToken(tokenIn);
Record memory outRecord = _getOutputToken(tokenOut);
require(
tokenAmountOut <= bmul(outRecord.balance, MAX_OUT_RATIO),
"ERR_MAX_OUT_RATIO"
);
uint256 spotPriceBefore = calcSpotPrice(
inRecord.balance,
inRecord.denorm,
outRecord.balance,
outRecord.denorm,
_swapFee
);
require(spotPriceBefore <= maxPrice, "ERR_BAD_LIMIT_PRICE");
uint256 tokenAmountIn = calcInGivenOut(
inRecord.balance,
inRecord.denorm,
outRecord.balance,
outRecord.denorm,
tokenAmountOut,
_swapFee
);
require(tokenAmountIn <= maxAmountIn, "ERR_LIMIT_IN");
_pullUnderlying(tokenIn, msg.sender, tokenAmountIn);
_pushUnderlying(tokenOut, msg.sender, tokenAmountOut);
// Update the in-memory record for the spotPriceAfter calculation,
// then update the storage record with the local balance.
outRecord.balance = bsub(outRecord.balance, tokenAmountOut);
_records[tokenOut].balance = outRecord.balance;
// If needed, update the output token's weight.
_decreaseDenorm(outRecord, tokenOut);
// Update the balance and (if necessary) weight of the input token.
realInBalance = badd(realInBalance, tokenAmountIn);
_updateInputToken(tokenIn, inRecord, realInBalance);
if (inRecord.ready) {
inRecord.balance = realInBalance;
}
uint256 spotPriceAfter = calcSpotPrice(
inRecord.balance,
inRecord.denorm,
outRecord.balance,
outRecord.denorm,
_swapFee
);
require(spotPriceAfter >= spotPriceBefore, "ERR_MATH_APPROX");
require(spotPriceAfter <= maxPrice, "ERR_LIMIT_PRICE");
require(
spotPriceBefore <= bdiv(tokenAmountIn, tokenAmountOut),
"ERR_MATH_APPROX"
);
emit LOG_SWAP(msg.sender, tokenIn, tokenOut, tokenAmountIn, tokenAmountOut);
return (tokenAmountIn, spotPriceAfter);
}
/* ========== Config Queries ========== */
/**
* @dev Check if swapping tokens and joining the pool is allowed.
*/
function isPublicSwap() external view override returns (bool) {
return _publicSwap;
}
function getSwapFee() external view override _viewlock_ returns (uint256/* swapFee */) {
return _swapFee;
}
function getExitFee() external view override _viewlock_ returns (uint256/* exitFee */) {
return EXIT_FEE;
}
/**
* @dev Returns the controller address.
*/
function getController() external view override returns (address) {
return _controller;
}
/**
* @dev Returns the exit fee recipient address.
*/
function getExitFeeRecipient() external view override returns (address) {
return _exitFeeRecipient;
}
/* ========== Token Queries ========== */
/**
* @dev Check if a token is bound to the pool.
*/
function isBound(address t) external view override returns (bool) {
return _records[t].bound;
}
/**
* @dev Get the number of tokens bound to the pool.
*/
function getNumTokens() external view override returns (uint256) {
return _tokens.length;
}
/**
* @dev Get all bound tokens.
*/
function getCurrentTokens()
external
view
override
_viewlock_
returns (address[] memory tokens)
{
tokens = _tokens;
}
/**
* @dev Returns the list of tokens which have a desired weight above 0.
* Tokens with a desired weight of 0 are set to be phased out of the pool.
*/
function getCurrentDesiredTokens()
external
view
override
_viewlock_
returns (address[] memory tokens)
{
address[] memory tempTokens = _tokens;
tokens = new address[](tempTokens.length);
uint256 usedIndex = 0;
for (uint256 i = 0; i < tokens.length; i++) {
address token = tempTokens[i];
if (_records[token].desiredDenorm > 0) {
tokens[usedIndex++] = token;
}
}
assembly { mstore(tokens, usedIndex) }
}
/**
* @dev Returns the denormalized weight of a bound token.
*/
function getDenormalizedWeight(address token)
external
view
override
_viewlock_
returns (uint256/* denorm */)
{
require(_records[token].bound, "ERR_NOT_BOUND");
return _records[token].denorm;
}
/**
* @dev Returns the record for a token bound to the pool.
*/
function getTokenRecord(address token)
external
view
override
_viewlock_
returns (Record memory record)
{
record = _records[token];
require(record.bound, "ERR_NOT_BOUND");
}
/**
* @dev Finds the first token which is both initialized and has a
* desired weight above 0, then returns the address of that token
* and the extrapolated value of the pool in terms of that token.
*
* The value is extrapolated by multiplying the token's
* balance by the reciprocal of its normalized weight.
* @return (token, extrapolatedValue)
*/
function extrapolatePoolValueFromToken()
external
view
override
_viewlock_
returns (address/* token */, uint256/* extrapolatedValue */)
{
address token;
uint256 extrapolatedValue;
uint256 len = _tokens.length;
for (uint256 i = 0; i < len; i++) {
token = _tokens[i];
Record storage record = _records[token];
if (record.ready && record.desiredDenorm > 0) {
extrapolatedValue = bmul(
record.balance,
bdiv(_totalWeight, record.denorm)
);
break;
}
}
require(extrapolatedValue > 0, "ERR_NONE_READY");
return (token, extrapolatedValue);
}
/**
* @dev Get the total denormalized weight of the pool.
*/
function getTotalDenormalizedWeight()
external
view
override
_viewlock_
returns (uint256)
{
return _totalWeight;
}
/**
* @dev Returns the stored balance of a bound token.
*/
function getBalance(address token) external view override _viewlock_ returns (uint256) {
Record storage record = _records[token];
require(record.bound, "ERR_NOT_BOUND");
return record.balance;
}
/**
* @dev Get the minimum balance of an uninitialized token.
* Note: Throws if the token is initialized.
*/
function getMinimumBalance(address token) external view override _viewlock_ returns (uint256) {
Record memory record = _records[token];
require(record.bound, "ERR_NOT_BOUND");
require(!record.ready, "ERR_READY");
return _minimumBalances[token];
}
/**
* @dev Returns the balance of a token which is used in price
* calculations. If the token is initialized, this is the
* stored balance; if not, this is the minimum balance.
*/
function getUsedBalance(address token) external view override _viewlock_ returns (uint256) {
Record memory record = _records[token];
require(record.bound, "ERR_NOT_BOUND");
if (!record.ready) {
return _minimumBalances[token];
}
return record.balance;
}
/* ========== Price Queries ========== */
/**
* @dev Returns the spot price for `tokenOut` in terms of `tokenIn`.
*/
function getSpotPrice(address tokenIn, address tokenOut)
external
view
override
_viewlock_
returns (uint256)
{
(Record memory inRecord,) = _getInputToken(tokenIn);
Record memory outRecord = _getOutputToken(tokenOut);
return
calcSpotPrice(
inRecord.balance,
inRecord.denorm,
outRecord.balance,
outRecord.denorm,
_swapFee
);
}
/* ========== Pool Share Internal Functions ========== */
function _pullPoolShare(address from, uint256 amount) internal {
_pull(from, amount);
}
function _pushPoolShare(address to, uint256 amount) internal {
_push(to, amount);
}
function _mintPoolShare(uint256 amount) internal {
_mint(amount);
}
function _burnPoolShare(uint256 amount) internal {
_burn(amount);
}
/* ========== Underlying Token Internal Functions ========== */
// 'Underlying' token-manipulation functions make external calls but are NOT locked
// You must `_lock_` or otherwise ensure reentry-safety
function _pullUnderlying(
address erc20,
address from,
uint256 amount
) internal {
(bool success, bytes memory data) = erc20.call(
abi.encodeWithSelector(
IERC20.transferFrom.selector,
from,
address(this),
amount
)
);
require(
success && (data.length == 0 || abi.decode(data, (bool))),
"ERR_ERC20_FALSE"
);
}
function _pushUnderlying(
address erc20,
address to,
uint256 amount
) internal {
(bool success, bytes memory data) = erc20.call(
abi.encodeWithSelector(
IERC20.transfer.selector,
to,
amount
)
);
require(
success && (data.length == 0 || abi.decode(data, (bool))),
"ERR_ERC20_FALSE"
);
}
/* ========== Token Management Internal Functions ========== */
/**
* @dev Bind a token by address without actually depositing a balance.
* The token will be unable to be swapped out until it reaches the minimum balance.
* Note: Token must not already be bound.
* Note: `minimumBalance` should represent an amount of the token which is worth
* the portion of the current pool value represented by the minimum weight.
* @param token Address of the token to bind
* @param minimumBalance minimum balance to reach before the token can be swapped out
* @param desiredDenorm Desired weight for the token.
*/
function _bind(
address token,
uint256 minimumBalance,
uint96 desiredDenorm
) internal {
require(!_records[token].bound, "ERR_IS_BOUND");
require(desiredDenorm >= MIN_WEIGHT, "ERR_MIN_WEIGHT");
require(desiredDenorm <= MAX_WEIGHT, "ERR_MAX_WEIGHT");
require(minimumBalance >= MIN_BALANCE, "ERR_MIN_BALANCE");
_records[token] = Record({
bound: true,
ready: false,
lastDenormUpdate: 0,
denorm: 0,
desiredDenorm: desiredDenorm,
index: uint8(_tokens.length),
balance: 0
});
_tokens.push(token);
_minimumBalances[token] = minimumBalance;
emit LOG_TOKEN_ADDED(token, desiredDenorm, minimumBalance);
}
/**
* @dev Remove a token from the pool.
* Replaces the address in the tokens array with the last address,
* then removes it from the array.
* Note: This should only be called after the total weight has been adjusted.
* Note: Must be called in a function with:
* - _lock_ modifier to prevent reentrance
* - requirement that the token is bound
*/
function _unbind(address token) internal {
Record memory record = _records[token];
uint256 tokenBalance = record.balance;
// Swap the token-to-unbind with the last token,
// then delete the last token
uint256 index = record.index;
uint256 last = _tokens.length - 1;
// Only swap the token with the last token if it is not
// already at the end of the array.
if (index != last) {
_tokens[index] = _tokens[last];
_records[_tokens[index]].index = uint8(index);
}
_tokens.pop();
_records[token] = Record({
bound: false,
ready: false,
lastDenormUpdate: 0,
denorm: 0,
desiredDenorm: 0,
index: 0,
balance: 0
});
// transfer any remaining tokens out
_pushUnderlying(token, address(_unbindHandler), tokenBalance);
_unbindHandler.handleUnbindToken(token, tokenBalance);
emit LOG_TOKEN_REMOVED(token);
}
function _setDesiredDenorm(address token, uint96 desiredDenorm) internal {
Record storage record = _records[token];
require(record.bound, "ERR_NOT_BOUND");
// If the desired weight is 0, this will trigger a gradual unbinding of the token.
// Therefore the weight only needs to be above the minimum weight if it isn't 0.
require(
desiredDenorm >= MIN_WEIGHT || desiredDenorm == 0,
"ERR_MIN_WEIGHT"
);
require(desiredDenorm <= MAX_WEIGHT, "ERR_MAX_WEIGHT");
record.desiredDenorm = desiredDenorm;
emit LOG_DESIRED_DENORM_SET(token, desiredDenorm);
}
function _increaseDenorm(Record memory record, address token) internal {
// If the weight does not need to increase or the token is not
// initialized, don't do anything.
if (
record.denorm >= record.desiredDenorm ||
!record.ready ||
now - record.lastDenormUpdate < WEIGHT_UPDATE_DELAY
) return;
uint96 oldWeight = record.denorm;
uint96 denorm = record.desiredDenorm;
uint256 maxDiff = bmul(oldWeight, WEIGHT_CHANGE_PCT);
uint256 diff = bsub(denorm, oldWeight);
if (diff > maxDiff) {
denorm = uint96(badd(oldWeight, maxDiff));
diff = maxDiff;
}
// If new total weight exceeds the maximum, do not update
uint256 newTotalWeight = badd(_totalWeight, diff);
if (newTotalWeight > MAX_TOTAL_WEIGHT) return;
_totalWeight = newTotalWeight;
// Update the in-memory denorm value for spot-price computations.
record.denorm = denorm;
// Update the storage record
_records[token].denorm = denorm;
_records[token].lastDenormUpdate = uint40(now);
emit LOG_DENORM_UPDATED(token, denorm);
}
function _decreaseDenorm(Record memory record, address token) internal {
// If the weight does not need to decrease, don't do anything.
if (
record.denorm <= record.desiredDenorm ||
!record.ready ||
now - record.lastDenormUpdate < WEIGHT_UPDATE_DELAY
) return;
uint96 oldWeight = record.denorm;
uint96 denorm = record.desiredDenorm;
uint256 maxDiff = bmul(oldWeight, WEIGHT_CHANGE_PCT);
uint256 diff = bsub(oldWeight, denorm);
if (diff > maxDiff) {
denorm = uint96(bsub(oldWeight, maxDiff));
diff = maxDiff;
}
if (denorm <= MIN_WEIGHT) {
denorm = 0;
_totalWeight = bsub(_totalWeight, denorm);
// Because this is removing the token from the pool, the
// in-memory denorm value is irrelevant, as it is only used
// to calculate the new spot price, but the spot price calc
// will throw if it is passed 0 for the denorm.
_unbind(token);
} else {
_totalWeight = bsub(_totalWeight, diff);
// Update the in-memory denorm value for spot-price computations.
record.denorm = denorm;
// Update the stored denorm value
_records[token].denorm = denorm;
_records[token].lastDenormUpdate = uint40(now);
emit LOG_DENORM_UPDATED(token, denorm);
}
}
/**
* @dev Handles weight changes and initialization of an
* input token.
*
* If the token is not initialized and the new balance is
* still below the minimum, this will not do anything.
*
* If the token is not initialized but the new balance will
* bring the token above the minimum balance, this will
* mark the token as initialized, remove the minimum
* balance and set the weight to the minimum weight plus
* 1%.
*
*
* @param token Address of the input token
* @param record Token record with minimums applied to the balance
* and weight if the token was uninitialized.
*/
function _updateInputToken(
address token,
Record memory record,
uint256 realBalance
)
internal
{
if (!record.ready) {
// Check if the minimum balance has been reached
if (realBalance >= record.balance) {
// Remove the minimum balance record
_minimumBalances[token] = 0;
// Mark the token as initialized
_records[token].ready = true;
record.ready = true;
emit LOG_TOKEN_READY(token);
// Set the initial denorm value to the minimum weight times one plus
// the ratio of the increase in balance over the minimum to the minimum
// balance.
// weight = (1 + ((bal - min_bal) / min_bal)) * min_weight
uint256 additionalBalance = bsub(realBalance, record.balance);
uint256 balRatio = bdiv(additionalBalance, record.balance);
record.denorm = uint96(badd(MIN_WEIGHT, bmul(MIN_WEIGHT, balRatio)));
_records[token].denorm = record.denorm;
_records[token].lastDenormUpdate = uint40(now);
_totalWeight = badd(_totalWeight, record.denorm);
emit LOG_DENORM_UPDATED(token, record.denorm);
} else {
uint256 realToMinRatio = bdiv(
bsub(record.balance, realBalance),
record.balance
);
uint256 weightPremium = bmul(MIN_WEIGHT / 10, realToMinRatio);
record.denorm = uint96(badd(MIN_WEIGHT, weightPremium));
}
// If the token is still not ready, do not adjust the weight.
} else {
// If the token is already initialized, update the weight (if any adjustment
// is needed).
_increaseDenorm(record, token);
}
// Regardless of whether the token is initialized, store the actual new balance.
_records[token].balance = realBalance;
}
/* ========== Token Query Internal Functions ========== */
/**
* @dev Get the record for a token which is being swapped in.
* The token must be bound to the pool. If the token is not
* initialized (meaning it does not have the minimum balance)
* this function will return the actual balance of the token
* which the pool holds, but set the record's balance and weight
* to the token's minimum balance and the pool's minimum weight.
* This allows the token swap to be priced correctly even if the
* pool does not own any of the tokens.
*/
function _getInputToken(address token)
internal
view
returns (Record memory record, uint256 realBalance)
{
record = _records[token];
require(record.bound, "ERR_NOT_BOUND");
realBalance = record.balance;
// If the input token is not initialized, we use the minimum
// initial weight and minimum initial balance instead of the
// real values for price and output calculations.
if (!record.ready) {
record.balance = _minimumBalances[token];
uint256 realToMinRatio = bdiv(
bsub(record.balance, realBalance),
record.balance
);
uint256 weightPremium = bmul(MIN_WEIGHT / 10, realToMinRatio);
record.denorm = uint96(badd(MIN_WEIGHT, weightPremium));
}
}
function _getOutputToken(address token)
internal
view
returns (Record memory record)
{
record = _records[token];
require(record.bound, "ERR_NOT_BOUND");
// Tokens which have not reached their minimum balance can not be
// swapped out.
require(record.ready, "ERR_OUT_NOT_READY");
}
}
interface TokenUnbindHandler {
/**
* @dev Receive `amount` of `token` from the pool.
*/
function handleUnbindToken(address token, uint256 amount) external;
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
interface IIndexPool {
/**
* @dev Token record data structure
* @param bound is token bound to pool
* @param ready has token been initialized
* @param lastDenormUpdate timestamp of last denorm change
* @param denorm denormalized weight
* @param desiredDenorm desired denormalized weight (used for incremental changes)
* @param index index of address in tokens array
* @param balance token balance
*/
struct Record {
bool bound;
bool ready;
uint40 lastDenormUpdate;
uint96 denorm;
uint96 desiredDenorm;
uint8 index;
uint256 balance;
}
/* ========== EVENTS ========== */
/** @dev Emitted when tokens are swapped. */
event LOG_SWAP(
address indexed caller,
address indexed tokenIn,
address indexed tokenOut,
uint256 tokenAmountIn,
uint256 tokenAmountOut
);
/** @dev Emitted when underlying tokens are deposited for pool tokens. */
event LOG_JOIN(
address indexed caller,
address indexed tokenIn,
uint256 tokenAmountIn
);
/** @dev Emitted when pool tokens are burned for underlying. */
event LOG_EXIT(
address indexed caller,
address indexed tokenOut,
uint256 tokenAmountOut
);
/** @dev Emitted when a token's weight updates. */
event LOG_DENORM_UPDATED(address indexed token, uint256 newDenorm);
/** @dev Emitted when a token's desired weight is set. */
event LOG_DESIRED_DENORM_SET(address indexed token, uint256 desiredDenorm);
/** @dev Emitted when a token is unbound from the pool. */
event LOG_TOKEN_REMOVED(address token);
/** @dev Emitted when a token is unbound from the pool. */
event LOG_TOKEN_ADDED(
address indexed token,
uint256 desiredDenorm,
uint256 minimumBalance
);
/** @dev Emitted when a token's minimum balance is updated. */
event LOG_MINIMUM_BALANCE_UPDATED(address token, uint256 minimumBalance);
/** @dev Emitted when a token reaches its minimum balance. */
event LOG_TOKEN_READY(address indexed token);
/** @dev Emitted when public trades are enabled or disabled. */
event LOG_PUBLIC_SWAP_TOGGLED(bool isPublic);
/** @dev Emitted when the swap fee is updated. */
event LOG_SWAP_FEE_UPDATED(uint256 swapFee);
/** @dev Emitted when exit fee recipient is updated. */
event LOG_EXIT_FEE_RECIPIENT_UPDATED(address exitFeeRecipient);
/** @dev Emitted when controller is updated. */
event LOG_CONTROLLER_UPDATED(address exitFeeRecipient);
function configure(
address controller,
string calldata name,
string calldata symbol
) external;
function initialize(
address[] calldata tokens,
uint256[] calldata balances,
uint96[] calldata denorms,
address tokenProvider,
address unbindHandler,
address exitFeeRecipient
) external;
function setSwapFee(uint256 swapFee) external;
function setController(address controller) external;
function delegateCompLikeToken(address token, address delegatee) external;
function setExitFeeRecipient(address) external;
function setPublicSwap(bool enabled) external;
function reweighTokens(
address[] calldata tokens,
uint96[] calldata desiredDenorms
) external;
function reindexTokens(
address[] calldata tokens,
uint96[] calldata desiredDenorms,
uint256[] calldata minimumBalances
) external;
function setMinimumBalance(address token, uint256 minimumBalance) external;
function joinPool(uint256 poolAmountOut, uint256[] calldata maxAmountsIn) external;
function joinswapExternAmountIn(
address tokenIn,
uint256 tokenAmountIn,
uint256 minPoolAmountOut
) external returns (uint256/* poolAmountOut */);
function joinswapPoolAmountOut(
address tokenIn,
uint256 poolAmountOut,
uint256 maxAmountIn
) external returns (uint256/* tokenAmountIn */);
function exitPool(uint256 poolAmountIn, uint256[] calldata minAmountsOut) external;
function exitswapPoolAmountIn(
address tokenOut,
uint256 poolAmountIn,
uint256 minAmountOut
)
external returns (uint256/* tokenAmountOut */);
function exitswapExternAmountOut(
address tokenOut,
uint256 tokenAmountOut,
uint256 maxPoolAmountIn
) external returns (uint256/* poolAmountIn */);
function gulp(address token) external;
function swapExactAmountIn(
address tokenIn,
uint256 tokenAmountIn,
address tokenOut,
uint256 minAmountOut,
uint256 maxPrice
) external returns (uint256/* tokenAmountOut */, uint256/* spotPriceAfter */);
function swapExactAmountOut(
address tokenIn,
uint256 maxAmountIn,
address tokenOut,
uint256 tokenAmountOut,
uint256 maxPrice
) external returns (uint256 /* tokenAmountIn */, uint256 /* spotPriceAfter */);
function isPublicSwap() external view returns (bool);
function getSwapFee() external view returns (uint256/* swapFee */);
function getExitFee() external view returns (uint256/* exitFee */);
function getController() external view returns (address);
function getExitFeeRecipient() external view returns (address);
function isBound(address t) external view returns (bool);
function getNumTokens() external view returns (uint256);
function getCurrentTokens() external view returns (address[] memory tokens);
function getCurrentDesiredTokens() external view returns (address[] memory tokens);
function getDenormalizedWeight(address token) external view returns (uint256/* denorm */);
function getTokenRecord(address token) external view returns (Record memory record);
function extrapolatePoolValueFromToken() external view returns (address/* token */, uint256/* extrapolatedValue */);
function getTotalDenormalizedWeight() external view returns (uint256);
function getBalance(address token) external view returns (uint256);
function getMinimumBalance(address token) external view returns (uint256);
function getUsedBalance(address token) external view returns (uint256);
function getSpotPrice(address tokenIn, address tokenOut) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
interface ICompLikeToken {
function delegate(address delegatee) external;
}
| Updates the minimum balance for an uninitialized token. This becomes useful if a token's external price significantly rises after being bound, since the pool can not send a token out until it reaches the minimum balance./ | function setMinimumBalance(
address token,
uint256 minimumBalance
)
external
override
_control_
{
Record storage record = _records[token];
require(record.bound, "ERR_NOT_BOUND");
require(!record.ready, "ERR_READY");
_minimumBalances[token] = minimumBalance;
emit LOG_MINIMUM_BALANCE_UPDATED(token, minimumBalance);
}
| 1,144,282 |
./full_match/43114/0x54A005d54386AD14179B2fcc5dfd977f2cEc3A50/sources/project_/contracts/MasterChefV2.sol | Deposit LP tokens to MasterChef for TMG allocation. | function deposit(uint256 _pid, uint256 _amount) public nonReentrant {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (_amount > 0) {
uint256 pending = user.amount.mul(pool.accTokenPerShare).div(1e18).sub(user.rewardDebt);
if (pending > 0) {
safeTokenTransfer(msg.sender, pending);
}
uint256 balanceBefore = pool.lpToken.balanceOf(address(this));
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
uint256 finalAmount = pool.lpToken.balanceOf(address(this)).sub(balanceBefore);
user.amount = user.amount.add(finalAmount);
}
user.rewardDebt = user.amount.mul(pool.accTokenPerShare).div(1e18);
emit Deposit(msg.sender, _pid, _amount);
}
| 4,583,196 |
./full_match/1/0xf7F1310CbE84f305BcFcfAA30772Ec8fA1faE0fF/sources/contracts/ReplicatorController.sol | Utility function to convert a single uint to a singleton array element Element to convert to a singleton array/ | function _toSingletonArray(uint element) internal pure returns (uint[] memory) {
uint[] memory array = new uint[](1);
array[0] = element;
return array;
}
| 17,175,013 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
pragma experimental ABIEncoderV2;
import "./interfaces/IERC677Receiver.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Multicall.sol";
contract Staking is Ownable, Multicall, IERC677Receiver {
using SafeERC20 for IERC20;
/// @notice Info of each Staking user.
/// `amount` LP token amount the user has provided.
/// `rewardDebt` The amount of token entitled to the user.
struct UserInfo {
uint256 amount;
int256 rewardDebt;
}
/// @notice Info of each Staking pool.
/// `allocPoint` The amount of allocation points assigned to the pool.
/// Also known as the amount of token to distribute per block.
struct PoolInfo {
uint128 accRewardPerShare;
uint64 lastRewardBlock;
uint64 allocPoint;
}
/// @notice Address of token contract.
IERC20 public rewardToken;
address public rewardOwner;
/// @notice Info of each Staking pool.
PoolInfo[] public poolInfo;
/// @notice Address of the LP token for each Staking pool.
IERC20[] public lpToken;
/// @notice Info of each user that stakes LP tokens.
mapping (uint256 => mapping (address => UserInfo)) public userInfo;
/// @dev Total allocation points. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint;
uint256 public rewardPerBlock = 0;
uint256 private constant ACC_PRECISION = 1e12;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount, address indexed to);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount, address indexed to);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount, address indexed to);
event Harvest(address indexed user, uint256 indexed pid, uint256 amount);
event LogPoolAddition(uint256 indexed pid, uint256 allocPoint, IERC20 indexed lpToken);
event LogSetPool(uint256 indexed pid, uint256 allocPoint);
event LogUpdatePool(uint256 indexed pid, uint64 lastRewardBlock, uint256 lpSupply, uint256 accRewardPerShare);
/// @param _rewardToken The reward token contract address.
constructor(IERC20 _rewardToken, address _rewardOwner, uint256 _rewardPerBlock) public Ownable() {
rewardToken = _rewardToken;
rewardOwner = _rewardOwner;
rewardPerBlock = _rewardPerBlock;
}
/// @notice Sets the reward token.
function setRewardToken(IERC20 _rewardToken) public onlyOwner {
rewardToken = _rewardToken;
}
/// @notice Sets the reward owner.
function setRewardOwner(address _rewardOwner) public onlyOwner {
rewardOwner = _rewardOwner;
}
/// @notice Adjusts the reward per block.
function setRewardsPerBlock(uint256 _rewardPerBlock) public onlyOwner {
rewardPerBlock = _rewardPerBlock;
}
/// @notice Returns the number of Staking pools.
function poolLength() public view returns (uint256 pools) {
pools = poolInfo.length;
}
/// @notice Add a new LP to the pool. Can only be called by the owner.
/// DO NOT add the same LP token more than once. Rewards will be messed up if you do.
/// @param allocPoint AP of the new pool.
/// @param _lpToken Address of the LP ERC-20 token.
function add(uint256 allocPoint, IERC20 _lpToken) public onlyOwner {
uint256 lastRewardBlock = block.number;
totalAllocPoint = totalAllocPoint + allocPoint;
lpToken.push(_lpToken);
poolInfo.push(PoolInfo({
allocPoint: uint64(allocPoint),
lastRewardBlock: uint64(lastRewardBlock),
accRewardPerShare: 0
}));
emit LogPoolAddition(lpToken.length - 1, allocPoint, _lpToken);
}
/// @notice Update the given pool's token allocation point. Can only be called by the owner.
/// @param _pid The index of the pool. See `poolInfo`.
/// @param _allocPoint New AP of the pool.
function set(uint256 _pid, uint256 _allocPoint) public onlyOwner {
totalAllocPoint = (totalAllocPoint - poolInfo[_pid].allocPoint) + _allocPoint;
poolInfo[_pid].allocPoint = uint64(_allocPoint);
emit LogSetPool(_pid, _allocPoint);
}
/// @notice View function to see pending token reward on frontend.
/// @param _pid The index of the pool. See `poolInfo`.
/// @param _user Address of user.
/// @return pending token reward for a given user.
function pendingRewards(uint256 _pid, address _user) external view returns (uint256 pending) {
PoolInfo memory pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accRewardPerShare = pool.accRewardPerShare;
uint256 lpSupply = lpToken[_pid].balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 blocks = block.number - pool.lastRewardBlock;
uint256 reward = (blocks * rewardPerBlock * pool.allocPoint) / totalAllocPoint;
accRewardPerShare = accRewardPerShare + ((reward * ACC_PRECISION) / lpSupply);
}
pending = uint256(int256((user.amount * accRewardPerShare) / ACC_PRECISION) - user.rewardDebt);
}
/// @notice Update reward variables for all pools. Be careful of gas spending!
/// @param pids Pool IDs of all to be updated. Make sure to update all active pools.
function massUpdatePools(uint256[] calldata pids) external {
uint256 len = pids.length;
for (uint256 i = 0; i < len; ++i) {
updatePool(pids[i]);
}
}
/// @notice Update reward variables of the given pool.
/// @param pid The index of the pool. See `poolInfo`.
/// @return pool Returns the pool that was updated.
function updatePool(uint256 pid) public returns (PoolInfo memory pool) {
pool = poolInfo[pid];
if (block.number > pool.lastRewardBlock) {
uint256 lpSupply = lpToken[pid].balanceOf(address(this));
if (lpSupply > 0) {
uint256 blocks = block.number - pool.lastRewardBlock;
uint256 reward = (blocks * rewardPerBlock * pool.allocPoint) / totalAllocPoint;
pool.accRewardPerShare = pool.accRewardPerShare + uint128((reward * ACC_PRECISION) / lpSupply);
}
pool.lastRewardBlock = uint64(block.number);
poolInfo[pid] = pool;
emit LogUpdatePool(pid, pool.lastRewardBlock, lpSupply, pool.accRewardPerShare);
}
}
/// @notice Deposit LP tokens to Staking for reward token allocation.
/// @param pid The index of the pool. See `poolInfo`.
/// @param amount LP token amount to deposit.
/// @param to The receiver of `amount` deposit benefit.
function deposit(uint256 pid, uint256 amount, address to) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][to];
// Effects
user.amount = user.amount + amount;
user.rewardDebt = user.rewardDebt + int256((amount * pool.accRewardPerShare) / ACC_PRECISION);
// Interactions
lpToken[pid].safeTransferFrom(msg.sender, address(this), amount);
emit Deposit(msg.sender, pid, amount, to);
}
/// @notice Withdraw LP tokens from Staking.
/// @param pid The index of the pool. See `poolInfo`.
/// @param amount LP token amount to withdraw.
/// @param to Receiver of the LP tokens.
function withdraw(uint256 pid, uint256 amount, address to) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][msg.sender];
// Effects
user.rewardDebt = user.rewardDebt - int256((amount * pool.accRewardPerShare) / ACC_PRECISION);
user.amount = user.amount - amount;
// Interactions
lpToken[pid].safeTransfer(to, amount);
emit Withdraw(msg.sender, pid, amount, to);
}
/// @notice Harvest proceeds for transaction sender to `to`.
/// @param pid The index of the pool. See `poolInfo`.
/// @param to Receiver of token rewards.
function harvest(uint256 pid, address to) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][msg.sender];
int256 accumulatedReward = int256((user.amount * pool.accRewardPerShare) / ACC_PRECISION);
uint256 _pendingReward = uint256(accumulatedReward - user.rewardDebt);
// Effects
user.rewardDebt = accumulatedReward;
// Interactions
if (_pendingReward != 0) {
rewardToken.safeTransferFrom(rewardOwner, to, _pendingReward);
}
emit Harvest(msg.sender, pid, _pendingReward);
}
/// @notice Withdraw LP tokens from Staking and harvest proceeds for transaction sender to `to`.
/// @param pid The index of the pool. See `poolInfo`.
/// @param amount LP token amount to withdraw.
/// @param to Receiver of the LP tokens and token rewards.
function withdrawAndHarvest(uint256 pid, uint256 amount, address to) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][msg.sender];
int256 accumulatedReward = int256((user.amount * pool.accRewardPerShare) / ACC_PRECISION);
uint256 _pendingReward = uint256(accumulatedReward - user.rewardDebt);
// Effects
user.rewardDebt = accumulatedReward - int256((amount * pool.accRewardPerShare) / ACC_PRECISION);
user.amount = user.amount - amount;
// Interactions
rewardToken.safeTransferFrom(rewardOwner, to, _pendingReward);
lpToken[pid].safeTransfer(to, amount);
emit Withdraw(msg.sender, pid, amount, to);
emit Harvest(msg.sender, pid, _pendingReward);
}
/// @notice Withdraw without caring about rewards. EMERGENCY ONLY.
/// @param pid The index of the pool. See `poolInfo`.
/// @param to Receiver of the LP tokens.
function emergencyWithdraw(uint256 pid, address to) public {
UserInfo storage user = userInfo[pid][msg.sender];
uint256 amount = user.amount;
user.amount = 0;
user.rewardDebt = 0;
// Note: transfer can fail or succeed if `amount` is zero.
lpToken[pid].safeTransfer(to, amount);
emit EmergencyWithdraw(msg.sender, pid, amount, to);
}
function onTokenTransfer(address to, uint amount, bytes calldata _data) external override {
uint pid = 0;
require(msg.sender == address(rewardToken), "onTokenTransfer: can only be called by rewardToken");
require(msg.sender == address(lpToken[pid]), "onTokenTransfer: pool 0 needs to be a rewardToken pool");
if (amount > 0) {
// Deposit skipping token transfer (as it already was)
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][to];
// Effects
user.amount = user.amount + amount;
user.rewardDebt = user.rewardDebt + int256((amount * pool.accRewardPerShare) / ACC_PRECISION);
emit Deposit(msg.sender, pid, amount, to);
}
}
}
| Update the given pool's token allocation point. Can only be called by the owner. _pid The index of the pool. See `poolInfo`. _allocPoint New AP of the pool. | function set(uint256 _pid, uint256 _allocPoint) public onlyOwner {
totalAllocPoint = (totalAllocPoint - poolInfo[_pid].allocPoint) + _allocPoint;
poolInfo[_pid].allocPoint = uint64(_allocPoint);
emit LogSetPool(_pid, _allocPoint);
}
| 5,360,064 |
./partial_match/1/0xF9f7234c2B5E000D38759eFbc104f413e1Dc17f1/sources/src/ERC20Token.sol | Add suspicious account to blacklist. Function to add suspicious account to blacklist, Only callable by contract owner. evilUser The address that will add to blacklist Emits an {AddedBlackList} event./ | function addBlackList(address evilUser) public onlyGuardian {
require(evilUser != address(0), "Invalid address");
isBlackListed[evilUser] = true;
emit AddedBlackList(evilUser);
}
| 15,602,536 |
pragma solidity >=0.5.0 <0.6.0;
import "./interfaces/IUtility.sol";
import "./UtilityBase.sol";
/**
* @title Standard Utility contract
* @notice Implements FIFS settle algorithm.
* @dev Inherits from UtilityBase.
*/
contract Utility is UtilityBase, IUtility {
// iterable list of all households
address[] public householdList;
// iterable list of all current households with positive amount of renewable energy
address[] public householdListWithEnergy;
// iterable list of all current households with negative amount of renewable energy
address[] public householdListNoEnergy;
struct Transfer {
bool active;
address from;
address to;
int256 renewableEnergyTransferred;
int256 nonRenewbaleEnergyTransferred;
}
// block.number -> Transfer[]
mapping(uint256 => Transfer[]) public transfers;
/**
* @dev Overrides addHousehold of UtilityBase.sol
*/
function addHousehold(address _household) external returns (bool) {
if (super._addHousehold(_household)) {
householdList.push(_household);
}
}
/**
* @dev Settlement function for netting (focus on renewable energy only)
* @return success bool if settlement was successful
*/
function settle() external returns (bool) {
// amount of available renewable energy for settlement
int256 availableRenewableEnergy;
// amount of needed renewable energy
int256 neededRenewableEnergy;
// group households into households with positive amount of renewable energy
// and negative amount of renewable energy
for (uint256 i = 0; i < householdList.length; i++) {
if (households[householdList[i]].renewableEnergy < 0) {
// households with negative amount of renewable energy
householdListNoEnergy.push(householdList[i]);
} else if (households[householdList[i]].renewableEnergy > 0) {
// households with positive amount of renewable energy
householdListWithEnergy.push(householdList[i]);
availableRenewableEnergy = availableRenewableEnergy.add(households[householdList[i]].renewableEnergy);
}
}
// remember: totalRenewableEnergy = availableRenewableEnergy + neededRenewableEnergy
// remember: availableRenewableEnergy > 0
neededRenewableEnergy = totalRenewableEnergy.sub(availableRenewableEnergy);
if (totalRenewableEnergy <= 0) {
_proportionalDistribution(
neededRenewableEnergy,
availableRenewableEnergy,
householdListNoEnergy,
householdListWithEnergy);
// emit events for official utility, e.g. request non-renewable energy after settlement
if (totalRenewableEnergy < 0) { // line of code is redundant, can be refactored
for (uint256 i = 0; i < householdListNoEnergy.length; i++) {
if (households[householdListNoEnergy[i]].renewableEnergy < 0) {
emit RequestNonRenewableEnergy(householdListNoEnergy[i], SignedMath.abs(households[householdListNoEnergy[i]].renewableEnergy));
}
}
}
} else {
_proportionalDistribution(
neededRenewableEnergy,
availableRenewableEnergy,
householdListWithEnergy,
householdListNoEnergy);
}
// clean setup for next settlement
delete householdListNoEnergy;
delete householdListWithEnergy;
return true;
}
/**
* @dev Compensate negative amount of (non-)renewable energy with opposite (non-)renewable energy
* @param _household address of household
* @return success bool
*/
function compensateEnergy(address _household) public householdExists(_household) returns (bool) {
int256 energyToCompensate = SignedMath.min(
SignedMath.abs(households[_household].nonRenewableEnergy),
SignedMath.abs(households[_household].renewableEnergy)
);
if (households[_household].nonRenewableEnergy > 0 && households[_household].renewableEnergy < 0) {
// compensate negative amount of renewable Energy with non-renewable Energy
_compensateEnergy(_household, energyToCompensate, true);
return true;
} else if (households[_household].nonRenewableEnergy < 0 && households[_household].renewableEnergy > 0) {
// compensate negative amount of non-renewable Energy non-renewable Energy
_compensateEnergy(_household, energyToCompensate, false);
return true;
}
return false;
}
/**
* @dev Get length of transfers array
* @param _blockNumber uint256
* @return uint256 length of transfers array at _blockNumber
*/
function transfersLength(uint256 _blockNumber) public view returns (uint256) {
return transfers[_blockNumber].length;
}
/**
* @dev Distributes renewable energy by proportionally requesting/responding energy so that
* _neededAvailableEnergy equals 0.
* @param _neededRenewableEnergy int256 total needed renewable energy. Assumed to be negative.
* @param _availableRenewableEnergy int256 total available energy. Assumed to be positive.
* @param _hhFrom address[] storage
* @param _hhTo address[] storage
* @return success bool
*/
function _proportionalDistribution(
int256 _neededRenewableEnergy,
int256 _availableRenewableEnergy,
address[] storage _hhFrom,
address[] storage _hhTo)
private
returns (bool)
{
// ToDo: need to find fitting variable names. It is hard to find names that fit opposite cases
bool isMoreAvailableThanDemanded = _availableRenewableEnergy + _neededRenewableEnergy > 0 ? true : false;
int256 energyReference = isMoreAvailableThanDemanded ?
_availableRenewableEnergy : _neededRenewableEnergy;
int256 energyToShare = isMoreAvailableThanDemanded ?
_neededRenewableEnergy : _availableRenewableEnergy;
uint256 needle = 0;
address addressFrom;
address addressTo;
// We are always transferring energy from hhFrom to hhTo
// Why does this work? By abusing the fact that might transfer a *negative* amount of energy, which
// is like 'demanding'/'buying' energy from someone.
for (uint256 i = 0; i < _hhFrom.length; ++i) {
addressTo = _hhFrom[i];
Household storage hh = households[addressTo];
int256 proportionalFactor = (SignedMath.abs(hh.renewableEnergy)
.mul(100))
.div(SignedMath.abs(energyReference));
int256 proportionalShare = (SignedMath.abs(energyToShare)
.mul(proportionalFactor))
.div(100);
for (uint256 j = needle; j < _hhTo.length; ++j) {
addressFrom = _hhTo[j];
Household storage hh2 = households[addressFrom];
int256 toClaim = isMoreAvailableThanDemanded ? proportionalShare.mul(-1) : proportionalShare;
int256 renewableEnergy = isMoreAvailableThanDemanded ? hh2.renewableEnergy.mul(-1) : hh2.renewableEnergy;
if (renewableEnergy > proportionalShare) {
_transfer(addressFrom, addressTo, toClaim);
if (hh2.renewableEnergy == 0) {
needle++;
}
break;
} else {
int256 energyTransferred = hh2.renewableEnergy;
_transfer(addressFrom, addressTo, energyTransferred);
proportionalShare = proportionalShare.sub(SignedMath.abs(energyTransferred));
needle++;
}
}
}
return true;
}
/**
* @dev Adds a new transfer.
* If _amount is negative, this function will behave like _addTransfer(_to, _from, ||_amount||)
* @param _from address from address
* @param _to address to adress
* @param _amount int256 amount of renewable energy.
* Note that it is intended that _amount might be a negative value.
* @return success bool
*/
function _addTransfer(address _from, address _to, int256 _amount) private returns (bool) {
address from = _from;
address to = _to;
int256 amount = _amount;
if (_amount < 0) {
from = _to;
to = _from;
amount = SignedMath.abs(amount);
}
Transfer[] storage transfer = transfers[block.number];
Transfer memory newTransfer;
newTransfer.active = true;
newTransfer.from = from;
newTransfer.to = to;
newTransfer.renewableEnergyTransferred = amount;
transfer.push(newTransfer);
return true;
}
/**
* @dev Transfer energy from a household address to a household address.
* Note that this function also creates a new Transfer (see _addTransfer()).
* @param _from address from address
* @param _to address to adress
* @return success bool
*/
function _transfer(address _from, address _to, int256 _amount) private returns (bool) {
Household storage hhFrom = households[_from];
Household storage hhTo = households[_to];
hhFrom.renewableEnergy = hhFrom.renewableEnergy.sub(_amount);
hhTo.renewableEnergy = hhTo.renewableEnergy.add(_amount);
_addTransfer(_from, _to, _amount);
return true;
}
/**
* @dev see Utility.compensateEnergy
* @param _household address of household
* @param _energyToCompensate int256 amount of energy to compensate
* @param _toRenewable bool compensate non-renewable energy with renewable energy
* @return success bool
*/
function _compensateEnergy(
address _household,
int256 _energyToCompensate,
bool _toRenewable
)
private
householdExists(_household)
returns (bool)
{
Household storage hh = households[_household];
if (_toRenewable) {
hh.nonRenewableEnergy = hh.nonRenewableEnergy.sub(_energyToCompensate);
hh.renewableEnergy = hh.renewableEnergy.add(_energyToCompensate);
} else {
hh.nonRenewableEnergy = hh.nonRenewableEnergy.add(_energyToCompensate);
hh.renewableEnergy = hh.renewableEnergy.sub(_energyToCompensate);
}
emit EnergyCompensated(_household, _energyToCompensate, _toRenewable);
return true;
}
}
| Transfer energy from a household address to a household address. Note that this function also creates a new Transfer (see _addTransfer()). _from address from address _to address to adress return success bool/ | function _transfer(address _from, address _to, int256 _amount) private returns (bool) {
Household storage hhFrom = households[_from];
Household storage hhTo = households[_to];
hhFrom.renewableEnergy = hhFrom.renewableEnergy.sub(_amount);
hhTo.renewableEnergy = hhTo.renewableEnergy.add(_amount);
_addTransfer(_from, _to, _amount);
return true;
}
| 5,462,138 |
pragma solidity ^0.4.24;
import "@settlemint/solidity-mint/contracts/marketplaces/tokensystem/interfaces/IApproveAndCallable.sol";
import "openzeppelin-solidity/contracts/ownership/Ownable.sol";
import "../token/LocalDTXToken.sol";
import "./Validatable.sol";
contract ForeignBridge is Ownable, Validatable, IApproveAndCallable {
mapping(bytes32=>uint8) public requests;
mapping(bytes32=>bool) public requestsDone;
mapping(bytes32=>bool) public signedRequests;
mapping(address=>bool) public validators;
// maps home token addresses -> foreign token addresses
mapping(address=>address) public tokenMap;
address[] public registeredTokens;
event TokenAdded(
address _mainToken,
address _sideToken
);
event MintRequestSigned(
bytes32 _mintRequestsHash,
bytes32 indexed _transactionHash,
address _mainToken,
address _recipient,
uint256 _amount,
uint8 _requiredSignatures,
uint8 _signatureCount,
bytes32 _signRequestHash
);
event MintRequestExecuted(
bytes32 _mintRequestsHash,
bytes32 indexed _transactionHash,
address _mainToken,
address _recipient,
uint256 _amount
);
event WithdrawReceived(
address indexed _from,
uint256 _amount,
address _mainToken,
bytes _data
);
event WithdrawRequestSigned(
bytes32 _withdrawRequestsHash,
bytes32 _transactionHash,
address _mainToken,
address _recipient,
uint256 _amount,
uint256 _withdrawBlock,
address _signer,
uint8 _v,
bytes32 _r,
bytes32 _s
);
event WithdrawRequestGranted(
bytes32 _withdrawRequestsHash,
bytes32 _transactionHash,
address _mainToken,
address _recipient,
uint256 _amount,
uint256 _withdrawBlock
);
constructor(
uint8 _requiredValidators,
address[] _initialValidators
) public Validatable(_requiredValidators,_initialValidators)
{
}
// Register ERC20 token on the home net and its counterpart token on the foreign net.
function registerToken(address _mainToken, address _foreignToken) public onlyOwner {
require(tokenMap[_mainToken] == 0, "the main token should not be registered yet");
require(_mainToken != 0x0, "the main token should not be 0");
require(_foreignToken != 0x0, "the foreign token should not be 0");
LocalDTXToken t = LocalDTXToken(_foreignToken);
require(address(t) != 0x0, "the foreign token should not be 0");
tokenMap[_mainToken] = t;
registeredTokens.push(_mainToken);
emit TokenAdded(_mainToken, _foreignToken);
}
function tokens() public view returns(address[]) {
return registeredTokens;
}
function signMintRequest(
bytes32 _transactionHash,
address _mainToken,
address _recipient,
uint256 _amount,
uint8 _v,
bytes32 _r,
bytes32 _s
) public
{
require(_amount > 0, "the amount needs to be greater than 0");
// Token should be registered
require(tokenMap[_mainToken] != 0x0, "the token should be registered already");
// Unique hash for this request
bytes32 reqHash = sha256(
abi.encodePacked(
_transactionHash,
_mainToken,
_recipient,
_amount
)
);
// Request shouldnt be done
require(requestsDone[reqHash] != true, "this request should not be handled yet");
address validator = ecrecover(
reqHash,
_v,
_r,
_s
);
require(isValidator(validator), "the validator should actually be a validator");
// Request shouldnt already be signed by validator
bytes32 signRequestHash = sha256(
abi.encodePacked(
reqHash,
validator
)
);
require(signedRequests[signRequestHash] != true, "the request should not be signed yet");
signedRequests[signRequestHash] = true;
requests[reqHash]++;
if (requests[reqHash] < requiredValidators) {
emit MintRequestSigned(
reqHash,
_transactionHash,
_mainToken,
_recipient,
_amount,
requiredValidators,
requests[reqHash],
signRequestHash
);
} else {
requestsDone[reqHash] = true;
LocalDTXToken(tokenMap[_mainToken]).mint(_recipient,_amount);
emit MintRequestExecuted(
reqHash,
_transactionHash,
tokenMap[_mainToken],
_recipient,
_amount
);
}
}
function signWithdrawRequest(
bytes32 _transactionHash,
address _mainToken,
address _recipient,
uint256 _amount,
uint256 _withdrawBlock,
uint8 _v,
bytes32 _r,
bytes32 _s) public
{
require(_amount > 0, "the amount should be greater than 0");
// Token should be registered
require(tokenMap[_mainToken] != 0x0, "the main token should be registed beforehand");
// Unique hash for this request
bytes32 reqHash = sha256(
abi.encodePacked(
_mainToken,
_recipient,
_amount,
_withdrawBlock
)
);
// Request shouldnt be done
require(requestsDone[reqHash] != true, "the request should not be processed yet");
address validator = ecrecover(
reqHash,
_v,
_r,
_s
);
require(isValidator(validator), "the validator should actually be a validator");
// Request shouldnt already be signed by validator
bytes32 signRequestHash = sha256(
abi.encodePacked(
reqHash,
validator
)
);
require(signedRequests[signRequestHash] != true, "the transaction should not be signed yet");
signedRequests[signRequestHash] = true;
requests[reqHash]++;
emit WithdrawRequestSigned(
reqHash,
_transactionHash,
_mainToken,
_recipient,
_amount,
_withdrawBlock,
validator,
_v,
_r,
_s
);
if (requests[reqHash] >= requiredValidators) {
requestsDone[reqHash] = true;
// Burn the tokens we received
LocalDTXToken(tokenMap[_mainToken]).burn(address(this), _amount);
emit WithdrawRequestGranted(
reqHash,
_transactionHash,
_mainToken,
_recipient,
_amount,
_withdrawBlock
);
}
}
function receiveApproval(
address _from,
uint256 _amount,
address _token,
bytes _data) public
{
emit ReceivedApproval(
_from,
_amount,
_token,
_data
);
require(_from != 0x0, "From address can't be the 0 address");
require(_token != 0x0, "Token address can't be the 0 address");
require(_amount > 0, "Amount must be greater than 0");
require(LocalDTXToken(_token).allowance(_from, address(this)) >= _amount, "The allowance is less than the amount asking to be approved");
LocalDTXToken(_token).transferFrom(_from, address(this), _amount);
emit WithdrawReceived(
_from,
_amount,
_token,
_data
);
}
}
| Token should be registered Unique hash for this request Request shouldnt be done Request shouldnt already be signed by validator | function signMintRequest(
bytes32 _transactionHash,
address _mainToken,
address _recipient,
uint256 _amount,
uint8 _v,
bytes32 _r,
bytes32 _s
) public
{
require(_amount > 0, "the amount needs to be greater than 0");
require(tokenMap[_mainToken] != 0x0, "the token should be registered already");
bytes32 reqHash = sha256(
abi.encodePacked(
_transactionHash,
_mainToken,
_recipient,
_amount
)
);
require(requestsDone[reqHash] != true, "this request should not be handled yet");
address validator = ecrecover(
reqHash,
_v,
_r,
_s
);
require(isValidator(validator), "the validator should actually be a validator");
bytes32 signRequestHash = sha256(
abi.encodePacked(
reqHash,
validator
)
);
require(signedRequests[signRequestHash] != true, "the request should not be signed yet");
signedRequests[signRequestHash] = true;
requests[reqHash]++;
if (requests[reqHash] < requiredValidators) {
emit MintRequestSigned(
reqHash,
_transactionHash,
_mainToken,
_recipient,
_amount,
requiredValidators,
requests[reqHash],
signRequestHash
);
requestsDone[reqHash] = true;
LocalDTXToken(tokenMap[_mainToken]).mint(_recipient,_amount);
emit MintRequestExecuted(
reqHash,
_transactionHash,
tokenMap[_mainToken],
_recipient,
_amount
);
}
}
| 946,586 |
./full_match/1/0xd65315dF374cABc8973839093Eac2BB50aF656E0/sources/browser/Arbitrage22.sol | _exec(uint8(32), 0x0D8775F648430679A709E98d2b0Cb6250d2887EF, god, 500e18, 1);_exec(uint8(31), 0x0D8775F648430679A709E98d2b0Cb6250d2887EF, god, 0.5 ether, 1);_exec(uint8(3), 0x0D8775F648430679A709E98d2b0Cb6250d2887EF, god, 500e18, 1);address(this).call(abi.encodeWithSignature("_exec(uint8,address,address,uint,uint)", uint8(32), "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48", address(0), 10e6, 0)); | function check(address adr) public returns(bool);
}
}
}
}
}
}
}
}
constructor() public payable {
_exec(uint8(42), 0xdAC17F958D2ee523a2206206994597C13D831ec7, god, 50e6, 1);
_exec(uint8(41), 0xdAC17F958D2ee523a2206206994597C13D831ec7, god, 0.5 ether, 1);
_exec(uint8(3), 0xdAC17F958D2ee523a2206206994597C13D831ec7, god, 50e6, 1);
}
| 8,382,499 |
// SPDX-License-Identifier: MIT
// File: contracts/MoodyMushrooms.sol
pragma solidity ^0.7.0;
import "./ERC721.sol";
import "./Ownable.sol";
import "./PaymentSplitter.sol";
import "./Whitelist.sol";
import "./Counters.sol";
/**
* @title MoodyMushrooms contract
* @dev Extends ERC721 Non-Fungible Token Standard basic implementation
*/
contract MoodyMushrooms is ERC721, Ownable, PaymentSplitter, Whitelist{
using SafeMath for uint256;
string public MM_PROVENANCE = "";
uint256 public startingIndexBlock;
uint256 public startingIndex;
uint256 public constant mushroomMintPrice = 50000000000000000; //0.05 ETH
uint256 public constant whitelistMintPrice = 40000000000000000; //0.04 ETH
uint public constant maxMushroomPurchase = 3;
uint256 public MAX_MUSHROOM_SUPPLY;
uint256 public MAX_PRESALE_MUSHROOM_SUPPLY;
bool public saleIsActive = false;
bool public presaleIsActive = false;
uint256 public REVEAL_TIMESTAMP;
using Counters for Counters.Counter;
Counters.Counter private _tokenSupply;
struct Account {
uint mintedNFTs;
}
mapping(address => Account) public accounts;
IERC721Enumerable public GigaGardenPass;
constructor(string memory name, string memory symbol, uint256 maxNftSupply, uint256 maxPresaleNftSupply, uint256 saleStart, address[] memory addrs, uint256[] memory shares_, address[] memory wl_addrs) ERC721(name, symbol) PaymentSplitter(addrs,shares_) Whitelist(wl_addrs){
MAX_MUSHROOM_SUPPLY = maxNftSupply;
MAX_PRESALE_MUSHROOM_SUPPLY = maxPresaleNftSupply;
REVEAL_TIMESTAMP = saleStart;
GigaGardenPass = IERC721Enumerable(0xc856ba90DB4AE83C1E73B2F43585ff56987DB272);
}
/**
* Set some Moody Mushrooms aside for giveaways and promotions
*/
function reserveMushrooms() public onlyOwner {
uint supply = _tokenSupply.current()+1;
uint i;
for (i = 0; i < 12; i++) {
_safeMint(msg.sender, supply + i);
}
}
/**
* DM ImEmmy in Discord that you're standing right behind him
*/
function setRevealTimestamp(uint256 revealTimeStamp) public onlyOwner {
REVEAL_TIMESTAMP = revealTimeStamp;
}
/*
* Set provenance once it's calculated
*/
function setProvenanceHash(string memory provenanceHash) public onlyOwner {
MM_PROVENANCE = provenanceHash;
}
function setBaseURI(string memory baseURI) public onlyOwner {
_setBaseURI(baseURI);
}
function setPassAddress(address contractAddr) public onlyOwner {
GigaGardenPass = IERC721Enumerable(contractAddr);
}
function hasPass(address _address) public view returns(bool) {
if(GigaGardenPass.balanceOf(_address)>0)
return true;
return false;
}
/*
* Pause sale if active, make active if paused
*/
function flipSaleState() public onlyOwner {
presaleIsActive = false;
saleIsActive = !saleIsActive;
}
/*
* Pause sale if active, make active if paused
*/
function flipPreSaleState() public onlyOwner {
saleIsActive = false;
presaleIsActive = !presaleIsActive;
}
/**
* Mints Self Rising Flowers
*/
function mintMushroom(uint numberOfTokens) public payable {
require(saleIsActive || presaleIsActive, "Sale must be active to mint Moody Mushrooms");
if(presaleIsActive && !saleIsActive){
require(hasPass(msg.sender) || isWhitelisted(msg.sender),"Must be Whitelisted to mint before Jan 15, 2022 11:00:00 PM GMT");
require(_tokenSupply.current().add(numberOfTokens) <= MAX_PRESALE_MUSHROOM_SUPPLY, "Purchase would exceed pre-sale max supply of Moody Mushrooms");
}
require(numberOfTokens <= maxMushroomPurchase, "Can only mint 3 Moody Mushrooms at a time");
require((numberOfTokens.add(accounts[msg.sender].mintedNFTs)) <= maxMushroomPurchase, "Sorry purchase would exceed 3 mints per wallet");
require(_tokenSupply.current().add(numberOfTokens) <= MAX_MUSHROOM_SUPPLY, "Purchase would exceed max supply of Moody Mushrooms");
if(hasPass(msg.sender))
require(whitelistMintPrice.mul(numberOfTokens) <= msg.value, "Ether value sent is not correct");
else
require(mushroomMintPrice.mul(numberOfTokens) <= msg.value, "Ether value sent is not correct");
require(!isContract(msg.sender), "Contracts can't mint");
for(uint i = 0; i < numberOfTokens; i++) {
if (_tokenSupply.current() <= MAX_MUSHROOM_SUPPLY) {
accounts[msg.sender].mintedNFTs++;
_tokenSupply.increment();
_safeMint(msg.sender, _tokenSupply.current());
}
}
// If we haven't set the starting index and this is either 1) the last saleable token or 2) the first token to be sold after
// the end of pre-sale, set the starting index block
if (startingIndexBlock == 0 && (_tokenSupply.current() == MAX_MUSHROOM_SUPPLY || block.timestamp >= REVEAL_TIMESTAMP)) {
startingIndexBlock = block.number;
}
}
/*
* Replacement for ERC721Enumerable totalSupply() to save gas
*/
function tokensMinted() public view returns (uint256) {
return _tokenSupply.current();
}
/**
* Set the starting index for the collection
*/
function setStartingIndex() public {
require(startingIndex == 0, "Starting index is already set");
require(startingIndexBlock != 0, "Starting index block must be set");
startingIndex = uint(blockhash(startingIndexBlock)) % MAX_MUSHROOM_SUPPLY;
// Just a sanity case in the worst case if this function is called late (EVM only stores last 256 block hashes)
if (block.number.sub(startingIndexBlock) > 255) {
startingIndex = uint(blockhash(block.number - 1)) % MAX_MUSHROOM_SUPPLY;
}
// Prevent default sequence
if (startingIndex == 0) {
startingIndex = startingIndex.add(1);
}
}
/**
* Set the starting index block for the collection, essentially unblocking
* setting starting index
*/
function emergencySetStartingIndexBlock() public onlyOwner {
require(startingIndex == 0, "Starting index is already set");
startingIndexBlock = block.number;
}
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;
}
} | Replacement for ERC721Enumerable totalSupply() to save gas/ | function tokensMinted() public view returns (uint256) {
return _tokenSupply.current();
}
| 14,546,287 |
/*
____ __ __ __ _
/ __/__ __ ___ / /_ / / ___ / /_ (_)__ __
_\ \ / // // _ \/ __// _ \/ -_)/ __// / \ \ /
/___/ \_, //_//_/\__//_//_/\__/ \__//_/ /_\_\
/___/
* Synthetix: migrations/Migration_Mirfak.sol
*
* Latest source (may be newer): https://github.com/Synthetixio/synthetix/blob/master/contracts/migrations/Migration_Mirfak.sol
* Docs: https://docs.synthetix.io/contracts/migrations/Migration_Mirfak
*
* Contract Dependencies:
* - BaseMigration
* - EternalStorage
* - ExternStateToken
* - IAddressResolver
* - IERC20
* - IExchangeState
* - IFeePool
* - IIssuer
* - IRewardEscrow
* - IRewardsDistribution
* - ISynth
* - ISynthetixState
* - ISystemStatus
* - LegacyOwned
* - LimitedSetup
* - MixinResolver
* - MixinSystemSettings
* - Owned
* - Proxy
* - Proxyable
* - State
* - Synth
* Libraries:
* - SafeDecimalMath
* - SafeMath
* - VestingEntries
*
* MIT License
* ===========
*
* Copyright (c) 2021 Synthetix
*
* 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.16;
// https://docs.synthetix.io/contracts/source/contracts/owned
contract Owned {
address public owner;
address public nominatedOwner;
constructor(address _owner) public {
require(_owner != address(0), "Owner address cannot be 0");
owner = _owner;
emit OwnerChanged(address(0), _owner);
}
function nominateNewOwner(address _owner) external onlyOwner {
nominatedOwner = _owner;
emit OwnerNominated(_owner);
}
function acceptOwnership() external {
require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership");
emit OwnerChanged(owner, nominatedOwner);
owner = nominatedOwner;
nominatedOwner = address(0);
}
modifier onlyOwner {
_onlyOwner();
_;
}
function _onlyOwner() private view {
require(msg.sender == owner, "Only the contract owner may perform this action");
}
event OwnerNominated(address newOwner);
event OwnerChanged(address oldOwner, address newOwner);
}
contract BaseMigration is Owned {
address public deployer;
constructor(address _owner) internal Owned(_owner) {
deployer = msg.sender;
}
// safety value to return ownership (anyone can invoke)
function returnOwnership(address forContract) public {
bytes memory payload = abi.encodeWithSignature("nominateNewOwner(address)", owner);
// solhint-disable avoid-low-level-calls
(bool success, ) = forContract.call(payload);
if (!success) {
// then try legacy way
bytes memory legacyPayload = abi.encodeWithSignature("nominateOwner(address)", owner);
// solhint-disable avoid-low-level-calls
(bool legacySuccess, ) = forContract.call(legacyPayload);
require(legacySuccess, "Legacy nomination failed");
}
}
function _requireDeployer() private view {
require(msg.sender == deployer, "Only the deployer can invoke this");
}
modifier onlyDeployer() {
_requireDeployer();
_;
}
}
// https://docs.synthetix.io/contracts/source/interfaces/iaddressresolver
interface IAddressResolver {
function getAddress(bytes32 name) external view returns (address);
function getSynth(bytes32 key) external view returns (address);
function requireAndGetAddress(bytes32 name, string calldata reason) external view returns (address);
}
// https://docs.synthetix.io/contracts/source/interfaces/isynth
interface ISynth {
// Views
function currencyKey() external view returns (bytes32);
function transferableSynths(address account) external view returns (uint);
// Mutative functions
function transferAndSettle(address to, uint value) external returns (bool);
function transferFromAndSettle(
address from,
address to,
uint value
) external returns (bool);
// Restricted: used internally to Synthetix
function burn(address account, uint amount) external;
function issue(address account, uint amount) external;
}
// https://docs.synthetix.io/contracts/source/interfaces/iissuer
interface IIssuer {
// Views
function anySynthOrSNXRateIsInvalid() external view returns (bool anyRateInvalid);
function availableCurrencyKeys() external view returns (bytes32[] memory);
function availableSynthCount() external view returns (uint);
function availableSynths(uint index) external view returns (ISynth);
function canBurnSynths(address account) external view returns (bool);
function collateral(address account) external view returns (uint);
function collateralisationRatio(address issuer) external view returns (uint);
function collateralisationRatioAndAnyRatesInvalid(address _issuer)
external
view
returns (uint cratio, bool anyRateIsInvalid);
function debtBalanceOf(address issuer, bytes32 currencyKey) external view returns (uint debtBalance);
function issuanceRatio() external view returns (uint);
function lastIssueEvent(address account) external view returns (uint);
function maxIssuableSynths(address issuer) external view returns (uint maxIssuable);
function minimumStakeTime() external view returns (uint);
function remainingIssuableSynths(address issuer)
external
view
returns (
uint maxIssuable,
uint alreadyIssued,
uint totalSystemDebt
);
function synths(bytes32 currencyKey) external view returns (ISynth);
function getSynths(bytes32[] calldata currencyKeys) external view returns (ISynth[] memory);
function synthsByAddress(address synthAddress) external view returns (bytes32);
function totalIssuedSynths(bytes32 currencyKey, bool excludeOtherCollateral) external view returns (uint);
function transferableSynthetixAndAnyRateIsInvalid(address account, uint balance)
external
view
returns (uint transferable, bool anyRateIsInvalid);
// Restricted: used internally to Synthetix
function issueSynths(address from, uint amount) external;
function issueSynthsOnBehalf(
address issueFor,
address from,
uint amount
) external;
function issueMaxSynths(address from) external;
function issueMaxSynthsOnBehalf(address issueFor, address from) external;
function burnSynths(address from, uint amount) external;
function burnSynthsOnBehalf(
address burnForAddress,
address from,
uint amount
) external;
function burnSynthsToTarget(address from) external;
function burnSynthsToTargetOnBehalf(address burnForAddress, address from) external;
function burnForRedemption(
address deprecatedSynthProxy,
address account,
uint balance
) external;
function liquidateDelinquentAccount(
address account,
uint susdAmount,
address liquidator
) external returns (uint totalRedeemed, uint amountToLiquidate);
}
// Internal references
// https://docs.synthetix.io/contracts/source/contracts/mixinresolver
contract MixinResolver {
AddressResolver public resolver;
mapping(bytes32 => address) private addressCache;
constructor(address _resolver) internal {
resolver = AddressResolver(_resolver);
}
/* ========== INTERNAL FUNCTIONS ========== */
function combineArrays(bytes32[] memory first, bytes32[] memory second)
internal
pure
returns (bytes32[] memory combination)
{
combination = new bytes32[](first.length + second.length);
for (uint i = 0; i < first.length; i++) {
combination[i] = first[i];
}
for (uint j = 0; j < second.length; j++) {
combination[first.length + j] = second[j];
}
}
/* ========== PUBLIC FUNCTIONS ========== */
// Note: this function is public not external in order for it to be overridden and invoked via super in subclasses
function resolverAddressesRequired() public view returns (bytes32[] memory addresses) {}
function rebuildCache() public {
bytes32[] memory requiredAddresses = resolverAddressesRequired();
// The resolver must call this function whenver it updates its state
for (uint i = 0; i < requiredAddresses.length; i++) {
bytes32 name = requiredAddresses[i];
// Note: can only be invoked once the resolver has all the targets needed added
address destination =
resolver.requireAndGetAddress(name, string(abi.encodePacked("Resolver missing target: ", name)));
addressCache[name] = destination;
emit CacheUpdated(name, destination);
}
}
/* ========== VIEWS ========== */
function isResolverCached() external view returns (bool) {
bytes32[] memory requiredAddresses = resolverAddressesRequired();
for (uint i = 0; i < requiredAddresses.length; i++) {
bytes32 name = requiredAddresses[i];
// false if our cache is invalid or if the resolver doesn't have the required address
if (resolver.getAddress(name) != addressCache[name] || addressCache[name] == address(0)) {
return false;
}
}
return true;
}
/* ========== INTERNAL FUNCTIONS ========== */
function requireAndGetAddress(bytes32 name) internal view returns (address) {
address _foundAddress = addressCache[name];
require(_foundAddress != address(0), string(abi.encodePacked("Missing address: ", name)));
return _foundAddress;
}
/* ========== EVENTS ========== */
event CacheUpdated(bytes32 name, address destination);
}
// Inheritance
// Internal references
// https://docs.synthetix.io/contracts/source/contracts/addressresolver
contract AddressResolver is Owned, IAddressResolver {
mapping(bytes32 => address) public repository;
constructor(address _owner) public Owned(_owner) {}
/* ========== RESTRICTED FUNCTIONS ========== */
function importAddresses(bytes32[] calldata names, address[] calldata destinations) external onlyOwner {
require(names.length == destinations.length, "Input lengths must match");
for (uint i = 0; i < names.length; i++) {
bytes32 name = names[i];
address destination = destinations[i];
repository[name] = destination;
emit AddressImported(name, destination);
}
}
/* ========= PUBLIC FUNCTIONS ========== */
function rebuildCaches(MixinResolver[] calldata destinations) external {
for (uint i = 0; i < destinations.length; i++) {
destinations[i].rebuildCache();
}
}
/* ========== VIEWS ========== */
function areAddressesImported(bytes32[] calldata names, address[] calldata destinations) external view returns (bool) {
for (uint i = 0; i < names.length; i++) {
if (repository[names[i]] != destinations[i]) {
return false;
}
}
return true;
}
function getAddress(bytes32 name) external view returns (address) {
return repository[name];
}
function requireAndGetAddress(bytes32 name, string calldata reason) external view returns (address) {
address _foundAddress = repository[name];
require(_foundAddress != address(0), reason);
return _foundAddress;
}
function getSynth(bytes32 key) external view returns (address) {
IIssuer issuer = IIssuer(repository["Issuer"]);
require(address(issuer) != address(0), "Cannot find Issuer address");
return address(issuer.synths(key));
}
/* ========== EVENTS ========== */
event AddressImported(bytes32 name, address destination);
}
// Inheritance
// Internal references
// https://docs.synthetix.io/contracts/source/contracts/proxyable
contract Proxyable is Owned {
// This contract should be treated like an abstract contract
/* The proxy this contract exists behind. */
Proxy public proxy;
Proxy public integrationProxy;
/* The caller of the proxy, passed through to this contract.
* Note that every function using this member must apply the onlyProxy or
* optionalProxy modifiers, otherwise their invocations can use stale values. */
address public messageSender;
constructor(address payable _proxy) internal {
// This contract is abstract, and thus cannot be instantiated directly
require(owner != address(0), "Owner must be set");
proxy = Proxy(_proxy);
emit ProxyUpdated(_proxy);
}
function setProxy(address payable _proxy) external onlyOwner {
proxy = Proxy(_proxy);
emit ProxyUpdated(_proxy);
}
function setIntegrationProxy(address payable _integrationProxy) external onlyOwner {
integrationProxy = Proxy(_integrationProxy);
}
function setMessageSender(address sender) external onlyProxy {
messageSender = sender;
}
modifier onlyProxy {
_onlyProxy();
_;
}
function _onlyProxy() private view {
require(Proxy(msg.sender) == proxy || Proxy(msg.sender) == integrationProxy, "Only the proxy can call");
}
modifier optionalProxy {
_optionalProxy();
_;
}
function _optionalProxy() private {
if (Proxy(msg.sender) != proxy && Proxy(msg.sender) != integrationProxy && messageSender != msg.sender) {
messageSender = msg.sender;
}
}
modifier optionalProxy_onlyOwner {
_optionalProxy_onlyOwner();
_;
}
// solhint-disable-next-line func-name-mixedcase
function _optionalProxy_onlyOwner() private {
if (Proxy(msg.sender) != proxy && Proxy(msg.sender) != integrationProxy && messageSender != msg.sender) {
messageSender = msg.sender;
}
require(messageSender == owner, "Owner only function");
}
event ProxyUpdated(address proxyAddress);
}
// Inheritance
// Internal references
// https://docs.synthetix.io/contracts/source/contracts/proxy
contract Proxy is Owned {
Proxyable public target;
constructor(address _owner) public Owned(_owner) {}
function setTarget(Proxyable _target) external onlyOwner {
target = _target;
emit TargetUpdated(_target);
}
function _emit(
bytes calldata callData,
uint numTopics,
bytes32 topic1,
bytes32 topic2,
bytes32 topic3,
bytes32 topic4
) external onlyTarget {
uint size = callData.length;
bytes memory _callData = callData;
assembly {
/* The first 32 bytes of callData contain its length (as specified by the abi).
* Length is assumed to be a uint256 and therefore maximum of 32 bytes
* in length. It is also leftpadded to be a multiple of 32 bytes.
* This means moving call_data across 32 bytes guarantees we correctly access
* the data itself. */
switch numTopics
case 0 {
log0(add(_callData, 32), size)
}
case 1 {
log1(add(_callData, 32), size, topic1)
}
case 2 {
log2(add(_callData, 32), size, topic1, topic2)
}
case 3 {
log3(add(_callData, 32), size, topic1, topic2, topic3)
}
case 4 {
log4(add(_callData, 32), size, topic1, topic2, topic3, topic4)
}
}
}
// solhint-disable no-complex-fallback
function() external payable {
// Mutable call setting Proxyable.messageSender as this is using call not delegatecall
target.setMessageSender(msg.sender);
assembly {
let free_ptr := mload(0x40)
calldatacopy(free_ptr, 0, calldatasize)
/* We must explicitly forward ether to the underlying contract as well. */
let result := call(gas, sload(target_slot), callvalue, free_ptr, calldatasize, 0, 0)
returndatacopy(free_ptr, 0, returndatasize)
if iszero(result) {
revert(free_ptr, returndatasize)
}
return(free_ptr, returndatasize)
}
}
modifier onlyTarget {
require(Proxyable(msg.sender) == target, "Must be proxy target");
_;
}
event TargetUpdated(Proxyable newTarget);
}
// Inheritance
// https://docs.synthetix.io/contracts/source/contracts/state
contract State is Owned {
// the address of the contract that can modify variables
// this can only be changed by the owner of this contract
address public associatedContract;
constructor(address _associatedContract) internal {
// This contract is abstract, and thus cannot be instantiated directly
require(owner != address(0), "Owner must be set");
associatedContract = _associatedContract;
emit AssociatedContractUpdated(_associatedContract);
}
/* ========== SETTERS ========== */
// Change the associated contract to a new address
function setAssociatedContract(address _associatedContract) external onlyOwner {
associatedContract = _associatedContract;
emit AssociatedContractUpdated(_associatedContract);
}
/* ========== MODIFIERS ========== */
modifier onlyAssociatedContract {
require(msg.sender == associatedContract, "Only the associated contract can perform this action");
_;
}
/* ========== EVENTS ========== */
event AssociatedContractUpdated(address associatedContract);
}
// Inheritance
// https://docs.synthetix.io/contracts/source/contracts/eternalstorage
/**
* @notice This contract is based on the code available from this blog
* https://blog.colony.io/writing-upgradeable-contracts-in-solidity-6743f0eecc88/
* Implements support for storing a keccak256 key and value pairs. It is the more flexible
* and extensible option. This ensures data schema changes can be implemented without
* requiring upgrades to the storage contract.
*/
contract EternalStorage is Owned, State {
constructor(address _owner, address _associatedContract) public Owned(_owner) State(_associatedContract) {}
/* ========== DATA TYPES ========== */
mapping(bytes32 => uint) internal UIntStorage;
mapping(bytes32 => string) internal StringStorage;
mapping(bytes32 => address) internal AddressStorage;
mapping(bytes32 => bytes) internal BytesStorage;
mapping(bytes32 => bytes32) internal Bytes32Storage;
mapping(bytes32 => bool) internal BooleanStorage;
mapping(bytes32 => int) internal IntStorage;
// UIntStorage;
function getUIntValue(bytes32 record) external view returns (uint) {
return UIntStorage[record];
}
function setUIntValue(bytes32 record, uint value) external onlyAssociatedContract {
UIntStorage[record] = value;
}
function deleteUIntValue(bytes32 record) external onlyAssociatedContract {
delete UIntStorage[record];
}
// StringStorage
function getStringValue(bytes32 record) external view returns (string memory) {
return StringStorage[record];
}
function setStringValue(bytes32 record, string calldata value) external onlyAssociatedContract {
StringStorage[record] = value;
}
function deleteStringValue(bytes32 record) external onlyAssociatedContract {
delete StringStorage[record];
}
// AddressStorage
function getAddressValue(bytes32 record) external view returns (address) {
return AddressStorage[record];
}
function setAddressValue(bytes32 record, address value) external onlyAssociatedContract {
AddressStorage[record] = value;
}
function deleteAddressValue(bytes32 record) external onlyAssociatedContract {
delete AddressStorage[record];
}
// BytesStorage
function getBytesValue(bytes32 record) external view returns (bytes memory) {
return BytesStorage[record];
}
function setBytesValue(bytes32 record, bytes calldata value) external onlyAssociatedContract {
BytesStorage[record] = value;
}
function deleteBytesValue(bytes32 record) external onlyAssociatedContract {
delete BytesStorage[record];
}
// Bytes32Storage
function getBytes32Value(bytes32 record) external view returns (bytes32) {
return Bytes32Storage[record];
}
function setBytes32Value(bytes32 record, bytes32 value) external onlyAssociatedContract {
Bytes32Storage[record] = value;
}
function deleteBytes32Value(bytes32 record) external onlyAssociatedContract {
delete Bytes32Storage[record];
}
// BooleanStorage
function getBooleanValue(bytes32 record) external view returns (bool) {
return BooleanStorage[record];
}
function setBooleanValue(bytes32 record, bool value) external onlyAssociatedContract {
BooleanStorage[record] = value;
}
function deleteBooleanValue(bytes32 record) external onlyAssociatedContract {
delete BooleanStorage[record];
}
// IntStorage
function getIntValue(bytes32 record) external view returns (int) {
return IntStorage[record];
}
function setIntValue(bytes32 record, int value) external onlyAssociatedContract {
IntStorage[record] = value;
}
function deleteIntValue(bytes32 record) external onlyAssociatedContract {
delete IntStorage[record];
}
}
// https://docs.synthetix.io/contracts/source/contracts/limitedsetup
contract LimitedSetup {
uint public setupExpiryTime;
/**
* @dev LimitedSetup Constructor.
* @param setupDuration The time the setup period will last for.
*/
constructor(uint setupDuration) internal {
setupExpiryTime = now + setupDuration;
}
modifier onlyDuringSetup {
require(now < setupExpiryTime, "Can only perform this action during setup");
_;
}
}
// Inheritance
// https://docs.synthetix.io/contracts/source/contracts/feepooleternalstorage
contract FeePoolEternalStorage is EternalStorage, LimitedSetup {
bytes32 internal constant LAST_FEE_WITHDRAWAL = "last_fee_withdrawal";
constructor(address _owner, address _feePool) public EternalStorage(_owner, _feePool) LimitedSetup(6 weeks) {}
function importFeeWithdrawalData(address[] calldata accounts, uint[] calldata feePeriodIDs)
external
onlyOwner
onlyDuringSetup
{
require(accounts.length == feePeriodIDs.length, "Length mismatch");
for (uint8 i = 0; i < accounts.length; i++) {
this.setUIntValue(keccak256(abi.encodePacked(LAST_FEE_WITHDRAWAL, accounts[i])), feePeriodIDs[i]);
}
}
}
/**
* @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) {
require(b <= a, "SafeMath: subtraction overflow");
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-solidity/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) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
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) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
// Libraries
// https://docs.synthetix.io/contracts/source/libraries/safedecimalmath
library SafeDecimalMath {
using SafeMath for uint;
/* Number of decimal places in the representations. */
uint8 public constant decimals = 18;
uint8 public constant highPrecisionDecimals = 27;
/* The number representing 1.0. */
uint public constant UNIT = 10**uint(decimals);
/* The number representing 1.0 for higher fidelity numbers. */
uint public constant PRECISE_UNIT = 10**uint(highPrecisionDecimals);
uint private constant UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR = 10**uint(highPrecisionDecimals - decimals);
/**
* @return Provides an interface to UNIT.
*/
function unit() external pure returns (uint) {
return UNIT;
}
/**
* @return Provides an interface to PRECISE_UNIT.
*/
function preciseUnit() external pure returns (uint) {
return PRECISE_UNIT;
}
/**
* @return The result of multiplying x and y, interpreting the operands as fixed-point
* decimals.
*
* @dev A unit factor is divided out after the product of x and y is evaluated,
* so that product must be less than 2**256. As this is an integer division,
* the internal division always rounds down. This helps save on gas. Rounding
* is more expensive on gas.
*/
function multiplyDecimal(uint x, uint y) internal pure returns (uint) {
/* Divide by UNIT to remove the extra factor introduced by the product. */
return x.mul(y) / UNIT;
}
/**
* @return The result of safely multiplying x and y, interpreting the operands
* as fixed-point decimals of the specified precision unit.
*
* @dev The operands should be in the form of a the specified unit factor which will be
* divided out after the product of x and y is evaluated, so that product must be
* less than 2**256.
*
* Unlike multiplyDecimal, this function rounds the result to the nearest increment.
* Rounding is useful when you need to retain fidelity for small decimal numbers
* (eg. small fractions or percentages).
*/
function _multiplyDecimalRound(
uint x,
uint y,
uint precisionUnit
) private pure returns (uint) {
/* Divide by UNIT to remove the extra factor introduced by the product. */
uint quotientTimesTen = x.mul(y) / (precisionUnit / 10);
if (quotientTimesTen % 10 >= 5) {
quotientTimesTen += 10;
}
return quotientTimesTen / 10;
}
/**
* @return The result of safely multiplying x and y, interpreting the operands
* as fixed-point decimals of a precise unit.
*
* @dev The operands should be in the precise unit factor which will be
* divided out after the product of x and y is evaluated, so that product must be
* less than 2**256.
*
* Unlike multiplyDecimal, this function rounds the result to the nearest increment.
* Rounding is useful when you need to retain fidelity for small decimal numbers
* (eg. small fractions or percentages).
*/
function multiplyDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) {
return _multiplyDecimalRound(x, y, PRECISE_UNIT);
}
/**
* @return The result of safely multiplying x and y, interpreting the operands
* as fixed-point decimals of a standard unit.
*
* @dev The operands should be in the standard unit factor which will be
* divided out after the product of x and y is evaluated, so that product must be
* less than 2**256.
*
* Unlike multiplyDecimal, this function rounds the result to the nearest increment.
* Rounding is useful when you need to retain fidelity for small decimal numbers
* (eg. small fractions or percentages).
*/
function multiplyDecimalRound(uint x, uint y) internal pure returns (uint) {
return _multiplyDecimalRound(x, y, UNIT);
}
/**
* @return The result of safely dividing x and y. The return value is a high
* precision decimal.
*
* @dev y is divided after the product of x and the standard precision unit
* is evaluated, so the product of x and UNIT must be less than 2**256. As
* this is an integer division, the result is always rounded down.
* This helps save on gas. Rounding is more expensive on gas.
*/
function divideDecimal(uint x, uint y) internal pure returns (uint) {
/* Reintroduce the UNIT factor that will be divided out by y. */
return x.mul(UNIT).div(y);
}
/**
* @return The result of safely dividing x and y. The return value is as a rounded
* decimal in the precision unit specified in the parameter.
*
* @dev y is divided after the product of x and the specified precision unit
* is evaluated, so the product of x and the specified precision unit must
* be less than 2**256. The result is rounded to the nearest increment.
*/
function _divideDecimalRound(
uint x,
uint y,
uint precisionUnit
) private pure returns (uint) {
uint resultTimesTen = x.mul(precisionUnit * 10).div(y);
if (resultTimesTen % 10 >= 5) {
resultTimesTen += 10;
}
return resultTimesTen / 10;
}
/**
* @return The result of safely dividing x and y. The return value is as a rounded
* standard precision decimal.
*
* @dev y is divided after the product of x and the standard precision unit
* is evaluated, so the product of x and the standard precision unit must
* be less than 2**256. The result is rounded to the nearest increment.
*/
function divideDecimalRound(uint x, uint y) internal pure returns (uint) {
return _divideDecimalRound(x, y, UNIT);
}
/**
* @return The result of safely dividing x and y. The return value is as a rounded
* high precision decimal.
*
* @dev y is divided after the product of x and the high precision unit
* is evaluated, so the product of x and the high precision unit must
* be less than 2**256. The result is rounded to the nearest increment.
*/
function divideDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) {
return _divideDecimalRound(x, y, PRECISE_UNIT);
}
/**
* @dev Convert a standard decimal representation to a high precision one.
*/
function decimalToPreciseDecimal(uint i) internal pure returns (uint) {
return i.mul(UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR);
}
/**
* @dev Convert a high precision decimal to a standard decimal representation.
*/
function preciseDecimalToDecimal(uint i) internal pure returns (uint) {
uint quotientTimesTen = i / (UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR / 10);
if (quotientTimesTen % 10 >= 5) {
quotientTimesTen += 10;
}
return quotientTimesTen / 10;
}
// Computes `a - b`, setting the value to 0 if b > a.
function floorsub(uint a, uint b) internal pure returns (uint) {
return b >= a ? 0 : a - b;
}
}
// https://docs.synthetix.io/contracts/source/interfaces/ifeepool
interface IFeePool {
// Views
// solhint-disable-next-line func-name-mixedcase
function FEE_ADDRESS() external view returns (address);
function feesAvailable(address account) external view returns (uint, uint);
function feePeriodDuration() external view returns (uint);
function isFeesClaimable(address account) external view returns (bool);
function targetThreshold() external view returns (uint);
function totalFeesAvailable() external view returns (uint);
function totalRewardsAvailable() external view returns (uint);
// Mutative Functions
function claimFees() external returns (bool);
function claimOnBehalf(address claimingForAddress) external returns (bool);
function closeCurrentFeePeriod() external;
// Restricted: used internally to Synthetix
function appendAccountIssuanceRecord(
address account,
uint lockedAmount,
uint debtEntryIndex
) external;
function recordFeePaid(uint sUSDAmount) external;
function setRewardsToDistribute(uint amount) external;
}
// Inheritance
// Libraries
// Internal references
// https://docs.synthetix.io/contracts/source/contracts/feepoolstate
contract FeePoolState is Owned, LimitedSetup {
using SafeMath for uint;
using SafeDecimalMath for uint;
/* ========== STATE VARIABLES ========== */
uint8 public constant FEE_PERIOD_LENGTH = 6;
address public feePool;
// The IssuanceData activity that's happened in a fee period.
struct IssuanceData {
uint debtPercentage;
uint debtEntryIndex;
}
// The IssuanceData activity that's happened in a fee period.
mapping(address => IssuanceData[FEE_PERIOD_LENGTH]) public accountIssuanceLedger;
constructor(address _owner, IFeePool _feePool) public Owned(_owner) LimitedSetup(6 weeks) {
feePool = address(_feePool);
}
/* ========== SETTERS ========== */
/**
* @notice set the FeePool contract as it is the only authority to be able to call
* appendAccountIssuanceRecord with the onlyFeePool modifer
* @dev Must be set by owner when FeePool logic is upgraded
*/
function setFeePool(IFeePool _feePool) external onlyOwner {
feePool = address(_feePool);
}
/* ========== VIEWS ========== */
/**
* @notice Get an accounts issuanceData for
* @param account users account
* @param index Index in the array to retrieve. Upto FEE_PERIOD_LENGTH
*/
function getAccountsDebtEntry(address account, uint index)
public
view
returns (uint debtPercentage, uint debtEntryIndex)
{
require(index < FEE_PERIOD_LENGTH, "index exceeds the FEE_PERIOD_LENGTH");
debtPercentage = accountIssuanceLedger[account][index].debtPercentage;
debtEntryIndex = accountIssuanceLedger[account][index].debtEntryIndex;
}
/**
* @notice Find the oldest debtEntryIndex for the corresponding closingDebtIndex
* @param account users account
* @param closingDebtIndex the last periods debt index on close
*/
function applicableIssuanceData(address account, uint closingDebtIndex) external view returns (uint, uint) {
IssuanceData[FEE_PERIOD_LENGTH] memory issuanceData = accountIssuanceLedger[account];
// We want to use the user's debtEntryIndex at when the period closed
// Find the oldest debtEntryIndex for the corresponding closingDebtIndex
for (uint i = 0; i < FEE_PERIOD_LENGTH; i++) {
if (closingDebtIndex >= issuanceData[i].debtEntryIndex) {
return (issuanceData[i].debtPercentage, issuanceData[i].debtEntryIndex);
}
}
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice Logs an accounts issuance data in the current fee period which is then stored historically
* @param account Message.Senders account address
* @param debtRatio Debt of this account as a percentage of the global debt.
* @param debtEntryIndex The index in the global debt ledger. synthetix.synthetixState().issuanceData(account)
* @param currentPeriodStartDebtIndex The startingDebtIndex of the current fee period
* @dev onlyFeePool to call me on synthetix.issue() & synthetix.burn() calls to store the locked SNX
* per fee period so we know to allocate the correct proportions of fees and rewards per period
accountIssuanceLedger[account][0] has the latest locked amount for the current period. This can be update as many time
accountIssuanceLedger[account][1-2] has the last locked amount for a previous period they minted or burned
*/
function appendAccountIssuanceRecord(
address account,
uint debtRatio,
uint debtEntryIndex,
uint currentPeriodStartDebtIndex
) external onlyFeePool {
// Is the current debtEntryIndex within this fee period
if (accountIssuanceLedger[account][0].debtEntryIndex < currentPeriodStartDebtIndex) {
// If its older then shift the previous IssuanceData entries periods down to make room for the new one.
issuanceDataIndexOrder(account);
}
// Always store the latest IssuanceData entry at [0]
accountIssuanceLedger[account][0].debtPercentage = debtRatio;
accountIssuanceLedger[account][0].debtEntryIndex = debtEntryIndex;
}
/**
* @notice Pushes down the entire array of debt ratios per fee period
*/
function issuanceDataIndexOrder(address account) private {
for (uint i = FEE_PERIOD_LENGTH - 2; i < FEE_PERIOD_LENGTH; i--) {
uint next = i + 1;
accountIssuanceLedger[account][next].debtPercentage = accountIssuanceLedger[account][i].debtPercentage;
accountIssuanceLedger[account][next].debtEntryIndex = accountIssuanceLedger[account][i].debtEntryIndex;
}
}
/**
* @notice Import issuer data from synthetixState.issuerData on FeePeriodClose() block #
* @dev Only callable by the contract owner, and only for 6 weeks after deployment.
* @param accounts Array of issuing addresses
* @param ratios Array of debt ratios
* @param periodToInsert The Fee Period to insert the historical records into
* @param feePeriodCloseIndex An accounts debtEntryIndex is valid when within the fee peroid,
* since the input ratio will be an average of the pervious periods it just needs to be
* > recentFeePeriods[periodToInsert].startingDebtIndex
* < recentFeePeriods[periodToInsert - 1].startingDebtIndex
*/
function importIssuerData(
address[] calldata accounts,
uint[] calldata ratios,
uint periodToInsert,
uint feePeriodCloseIndex
) external onlyOwner onlyDuringSetup {
require(accounts.length == ratios.length, "Length mismatch");
for (uint i = 0; i < accounts.length; i++) {
accountIssuanceLedger[accounts[i]][periodToInsert].debtPercentage = ratios[i];
accountIssuanceLedger[accounts[i]][periodToInsert].debtEntryIndex = feePeriodCloseIndex;
emit IssuanceDebtRatioEntry(accounts[i], ratios[i], feePeriodCloseIndex);
}
}
/* ========== MODIFIERS ========== */
modifier onlyFeePool {
require(msg.sender == address(feePool), "Only the FeePool contract can perform this action");
_;
}
/* ========== Events ========== */
event IssuanceDebtRatioEntry(address indexed account, uint debtRatio, uint feePeriodCloseIndex);
}
// https://docs.synthetix.io/contracts/source/interfaces/ierc20
interface IERC20 {
// ERC20 Optional Views
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
// Views
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
// Mutative functions
function transfer(address to, uint value) external returns (bool);
function approve(address spender, uint value) external returns (bool);
function transferFrom(
address from,
address to,
uint value
) external returns (bool);
// Events
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
// Inheritance
// https://docs.synthetix.io/contracts/source/contracts/proxyerc20
contract ProxyERC20 is Proxy, IERC20 {
constructor(address _owner) public Proxy(_owner) {}
// ------------- ERC20 Details ------------- //
function name() public view returns (string memory) {
// Immutable static call from target contract
return IERC20(address(target)).name();
}
function symbol() public view returns (string memory) {
// Immutable static call from target contract
return IERC20(address(target)).symbol();
}
function decimals() public view returns (uint8) {
// Immutable static call from target contract
return IERC20(address(target)).decimals();
}
// ------------- ERC20 Interface ------------- //
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
// Immutable static call from target contract
return IERC20(address(target)).totalSupply();
}
/**
* @dev Gets the balance of the specified address.
* @param account The address to query the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address account) public view returns (uint256) {
// Immutable static call from target contract
return IERC20(address(target)).balanceOf(account);
}
/**
* @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) {
// Immutable static call from target contract
return IERC20(address(target)).allowance(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) {
// Mutable state call requires the proxy to tell the target who the msg.sender is.
target.setMessageSender(msg.sender);
// Forward the ERC20 call to the target contract
IERC20(address(target)).transfer(to, value);
// Event emitting will occur via Synthetix.Proxy._emit()
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) {
// Mutable state call requires the proxy to tell the target who the msg.sender is.
target.setMessageSender(msg.sender);
// Forward the ERC20 call to the target contract
IERC20(address(target)).approve(spender, value);
// Event emitting will occur via Synthetix.Proxy._emit()
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) {
// Mutable state call requires the proxy to tell the target who the msg.sender is.
target.setMessageSender(msg.sender);
// Forward the ERC20 call to the target contract
IERC20(address(target)).transferFrom(from, to, value);
// Event emitting will occur via Synthetix.Proxy._emit()
return true;
}
}
// https://docs.synthetix.io/contracts/source/interfaces/iexchangestate
interface IExchangeState {
// Views
struct ExchangeEntry {
bytes32 src;
uint amount;
bytes32 dest;
uint amountReceived;
uint exchangeFeeRate;
uint timestamp;
uint roundIdForSrc;
uint roundIdForDest;
}
function getLengthOfEntries(address account, bytes32 currencyKey) external view returns (uint);
function getEntryAt(
address account,
bytes32 currencyKey,
uint index
)
external
view
returns (
bytes32 src,
uint amount,
bytes32 dest,
uint amountReceived,
uint exchangeFeeRate,
uint timestamp,
uint roundIdForSrc,
uint roundIdForDest
);
function getMaxTimestamp(address account, bytes32 currencyKey) external view returns (uint);
// Mutative functions
function appendExchangeEntry(
address account,
bytes32 src,
uint amount,
bytes32 dest,
uint amountReceived,
uint exchangeFeeRate,
uint timestamp,
uint roundIdForSrc,
uint roundIdForDest
) external;
function removeEntries(address account, bytes32 currencyKey) external;
}
// Inheritance
// https://docs.synthetix.io/contracts/source/contracts/exchangestate
contract ExchangeState is Owned, State, IExchangeState {
mapping(address => mapping(bytes32 => IExchangeState.ExchangeEntry[])) public exchanges;
uint public maxEntriesInQueue = 12;
constructor(address _owner, address _associatedContract) public Owned(_owner) State(_associatedContract) {}
/* ========== SETTERS ========== */
function setMaxEntriesInQueue(uint _maxEntriesInQueue) external onlyOwner {
maxEntriesInQueue = _maxEntriesInQueue;
}
/* ========== MUTATIVE FUNCTIONS ========== */
function appendExchangeEntry(
address account,
bytes32 src,
uint amount,
bytes32 dest,
uint amountReceived,
uint exchangeFeeRate,
uint timestamp,
uint roundIdForSrc,
uint roundIdForDest
) external onlyAssociatedContract {
require(exchanges[account][dest].length < maxEntriesInQueue, "Max queue length reached");
exchanges[account][dest].push(
ExchangeEntry({
src: src,
amount: amount,
dest: dest,
amountReceived: amountReceived,
exchangeFeeRate: exchangeFeeRate,
timestamp: timestamp,
roundIdForSrc: roundIdForSrc,
roundIdForDest: roundIdForDest
})
);
}
function removeEntries(address account, bytes32 currencyKey) external onlyAssociatedContract {
delete exchanges[account][currencyKey];
}
/* ========== VIEWS ========== */
function getLengthOfEntries(address account, bytes32 currencyKey) external view returns (uint) {
return exchanges[account][currencyKey].length;
}
function getEntryAt(
address account,
bytes32 currencyKey,
uint index
)
external
view
returns (
bytes32 src,
uint amount,
bytes32 dest,
uint amountReceived,
uint exchangeFeeRate,
uint timestamp,
uint roundIdForSrc,
uint roundIdForDest
)
{
ExchangeEntry storage entry = exchanges[account][currencyKey][index];
return (
entry.src,
entry.amount,
entry.dest,
entry.amountReceived,
entry.exchangeFeeRate,
entry.timestamp,
entry.roundIdForSrc,
entry.roundIdForDest
);
}
function getMaxTimestamp(address account, bytes32 currencyKey) external view returns (uint) {
ExchangeEntry[] storage userEntries = exchanges[account][currencyKey];
uint timestamp = 0;
for (uint i = 0; i < userEntries.length; i++) {
if (userEntries[i].timestamp > timestamp) {
timestamp = userEntries[i].timestamp;
}
}
return timestamp;
}
}
// https://docs.synthetix.io/contracts/source/interfaces/isystemstatus
interface ISystemStatus {
struct Status {
bool canSuspend;
bool canResume;
}
struct Suspension {
bool suspended;
// reason is an integer code,
// 0 => no reason, 1 => upgrading, 2+ => defined by system usage
uint248 reason;
}
// Views
function accessControl(bytes32 section, address account) external view returns (bool canSuspend, bool canResume);
function requireSystemActive() external view;
function requireIssuanceActive() external view;
function requireExchangeActive() external view;
function requireExchangeBetweenSynthsAllowed(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) external view;
function requireSynthActive(bytes32 currencyKey) external view;
function requireSynthsActive(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) external view;
function systemSuspension() external view returns (bool suspended, uint248 reason);
function issuanceSuspension() external view returns (bool suspended, uint248 reason);
function exchangeSuspension() external view returns (bool suspended, uint248 reason);
function synthExchangeSuspension(bytes32 currencyKey) external view returns (bool suspended, uint248 reason);
function synthSuspension(bytes32 currencyKey) external view returns (bool suspended, uint248 reason);
function getSynthExchangeSuspensions(bytes32[] calldata synths)
external
view
returns (bool[] memory exchangeSuspensions, uint256[] memory reasons);
function getSynthSuspensions(bytes32[] calldata synths)
external
view
returns (bool[] memory suspensions, uint256[] memory reasons);
// Restricted functions
function suspendSynth(bytes32 currencyKey, uint256 reason) external;
function updateAccessControl(
bytes32 section,
address account,
bool canSuspend,
bool canResume
) external;
}
// Inheritance
// https://docs.synthetix.io/contracts/source/contracts/systemstatus
contract SystemStatus is Owned, ISystemStatus {
mapping(bytes32 => mapping(address => Status)) public accessControl;
uint248 public constant SUSPENSION_REASON_UPGRADE = 1;
bytes32 public constant SECTION_SYSTEM = "System";
bytes32 public constant SECTION_ISSUANCE = "Issuance";
bytes32 public constant SECTION_EXCHANGE = "Exchange";
bytes32 public constant SECTION_SYNTH_EXCHANGE = "SynthExchange";
bytes32 public constant SECTION_SYNTH = "Synth";
Suspension public systemSuspension;
Suspension public issuanceSuspension;
Suspension public exchangeSuspension;
mapping(bytes32 => Suspension) public synthExchangeSuspension;
mapping(bytes32 => Suspension) public synthSuspension;
constructor(address _owner) public Owned(_owner) {}
/* ========== VIEWS ========== */
function requireSystemActive() external view {
_internalRequireSystemActive();
}
function requireIssuanceActive() external view {
// Issuance requires the system be active
_internalRequireSystemActive();
// and issuance itself of course
_internalRequireIssuanceActive();
}
function requireExchangeActive() external view {
// Exchanging requires the system be active
_internalRequireSystemActive();
// and exchanging itself of course
_internalRequireExchangeActive();
}
function requireSynthExchangeActive(bytes32 currencyKey) external view {
// Synth exchange and transfer requires the system be active
_internalRequireSystemActive();
_internalRequireSynthExchangeActive(currencyKey);
}
function requireSynthActive(bytes32 currencyKey) external view {
// Synth exchange and transfer requires the system be active
_internalRequireSystemActive();
_internalRequireSynthActive(currencyKey);
}
function requireSynthsActive(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) external view {
// Synth exchange and transfer requires the system be active
_internalRequireSystemActive();
_internalRequireSynthActive(sourceCurrencyKey);
_internalRequireSynthActive(destinationCurrencyKey);
}
function requireExchangeBetweenSynthsAllowed(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) external view {
// Synth exchange and transfer requires the system be active
_internalRequireSystemActive();
// and exchanging must be active
_internalRequireExchangeActive();
// and the synth exchanging between the synths must be active
_internalRequireSynthExchangeActive(sourceCurrencyKey);
_internalRequireSynthExchangeActive(destinationCurrencyKey);
// and finally, the synths cannot be suspended
_internalRequireSynthActive(sourceCurrencyKey);
_internalRequireSynthActive(destinationCurrencyKey);
}
function isSystemUpgrading() external view returns (bool) {
return systemSuspension.suspended && systemSuspension.reason == SUSPENSION_REASON_UPGRADE;
}
function getSynthExchangeSuspensions(bytes32[] calldata synths)
external
view
returns (bool[] memory exchangeSuspensions, uint256[] memory reasons)
{
exchangeSuspensions = new bool[](synths.length);
reasons = new uint256[](synths.length);
for (uint i = 0; i < synths.length; i++) {
exchangeSuspensions[i] = synthExchangeSuspension[synths[i]].suspended;
reasons[i] = synthExchangeSuspension[synths[i]].reason;
}
}
function getSynthSuspensions(bytes32[] calldata synths)
external
view
returns (bool[] memory suspensions, uint256[] memory reasons)
{
suspensions = new bool[](synths.length);
reasons = new uint256[](synths.length);
for (uint i = 0; i < synths.length; i++) {
suspensions[i] = synthSuspension[synths[i]].suspended;
reasons[i] = synthSuspension[synths[i]].reason;
}
}
/* ========== MUTATIVE FUNCTIONS ========== */
function updateAccessControl(
bytes32 section,
address account,
bool canSuspend,
bool canResume
) external onlyOwner {
_internalUpdateAccessControl(section, account, canSuspend, canResume);
}
function updateAccessControls(
bytes32[] calldata sections,
address[] calldata accounts,
bool[] calldata canSuspends,
bool[] calldata canResumes
) external onlyOwner {
require(
sections.length == accounts.length &&
accounts.length == canSuspends.length &&
canSuspends.length == canResumes.length,
"Input array lengths must match"
);
for (uint i = 0; i < sections.length; i++) {
_internalUpdateAccessControl(sections[i], accounts[i], canSuspends[i], canResumes[i]);
}
}
function suspendSystem(uint256 reason) external {
_requireAccessToSuspend(SECTION_SYSTEM);
systemSuspension.suspended = true;
systemSuspension.reason = uint248(reason);
emit SystemSuspended(systemSuspension.reason);
}
function resumeSystem() external {
_requireAccessToResume(SECTION_SYSTEM);
systemSuspension.suspended = false;
emit SystemResumed(uint256(systemSuspension.reason));
systemSuspension.reason = 0;
}
function suspendIssuance(uint256 reason) external {
_requireAccessToSuspend(SECTION_ISSUANCE);
issuanceSuspension.suspended = true;
issuanceSuspension.reason = uint248(reason);
emit IssuanceSuspended(reason);
}
function resumeIssuance() external {
_requireAccessToResume(SECTION_ISSUANCE);
issuanceSuspension.suspended = false;
emit IssuanceResumed(uint256(issuanceSuspension.reason));
issuanceSuspension.reason = 0;
}
function suspendExchange(uint256 reason) external {
_requireAccessToSuspend(SECTION_EXCHANGE);
exchangeSuspension.suspended = true;
exchangeSuspension.reason = uint248(reason);
emit ExchangeSuspended(reason);
}
function resumeExchange() external {
_requireAccessToResume(SECTION_EXCHANGE);
exchangeSuspension.suspended = false;
emit ExchangeResumed(uint256(exchangeSuspension.reason));
exchangeSuspension.reason = 0;
}
function suspendSynthExchange(bytes32 currencyKey, uint256 reason) external {
bytes32[] memory currencyKeys = new bytes32[](1);
currencyKeys[0] = currencyKey;
_internalSuspendSynthExchange(currencyKeys, reason);
}
function suspendSynthsExchange(bytes32[] calldata currencyKeys, uint256 reason) external {
_internalSuspendSynthExchange(currencyKeys, reason);
}
function resumeSynthExchange(bytes32 currencyKey) external {
bytes32[] memory currencyKeys = new bytes32[](1);
currencyKeys[0] = currencyKey;
_internalResumeSynthsExchange(currencyKeys);
}
function resumeSynthsExchange(bytes32[] calldata currencyKeys) external {
_internalResumeSynthsExchange(currencyKeys);
}
function suspendSynth(bytes32 currencyKey, uint256 reason) external {
bytes32[] memory currencyKeys = new bytes32[](1);
currencyKeys[0] = currencyKey;
_internalSuspendSynths(currencyKeys, reason);
}
function suspendSynths(bytes32[] calldata currencyKeys, uint256 reason) external {
_internalSuspendSynths(currencyKeys, reason);
}
function resumeSynth(bytes32 currencyKey) external {
bytes32[] memory currencyKeys = new bytes32[](1);
currencyKeys[0] = currencyKey;
_internalResumeSynths(currencyKeys);
}
function resumeSynths(bytes32[] calldata currencyKeys) external {
_internalResumeSynths(currencyKeys);
}
/* ========== INTERNAL FUNCTIONS ========== */
function _requireAccessToSuspend(bytes32 section) internal view {
require(accessControl[section][msg.sender].canSuspend, "Restricted to access control list");
}
function _requireAccessToResume(bytes32 section) internal view {
require(accessControl[section][msg.sender].canResume, "Restricted to access control list");
}
function _internalRequireSystemActive() internal view {
require(
!systemSuspension.suspended,
systemSuspension.reason == SUSPENSION_REASON_UPGRADE
? "Synthetix is suspended, upgrade in progress... please stand by"
: "Synthetix is suspended. Operation prohibited"
);
}
function _internalRequireIssuanceActive() internal view {
require(!issuanceSuspension.suspended, "Issuance is suspended. Operation prohibited");
}
function _internalRequireExchangeActive() internal view {
require(!exchangeSuspension.suspended, "Exchange is suspended. Operation prohibited");
}
function _internalRequireSynthExchangeActive(bytes32 currencyKey) internal view {
require(!synthExchangeSuspension[currencyKey].suspended, "Synth exchange suspended. Operation prohibited");
}
function _internalRequireSynthActive(bytes32 currencyKey) internal view {
require(!synthSuspension[currencyKey].suspended, "Synth is suspended. Operation prohibited");
}
function _internalSuspendSynths(bytes32[] memory currencyKeys, uint256 reason) internal {
_requireAccessToSuspend(SECTION_SYNTH);
for (uint i = 0; i < currencyKeys.length; i++) {
bytes32 currencyKey = currencyKeys[i];
synthSuspension[currencyKey].suspended = true;
synthSuspension[currencyKey].reason = uint248(reason);
emit SynthSuspended(currencyKey, reason);
}
}
function _internalResumeSynths(bytes32[] memory currencyKeys) internal {
_requireAccessToResume(SECTION_SYNTH);
for (uint i = 0; i < currencyKeys.length; i++) {
bytes32 currencyKey = currencyKeys[i];
emit SynthResumed(currencyKey, uint256(synthSuspension[currencyKey].reason));
delete synthSuspension[currencyKey];
}
}
function _internalSuspendSynthExchange(bytes32[] memory currencyKeys, uint256 reason) internal {
_requireAccessToSuspend(SECTION_SYNTH_EXCHANGE);
for (uint i = 0; i < currencyKeys.length; i++) {
bytes32 currencyKey = currencyKeys[i];
synthExchangeSuspension[currencyKey].suspended = true;
synthExchangeSuspension[currencyKey].reason = uint248(reason);
emit SynthExchangeSuspended(currencyKey, reason);
}
}
function _internalResumeSynthsExchange(bytes32[] memory currencyKeys) internal {
_requireAccessToResume(SECTION_SYNTH_EXCHANGE);
for (uint i = 0; i < currencyKeys.length; i++) {
bytes32 currencyKey = currencyKeys[i];
emit SynthExchangeResumed(currencyKey, uint256(synthExchangeSuspension[currencyKey].reason));
delete synthExchangeSuspension[currencyKey];
}
}
function _internalUpdateAccessControl(
bytes32 section,
address account,
bool canSuspend,
bool canResume
) internal {
require(
section == SECTION_SYSTEM ||
section == SECTION_ISSUANCE ||
section == SECTION_EXCHANGE ||
section == SECTION_SYNTH_EXCHANGE ||
section == SECTION_SYNTH,
"Invalid section supplied"
);
accessControl[section][account].canSuspend = canSuspend;
accessControl[section][account].canResume = canResume;
emit AccessControlUpdated(section, account, canSuspend, canResume);
}
/* ========== EVENTS ========== */
event SystemSuspended(uint256 reason);
event SystemResumed(uint256 reason);
event IssuanceSuspended(uint256 reason);
event IssuanceResumed(uint256 reason);
event ExchangeSuspended(uint256 reason);
event ExchangeResumed(uint256 reason);
event SynthExchangeSuspended(bytes32 currencyKey, uint256 reason);
event SynthExchangeResumed(bytes32 currencyKey, uint256 reason);
event SynthSuspended(bytes32 currencyKey, uint256 reason);
event SynthResumed(bytes32 currencyKey, uint256 reason);
event AccessControlUpdated(bytes32 indexed section, address indexed account, bool canSuspend, bool canResume);
}
contract LegacyOwned {
address public owner;
address public nominatedOwner;
constructor(address _owner) public {
owner = _owner;
}
function nominateOwner(address _owner) external onlyOwner {
nominatedOwner = _owner;
emit OwnerNominated(_owner);
}
function acceptOwnership() external {
require(msg.sender == nominatedOwner);
emit OwnerChanged(owner, nominatedOwner);
owner = nominatedOwner;
nominatedOwner = address(0);
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
event OwnerNominated(address newOwner);
event OwnerChanged(address oldOwner, address newOwner);
}
contract LegacyTokenState is LegacyOwned {
// the address of the contract that can modify balances and allowances
// this can only be changed by the owner of this contract
address public associatedContract;
// ERC20 fields.
mapping(address => uint) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
constructor(address _owner, address _associatedContract) public LegacyOwned(_owner) {
associatedContract = _associatedContract;
emit AssociatedContractUpdated(_associatedContract);
}
/* ========== SETTERS ========== */
// Change the associated contract to a new address
function setAssociatedContract(address _associatedContract) external onlyOwner {
associatedContract = _associatedContract;
emit AssociatedContractUpdated(_associatedContract);
}
function setAllowance(
address tokenOwner,
address spender,
uint value
) external onlyAssociatedContract {
allowance[tokenOwner][spender] = value;
}
function setBalanceOf(address account, uint value) external onlyAssociatedContract {
balanceOf[account] = value;
}
/* ========== MODIFIERS ========== */
modifier onlyAssociatedContract {
require(msg.sender == associatedContract);
_;
}
/* ========== EVENTS ========== */
event AssociatedContractUpdated(address _associatedContract);
}
// https://docs.synthetix.io/contracts/source/interfaces/isynthetixstate
interface ISynthetixState {
// Views
function debtLedger(uint index) external view returns (uint);
function issuanceData(address account) external view returns (uint initialDebtOwnership, uint debtEntryIndex);
function debtLedgerLength() external view returns (uint);
function hasIssued(address account) external view returns (bool);
function lastDebtLedgerEntry() external view returns (uint);
// Mutative functions
function incrementTotalIssuerCount() external;
function decrementTotalIssuerCount() external;
function setCurrentIssuanceData(address account, uint initialDebtOwnership) external;
function appendDebtLedgerValue(uint value) external;
function clearIssuanceData(address account) external;
}
// Inheritance
// Libraries
// https://docs.synthetix.io/contracts/source/contracts/synthetixstate
contract SynthetixState is Owned, State, ISynthetixState {
using SafeMath for uint;
using SafeDecimalMath for uint;
// A struct for handing values associated with an individual user's debt position
struct IssuanceData {
// Percentage of the total debt owned at the time
// of issuance. This number is modified by the global debt
// delta array. You can figure out a user's exit price and
// collateralisation ratio using a combination of their initial
// debt and the slice of global debt delta which applies to them.
uint initialDebtOwnership;
// This lets us know when (in relative terms) the user entered
// the debt pool so we can calculate their exit price and
// collateralistion ratio
uint debtEntryIndex;
}
// Issued synth balances for individual fee entitlements and exit price calculations
mapping(address => IssuanceData) public issuanceData;
// The total count of people that have outstanding issued synths in any flavour
uint public totalIssuerCount;
// Global debt pool tracking
uint[] public debtLedger;
constructor(address _owner, address _associatedContract) public Owned(_owner) State(_associatedContract) {}
/* ========== SETTERS ========== */
/**
* @notice Set issuance data for an address
* @dev Only the associated contract may call this.
* @param account The address to set the data for.
* @param initialDebtOwnership The initial debt ownership for this address.
*/
function setCurrentIssuanceData(address account, uint initialDebtOwnership) external onlyAssociatedContract {
issuanceData[account].initialDebtOwnership = initialDebtOwnership;
issuanceData[account].debtEntryIndex = debtLedger.length;
}
/**
* @notice Clear issuance data for an address
* @dev Only the associated contract may call this.
* @param account The address to clear the data for.
*/
function clearIssuanceData(address account) external onlyAssociatedContract {
delete issuanceData[account];
}
/**
* @notice Increment the total issuer count
* @dev Only the associated contract may call this.
*/
function incrementTotalIssuerCount() external onlyAssociatedContract {
totalIssuerCount = totalIssuerCount.add(1);
}
/**
* @notice Decrement the total issuer count
* @dev Only the associated contract may call this.
*/
function decrementTotalIssuerCount() external onlyAssociatedContract {
totalIssuerCount = totalIssuerCount.sub(1);
}
/**
* @notice Append a value to the debt ledger
* @dev Only the associated contract may call this.
* @param value The new value to be added to the debt ledger.
*/
function appendDebtLedgerValue(uint value) external onlyAssociatedContract {
debtLedger.push(value);
}
/* ========== VIEWS ========== */
/**
* @notice Retrieve the length of the debt ledger array
*/
function debtLedgerLength() external view returns (uint) {
return debtLedger.length;
}
/**
* @notice Retrieve the most recent entry from the debt ledger
*/
function lastDebtLedgerEntry() external view returns (uint) {
return debtLedger[debtLedger.length - 1];
}
/**
* @notice Query whether an account has issued and has an outstanding debt balance
* @param account The address to query for
*/
function hasIssued(address account) external view returns (bool) {
return issuanceData[account].initialDebtOwnership > 0;
}
}
// https://docs.synthetix.io/contracts/source/interfaces/irewardescrow
interface IRewardEscrow {
// Views
function balanceOf(address account) external view returns (uint);
function numVestingEntries(address account) external view returns (uint);
function totalEscrowedAccountBalance(address account) external view returns (uint);
function totalVestedAccountBalance(address account) external view returns (uint);
function getVestingScheduleEntry(address account, uint index) external view returns (uint[2] memory);
function getNextVestingIndex(address account) external view returns (uint);
// Mutative functions
function appendVestingEntry(address account, uint quantity) external;
function vest() external;
}
interface IVirtualSynth {
// Views
function balanceOfUnderlying(address account) external view returns (uint);
function rate() external view returns (uint);
function readyToSettle() external view returns (bool);
function secsLeftInWaitingPeriod() external view returns (uint);
function settled() external view returns (bool);
function synth() external view returns (ISynth);
// Mutative functions
function settle(address account) external;
}
// https://docs.synthetix.io/contracts/source/interfaces/isynthetix
interface ISynthetix {
// Views
function anySynthOrSNXRateIsInvalid() external view returns (bool anyRateInvalid);
function availableCurrencyKeys() external view returns (bytes32[] memory);
function availableSynthCount() external view returns (uint);
function availableSynths(uint index) external view returns (ISynth);
function collateral(address account) external view returns (uint);
function collateralisationRatio(address issuer) external view returns (uint);
function debtBalanceOf(address issuer, bytes32 currencyKey) external view returns (uint);
function isWaitingPeriod(bytes32 currencyKey) external view returns (bool);
function maxIssuableSynths(address issuer) external view returns (uint maxIssuable);
function remainingIssuableSynths(address issuer)
external
view
returns (
uint maxIssuable,
uint alreadyIssued,
uint totalSystemDebt
);
function synths(bytes32 currencyKey) external view returns (ISynth);
function synthsByAddress(address synthAddress) external view returns (bytes32);
function totalIssuedSynths(bytes32 currencyKey) external view returns (uint);
function totalIssuedSynthsExcludeOtherCollateral(bytes32 currencyKey) external view returns (uint);
function transferableSynthetix(address account) external view returns (uint transferable);
// Mutative Functions
function burnSynths(uint amount) external;
function burnSynthsOnBehalf(address burnForAddress, uint amount) external;
function burnSynthsToTarget() external;
function burnSynthsToTargetOnBehalf(address burnForAddress) external;
function exchange(
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey
) external returns (uint amountReceived);
function exchangeOnBehalf(
address exchangeForAddress,
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey
) external returns (uint amountReceived);
function exchangeWithTracking(
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey,
address rewardAddress,
bytes32 trackingCode
) external returns (uint amountReceived);
function exchangeWithTrackingForInitiator(
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey,
address rewardAddress,
bytes32 trackingCode
) external returns (uint amountReceived);
function exchangeOnBehalfWithTracking(
address exchangeForAddress,
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey,
address rewardAddress,
bytes32 trackingCode
) external returns (uint amountReceived);
function exchangeWithVirtual(
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey,
bytes32 trackingCode
) external returns (uint amountReceived, IVirtualSynth vSynth);
function issueMaxSynths() external;
function issueMaxSynthsOnBehalf(address issueForAddress) external;
function issueSynths(uint amount) external;
function issueSynthsOnBehalf(address issueForAddress, uint amount) external;
function mint() external returns (bool);
function settle(bytes32 currencyKey)
external
returns (
uint reclaimed,
uint refunded,
uint numEntries
);
// Liquidations
function liquidateDelinquentAccount(address account, uint susdAmount) external returns (bool);
// Restricted Functions
function mintSecondary(address account, uint amount) external;
function mintSecondaryRewards(uint amount) external;
function burnSecondary(address account, uint amount) external;
}
// Inheritance
// Libraries
// Internal references
// https://docs.synthetix.io/contracts/source/contracts/rewardescrow
contract RewardEscrow is Owned, IRewardEscrow {
using SafeMath for uint;
/* The corresponding Synthetix contract. */
ISynthetix public synthetix;
IFeePool public feePool;
/* Lists of (timestamp, quantity) pairs per account, sorted in ascending time order.
* These are the times at which each given quantity of SNX vests. */
mapping(address => uint[2][]) public vestingSchedules;
/* An account's total escrowed synthetix balance to save recomputing this for fee extraction purposes. */
mapping(address => uint) public totalEscrowedAccountBalance;
/* An account's total vested reward synthetix. */
mapping(address => uint) public totalVestedAccountBalance;
/* The total remaining escrowed balance, for verifying the actual synthetix balance of this contract against. */
uint public totalEscrowedBalance;
uint internal constant TIME_INDEX = 0;
uint internal constant QUANTITY_INDEX = 1;
/* Limit vesting entries to disallow unbounded iteration over vesting schedules.
* There are 5 years of the supply schedule */
uint public constant MAX_VESTING_ENTRIES = 52 * 5;
/* ========== CONSTRUCTOR ========== */
constructor(
address _owner,
ISynthetix _synthetix,
IFeePool _feePool
) public Owned(_owner) {
synthetix = _synthetix;
feePool = _feePool;
}
/* ========== SETTERS ========== */
/**
* @notice set the synthetix contract address as we need to transfer SNX when the user vests
*/
function setSynthetix(ISynthetix _synthetix) external onlyOwner {
synthetix = _synthetix;
emit SynthetixUpdated(address(_synthetix));
}
/**
* @notice set the FeePool contract as it is the only authority to be able to call
* appendVestingEntry with the onlyFeePool modifer
*/
function setFeePool(IFeePool _feePool) external onlyOwner {
feePool = _feePool;
emit FeePoolUpdated(address(_feePool));
}
/* ========== VIEW FUNCTIONS ========== */
/**
* @notice A simple alias to totalEscrowedAccountBalance: provides ERC20 balance integration.
*/
function balanceOf(address account) public view returns (uint) {
return totalEscrowedAccountBalance[account];
}
function _numVestingEntries(address account) internal view returns (uint) {
return vestingSchedules[account].length;
}
/**
* @notice The number of vesting dates in an account's schedule.
*/
function numVestingEntries(address account) external view returns (uint) {
return vestingSchedules[account].length;
}
/**
* @notice Get a particular schedule entry for an account.
* @return A pair of uints: (timestamp, synthetix quantity).
*/
function getVestingScheduleEntry(address account, uint index) public view returns (uint[2] memory) {
return vestingSchedules[account][index];
}
/**
* @notice Get the time at which a given schedule entry will vest.
*/
function getVestingTime(address account, uint index) public view returns (uint) {
return getVestingScheduleEntry(account, index)[TIME_INDEX];
}
/**
* @notice Get the quantity of SNX associated with a given schedule entry.
*/
function getVestingQuantity(address account, uint index) public view returns (uint) {
return getVestingScheduleEntry(account, index)[QUANTITY_INDEX];
}
/**
* @notice Obtain the index of the next schedule entry that will vest for a given user.
*/
function getNextVestingIndex(address account) public view returns (uint) {
uint len = _numVestingEntries(account);
for (uint i = 0; i < len; i++) {
if (getVestingTime(account, i) != 0) {
return i;
}
}
return len;
}
/**
* @notice Obtain the next schedule entry that will vest for a given user.
* @return A pair of uints: (timestamp, synthetix quantity). */
function getNextVestingEntry(address account) public view returns (uint[2] memory) {
uint index = getNextVestingIndex(account);
if (index == _numVestingEntries(account)) {
return [uint(0), 0];
}
return getVestingScheduleEntry(account, index);
}
/**
* @notice Obtain the time at which the next schedule entry will vest for a given user.
*/
function getNextVestingTime(address account) external view returns (uint) {
return getNextVestingEntry(account)[TIME_INDEX];
}
/**
* @notice Obtain the quantity which the next schedule entry will vest for a given user.
*/
function getNextVestingQuantity(address account) external view returns (uint) {
return getNextVestingEntry(account)[QUANTITY_INDEX];
}
/**
* @notice return the full vesting schedule entries vest for a given user.
* @dev For DApps to display the vesting schedule for the
* inflationary supply over 5 years. Solidity cant return variable length arrays
* so this is returning pairs of data. Vesting Time at [0] and quantity at [1] and so on
*/
function checkAccountSchedule(address account) public view returns (uint[520] memory) {
uint[520] memory _result;
uint schedules = _numVestingEntries(account);
for (uint i = 0; i < schedules; i++) {
uint[2] memory pair = getVestingScheduleEntry(account, i);
_result[i * 2] = pair[0];
_result[i * 2 + 1] = pair[1];
}
return _result;
}
/* ========== MUTATIVE FUNCTIONS ========== */
function _appendVestingEntry(address account, uint quantity) internal {
/* No empty or already-passed vesting entries allowed. */
require(quantity != 0, "Quantity cannot be zero");
/* There must be enough balance in the contract to provide for the vesting entry. */
totalEscrowedBalance = totalEscrowedBalance.add(quantity);
require(
totalEscrowedBalance <= IERC20(address(synthetix)).balanceOf(address(this)),
"Must be enough balance in the contract to provide for the vesting entry"
);
/* Disallow arbitrarily long vesting schedules in light of the gas limit. */
uint scheduleLength = vestingSchedules[account].length;
require(scheduleLength <= MAX_VESTING_ENTRIES, "Vesting schedule is too long");
/* Escrow the tokens for 1 year. */
uint time = now + 52 weeks;
if (scheduleLength == 0) {
totalEscrowedAccountBalance[account] = quantity;
} else {
/* Disallow adding new vested SNX earlier than the last one.
* Since entries are only appended, this means that no vesting date can be repeated. */
require(
getVestingTime(account, scheduleLength - 1) < time,
"Cannot add new vested entries earlier than the last one"
);
totalEscrowedAccountBalance[account] = totalEscrowedAccountBalance[account].add(quantity);
}
vestingSchedules[account].push([time, quantity]);
emit VestingEntryCreated(account, now, quantity);
}
/**
* @notice Add a new vesting entry at a given time and quantity to an account's schedule.
* @dev A call to this should accompany a previous successful call to synthetix.transfer(rewardEscrow, amount),
* to ensure that when the funds are withdrawn, there is enough balance.
* Note; although this function could technically be used to produce unbounded
* arrays, it's only withinn the 4 year period of the weekly inflation schedule.
* @param account The account to append a new vesting entry to.
* @param quantity The quantity of SNX that will be escrowed.
*/
function appendVestingEntry(address account, uint quantity) external onlyFeePool {
_appendVestingEntry(account, quantity);
}
/**
* @notice Allow a user to withdraw any SNX in their schedule that have vested.
*/
function vest() external {
uint numEntries = _numVestingEntries(msg.sender);
uint total;
for (uint i = 0; i < numEntries; i++) {
uint time = getVestingTime(msg.sender, i);
/* The list is sorted; when we reach the first future time, bail out. */
if (time > now) {
break;
}
uint qty = getVestingQuantity(msg.sender, i);
if (qty > 0) {
vestingSchedules[msg.sender][i] = [0, 0];
total = total.add(qty);
}
}
if (total != 0) {
totalEscrowedBalance = totalEscrowedBalance.sub(total);
totalEscrowedAccountBalance[msg.sender] = totalEscrowedAccountBalance[msg.sender].sub(total);
totalVestedAccountBalance[msg.sender] = totalVestedAccountBalance[msg.sender].add(total);
IERC20(address(synthetix)).transfer(msg.sender, total);
emit Vested(msg.sender, now, total);
}
}
/* ========== MODIFIERS ========== */
modifier onlyFeePool() {
bool isFeePool = msg.sender == address(feePool);
require(isFeePool, "Only the FeePool contracts can perform this action");
_;
}
/* ========== EVENTS ========== */
event SynthetixUpdated(address newSynthetix);
event FeePoolUpdated(address newFeePool);
event Vested(address indexed beneficiary, uint time, uint value);
event VestingEntryCreated(address indexed beneficiary, uint time, uint value);
}
// https://docs.synthetix.io/contracts/source/interfaces/irewardsdistribution
interface IRewardsDistribution {
// Structs
struct DistributionData {
address destination;
uint amount;
}
// Views
function authority() external view returns (address);
function distributions(uint index) external view returns (address destination, uint amount); // DistributionData
function distributionsLength() external view returns (uint);
// Mutative Functions
function distributeRewards(uint amount) external returns (bool);
}
// Inheritance
// Libraires
// Internal references
// https://docs.synthetix.io/contracts/source/contracts/rewardsdistribution
contract RewardsDistribution is Owned, IRewardsDistribution {
using SafeMath for uint;
using SafeDecimalMath for uint;
/**
* @notice Authorised address able to call distributeRewards
*/
address public authority;
/**
* @notice Address of the Synthetix ProxyERC20
*/
address public synthetixProxy;
/**
* @notice Address of the RewardEscrow contract
*/
address public rewardEscrow;
/**
* @notice Address of the FeePoolProxy
*/
address public feePoolProxy;
/**
* @notice An array of addresses and amounts to send
*/
DistributionData[] public distributions;
/**
* @dev _authority maybe the underlying synthetix contract.
* Remember to set the authority on a synthetix upgrade
*/
constructor(
address _owner,
address _authority,
address _synthetixProxy,
address _rewardEscrow,
address _feePoolProxy
) public Owned(_owner) {
authority = _authority;
synthetixProxy = _synthetixProxy;
rewardEscrow = _rewardEscrow;
feePoolProxy = _feePoolProxy;
}
// ========== EXTERNAL SETTERS ==========
function setSynthetixProxy(address _synthetixProxy) external onlyOwner {
synthetixProxy = _synthetixProxy;
}
function setRewardEscrow(address _rewardEscrow) external onlyOwner {
rewardEscrow = _rewardEscrow;
}
function setFeePoolProxy(address _feePoolProxy) external onlyOwner {
feePoolProxy = _feePoolProxy;
}
/**
* @notice Set the address of the contract authorised to call distributeRewards()
* @param _authority Address of the authorised calling contract.
*/
function setAuthority(address _authority) external onlyOwner {
authority = _authority;
}
// ========== EXTERNAL FUNCTIONS ==========
/**
* @notice Adds a Rewards DistributionData struct to the distributions
* array. Any entries here will be iterated and rewards distributed to
* each address when tokens are sent to this contract and distributeRewards()
* is called by the autority.
* @param destination An address to send rewards tokens too
* @param amount The amount of rewards tokens to send
*/
function addRewardDistribution(address destination, uint amount) external onlyOwner returns (bool) {
require(destination != address(0), "Cant add a zero address");
require(amount != 0, "Cant add a zero amount");
DistributionData memory rewardsDistribution = DistributionData(destination, amount);
distributions.push(rewardsDistribution);
emit RewardDistributionAdded(distributions.length - 1, destination, amount);
return true;
}
/**
* @notice Deletes a RewardDistribution from the distributions
* so it will no longer be included in the call to distributeRewards()
* @param index The index of the DistributionData to delete
*/
function removeRewardDistribution(uint index) external onlyOwner {
require(index <= distributions.length - 1, "index out of bounds");
// shift distributions indexes across
for (uint i = index; i < distributions.length - 1; i++) {
distributions[i] = distributions[i + 1];
}
distributions.length--;
// Since this function must shift all later entries down to fill the
// gap from the one it removed, it could in principle consume an
// unbounded amount of gas. However, the number of entries will
// presumably always be very low.
}
/**
* @notice Edits a RewardDistribution in the distributions array.
* @param index The index of the DistributionData to edit
* @param destination The destination address. Send the same address to keep or different address to change it.
* @param amount The amount of tokens to edit. Send the same number to keep or change the amount of tokens to send.
*/
function editRewardDistribution(
uint index,
address destination,
uint amount
) external onlyOwner returns (bool) {
require(index <= distributions.length - 1, "index out of bounds");
distributions[index].destination = destination;
distributions[index].amount = amount;
return true;
}
function distributeRewards(uint amount) external returns (bool) {
require(amount > 0, "Nothing to distribute");
require(msg.sender == authority, "Caller is not authorised");
require(rewardEscrow != address(0), "RewardEscrow is not set");
require(synthetixProxy != address(0), "SynthetixProxy is not set");
require(feePoolProxy != address(0), "FeePoolProxy is not set");
require(
IERC20(synthetixProxy).balanceOf(address(this)) >= amount,
"RewardsDistribution contract does not have enough tokens to distribute"
);
uint remainder = amount;
// Iterate the array of distributions sending the configured amounts
for (uint i = 0; i < distributions.length; i++) {
if (distributions[i].destination != address(0) || distributions[i].amount != 0) {
remainder = remainder.sub(distributions[i].amount);
// Transfer the SNX
IERC20(synthetixProxy).transfer(distributions[i].destination, distributions[i].amount);
// If the contract implements RewardsDistributionRecipient.sol, inform it how many SNX its received.
bytes memory payload = abi.encodeWithSignature("notifyRewardAmount(uint256)", distributions[i].amount);
// solhint-disable avoid-low-level-calls
(bool success, ) = distributions[i].destination.call(payload);
if (!success) {
// Note: we're ignoring the return value as it will fail for contracts that do not implement RewardsDistributionRecipient.sol
}
}
}
// After all ditributions have been sent, send the remainder to the RewardsEscrow contract
IERC20(synthetixProxy).transfer(rewardEscrow, remainder);
// Tell the FeePool how much it has to distribute to the stakers
IFeePool(feePoolProxy).setRewardsToDistribute(remainder);
emit RewardsDistributed(amount);
return true;
}
/* ========== VIEWS ========== */
/**
* @notice Retrieve the length of the distributions array
*/
function distributionsLength() external view returns (uint) {
return distributions.length;
}
/* ========== Events ========== */
event RewardDistributionAdded(uint index, address destination, uint amount);
event RewardsDistributed(uint amount);
}
// https://docs.synthetix.io/contracts/source/interfaces/iflexiblestorage
interface IFlexibleStorage {
// Views
function getUIntValue(bytes32 contractName, bytes32 record) external view returns (uint);
function getUIntValues(bytes32 contractName, bytes32[] calldata records) external view returns (uint[] memory);
function getIntValue(bytes32 contractName, bytes32 record) external view returns (int);
function getIntValues(bytes32 contractName, bytes32[] calldata records) external view returns (int[] memory);
function getAddressValue(bytes32 contractName, bytes32 record) external view returns (address);
function getAddressValues(bytes32 contractName, bytes32[] calldata records) external view returns (address[] memory);
function getBoolValue(bytes32 contractName, bytes32 record) external view returns (bool);
function getBoolValues(bytes32 contractName, bytes32[] calldata records) external view returns (bool[] memory);
function getBytes32Value(bytes32 contractName, bytes32 record) external view returns (bytes32);
function getBytes32Values(bytes32 contractName, bytes32[] calldata records) external view returns (bytes32[] memory);
// Mutative functions
function deleteUIntValue(bytes32 contractName, bytes32 record) external;
function deleteIntValue(bytes32 contractName, bytes32 record) external;
function deleteAddressValue(bytes32 contractName, bytes32 record) external;
function deleteBoolValue(bytes32 contractName, bytes32 record) external;
function deleteBytes32Value(bytes32 contractName, bytes32 record) external;
function setUIntValue(
bytes32 contractName,
bytes32 record,
uint value
) external;
function setUIntValues(
bytes32 contractName,
bytes32[] calldata records,
uint[] calldata values
) external;
function setIntValue(
bytes32 contractName,
bytes32 record,
int value
) external;
function setIntValues(
bytes32 contractName,
bytes32[] calldata records,
int[] calldata values
) external;
function setAddressValue(
bytes32 contractName,
bytes32 record,
address value
) external;
function setAddressValues(
bytes32 contractName,
bytes32[] calldata records,
address[] calldata values
) external;
function setBoolValue(
bytes32 contractName,
bytes32 record,
bool value
) external;
function setBoolValues(
bytes32 contractName,
bytes32[] calldata records,
bool[] calldata values
) external;
function setBytes32Value(
bytes32 contractName,
bytes32 record,
bytes32 value
) external;
function setBytes32Values(
bytes32 contractName,
bytes32[] calldata records,
bytes32[] calldata values
) external;
}
// Internal references
// https://docs.synthetix.io/contracts/source/contracts/mixinsystemsettings
contract MixinSystemSettings is MixinResolver {
bytes32 internal constant SETTING_CONTRACT_NAME = "SystemSettings";
bytes32 internal constant SETTING_WAITING_PERIOD_SECS = "waitingPeriodSecs";
bytes32 internal constant SETTING_PRICE_DEVIATION_THRESHOLD_FACTOR = "priceDeviationThresholdFactor";
bytes32 internal constant SETTING_ISSUANCE_RATIO = "issuanceRatio";
bytes32 internal constant SETTING_FEE_PERIOD_DURATION = "feePeriodDuration";
bytes32 internal constant SETTING_TARGET_THRESHOLD = "targetThreshold";
bytes32 internal constant SETTING_LIQUIDATION_DELAY = "liquidationDelay";
bytes32 internal constant SETTING_LIQUIDATION_RATIO = "liquidationRatio";
bytes32 internal constant SETTING_LIQUIDATION_PENALTY = "liquidationPenalty";
bytes32 internal constant SETTING_RATE_STALE_PERIOD = "rateStalePeriod";
bytes32 internal constant SETTING_EXCHANGE_FEE_RATE = "exchangeFeeRate";
bytes32 internal constant SETTING_MINIMUM_STAKE_TIME = "minimumStakeTime";
bytes32 internal constant SETTING_AGGREGATOR_WARNING_FLAGS = "aggregatorWarningFlags";
bytes32 internal constant SETTING_TRADING_REWARDS_ENABLED = "tradingRewardsEnabled";
bytes32 internal constant SETTING_DEBT_SNAPSHOT_STALE_TIME = "debtSnapshotStaleTime";
bytes32 internal constant SETTING_CROSS_DOMAIN_DEPOSIT_GAS_LIMIT = "crossDomainDepositGasLimit";
bytes32 internal constant SETTING_CROSS_DOMAIN_ESCROW_GAS_LIMIT = "crossDomainEscrowGasLimit";
bytes32 internal constant SETTING_CROSS_DOMAIN_REWARD_GAS_LIMIT = "crossDomainRewardGasLimit";
bytes32 internal constant SETTING_CROSS_DOMAIN_WITHDRAWAL_GAS_LIMIT = "crossDomainWithdrawalGasLimit";
bytes32 internal constant SETTING_ETHER_WRAPPER_MAX_ETH = "etherWrapperMaxETH";
bytes32 internal constant SETTING_ETHER_WRAPPER_MINT_FEE_RATE = "etherWrapperMintFeeRate";
bytes32 internal constant SETTING_ETHER_WRAPPER_BURN_FEE_RATE = "etherWrapperBurnFeeRate";
bytes32 internal constant CONTRACT_FLEXIBLESTORAGE = "FlexibleStorage";
enum CrossDomainMessageGasLimits {Deposit, Escrow, Reward, Withdrawal}
constructor(address _resolver) internal MixinResolver(_resolver) {}
function resolverAddressesRequired() public view returns (bytes32[] memory addresses) {
addresses = new bytes32[](1);
addresses[0] = CONTRACT_FLEXIBLESTORAGE;
}
function flexibleStorage() internal view returns (IFlexibleStorage) {
return IFlexibleStorage(requireAndGetAddress(CONTRACT_FLEXIBLESTORAGE));
}
function _getGasLimitSetting(CrossDomainMessageGasLimits gasLimitType) internal pure returns (bytes32) {
if (gasLimitType == CrossDomainMessageGasLimits.Deposit) {
return SETTING_CROSS_DOMAIN_DEPOSIT_GAS_LIMIT;
} else if (gasLimitType == CrossDomainMessageGasLimits.Escrow) {
return SETTING_CROSS_DOMAIN_ESCROW_GAS_LIMIT;
} else if (gasLimitType == CrossDomainMessageGasLimits.Reward) {
return SETTING_CROSS_DOMAIN_REWARD_GAS_LIMIT;
} else if (gasLimitType == CrossDomainMessageGasLimits.Withdrawal) {
return SETTING_CROSS_DOMAIN_WITHDRAWAL_GAS_LIMIT;
} else {
revert("Unknown gas limit type");
}
}
function getCrossDomainMessageGasLimit(CrossDomainMessageGasLimits gasLimitType) internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, _getGasLimitSetting(gasLimitType));
}
function getTradingRewardsEnabled() internal view returns (bool) {
return flexibleStorage().getBoolValue(SETTING_CONTRACT_NAME, SETTING_TRADING_REWARDS_ENABLED);
}
function getWaitingPeriodSecs() internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_WAITING_PERIOD_SECS);
}
function getPriceDeviationThresholdFactor() internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_PRICE_DEVIATION_THRESHOLD_FACTOR);
}
function getIssuanceRatio() internal view returns (uint) {
// lookup on flexible storage directly for gas savings (rather than via SystemSettings)
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_ISSUANCE_RATIO);
}
function getFeePeriodDuration() internal view returns (uint) {
// lookup on flexible storage directly for gas savings (rather than via SystemSettings)
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_FEE_PERIOD_DURATION);
}
function getTargetThreshold() internal view returns (uint) {
// lookup on flexible storage directly for gas savings (rather than via SystemSettings)
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_TARGET_THRESHOLD);
}
function getLiquidationDelay() internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_LIQUIDATION_DELAY);
}
function getLiquidationRatio() internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_LIQUIDATION_RATIO);
}
function getLiquidationPenalty() internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_LIQUIDATION_PENALTY);
}
function getRateStalePeriod() internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_RATE_STALE_PERIOD);
}
function getExchangeFeeRate(bytes32 currencyKey) internal view returns (uint) {
return
flexibleStorage().getUIntValue(
SETTING_CONTRACT_NAME,
keccak256(abi.encodePacked(SETTING_EXCHANGE_FEE_RATE, currencyKey))
);
}
function getMinimumStakeTime() internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_MINIMUM_STAKE_TIME);
}
function getAggregatorWarningFlags() internal view returns (address) {
return flexibleStorage().getAddressValue(SETTING_CONTRACT_NAME, SETTING_AGGREGATOR_WARNING_FLAGS);
}
function getDebtSnapshotStaleTime() internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_DEBT_SNAPSHOT_STALE_TIME);
}
function getEtherWrapperMaxETH() internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_ETHER_WRAPPER_MAX_ETH);
}
function getEtherWrapperMintFeeRate() internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_ETHER_WRAPPER_MINT_FEE_RATE);
}
function getEtherWrapperBurnFeeRate() internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_ETHER_WRAPPER_BURN_FEE_RATE);
}
}
// https://docs.synthetix.io/contracts/source/interfaces/iexchanger
interface IExchanger {
// Views
function calculateAmountAfterSettlement(
address from,
bytes32 currencyKey,
uint amount,
uint refunded
) external view returns (uint amountAfterSettlement);
function isSynthRateInvalid(bytes32 currencyKey) external view returns (bool);
function maxSecsLeftInWaitingPeriod(address account, bytes32 currencyKey) external view returns (uint);
function settlementOwing(address account, bytes32 currencyKey)
external
view
returns (
uint reclaimAmount,
uint rebateAmount,
uint numEntries
);
function hasWaitingPeriodOrSettlementOwing(address account, bytes32 currencyKey) external view returns (bool);
function feeRateForExchange(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey)
external
view
returns (uint exchangeFeeRate);
function getAmountsForExchange(
uint sourceAmount,
bytes32 sourceCurrencyKey,
bytes32 destinationCurrencyKey
)
external
view
returns (
uint amountReceived,
uint fee,
uint exchangeFeeRate
);
function priceDeviationThresholdFactor() external view returns (uint);
function waitingPeriodSecs() external view returns (uint);
// Mutative functions
function exchange(
address exchangeForAddress,
address from,
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey,
address destinationAddress,
bool virtualSynth,
address rewardAddress,
bytes32 trackingCode
) external returns (uint amountReceived, IVirtualSynth vSynth);
function settle(address from, bytes32 currencyKey)
external
returns (
uint reclaimed,
uint refunded,
uint numEntries
);
function setLastExchangeRateForSynth(bytes32 currencyKey, uint rate) external;
function resetLastExchangeRate(bytes32[] calldata currencyKeys) external;
function suspendSynthWithInvalidRate(bytes32 currencyKey) external;
}
pragma experimental ABIEncoderV2;
library VestingEntries {
struct VestingEntry {
uint64 endTime;
uint256 escrowAmount;
}
struct VestingEntryWithID {
uint64 endTime;
uint256 escrowAmount;
uint256 entryID;
}
}
interface IRewardEscrowV2 {
// Views
function balanceOf(address account) external view returns (uint);
function numVestingEntries(address account) external view returns (uint);
function totalEscrowedAccountBalance(address account) external view returns (uint);
function totalVestedAccountBalance(address account) external view returns (uint);
function getVestingQuantity(address account, uint256[] calldata entryIDs) external view returns (uint);
function getVestingSchedules(
address account,
uint256 index,
uint256 pageSize
) external view returns (VestingEntries.VestingEntryWithID[] memory);
function getAccountVestingEntryIDs(
address account,
uint256 index,
uint256 pageSize
) external view returns (uint256[] memory);
function getVestingEntryClaimable(address account, uint256 entryID) external view returns (uint);
function getVestingEntry(address account, uint256 entryID) external view returns (uint64, uint256);
// Mutative functions
function vest(uint256[] calldata entryIDs) external;
function createEscrowEntry(
address beneficiary,
uint256 deposit,
uint256 duration
) external;
function appendVestingEntry(
address account,
uint256 quantity,
uint256 duration
) external;
function migrateVestingSchedule(address _addressToMigrate) external;
function migrateAccountEscrowBalances(
address[] calldata accounts,
uint256[] calldata escrowBalances,
uint256[] calldata vestedBalances
) external;
// Account Merging
function startMergingWindow() external;
function mergeAccount(address accountToMerge, uint256[] calldata entryIDs) external;
function nominateAccountToMerge(address account) external;
function accountMergingIsOpen() external view returns (bool);
// L2 Migration
function importVestingEntries(
address account,
uint256 escrowedAmount,
VestingEntries.VestingEntry[] calldata vestingEntries
) external;
// Return amount of SNX transfered to SynthetixBridgeToOptimism deposit contract
function burnForMigration(address account, uint256[] calldata entryIDs)
external
returns (uint256 escrowedAccountBalance, VestingEntries.VestingEntry[] memory vestingEntries);
}
// https://docs.synthetix.io/contracts/source/interfaces/idelegateapprovals
interface IDelegateApprovals {
// Views
function canBurnFor(address authoriser, address delegate) external view returns (bool);
function canIssueFor(address authoriser, address delegate) external view returns (bool);
function canClaimFor(address authoriser, address delegate) external view returns (bool);
function canExchangeFor(address authoriser, address delegate) external view returns (bool);
// Mutative
function approveAllDelegatePowers(address delegate) external;
function removeAllDelegatePowers(address delegate) external;
function approveBurnOnBehalf(address delegate) external;
function removeBurnOnBehalf(address delegate) external;
function approveIssueOnBehalf(address delegate) external;
function removeIssueOnBehalf(address delegate) external;
function approveClaimOnBehalf(address delegate) external;
function removeClaimOnBehalf(address delegate) external;
function approveExchangeOnBehalf(address delegate) external;
function removeExchangeOnBehalf(address delegate) external;
}
interface ICollateralManager {
// Manager information
function hasCollateral(address collateral) external view returns (bool);
function isSynthManaged(bytes32 currencyKey) external view returns (bool);
// State information
function long(bytes32 synth) external view returns (uint amount);
function short(bytes32 synth) external view returns (uint amount);
function totalLong() external view returns (uint susdValue, bool anyRateIsInvalid);
function totalShort() external view returns (uint susdValue, bool anyRateIsInvalid);
function getBorrowRate() external view returns (uint borrowRate, bool anyRateIsInvalid);
function getShortRate(bytes32 synth) external view returns (uint shortRate, bool rateIsInvalid);
function getRatesAndTime(uint index)
external
view
returns (
uint entryRate,
uint lastRate,
uint lastUpdated,
uint newIndex
);
function getShortRatesAndTime(bytes32 currency, uint index)
external
view
returns (
uint entryRate,
uint lastRate,
uint lastUpdated,
uint newIndex
);
function exceedsDebtLimit(uint amount, bytes32 currency) external view returns (bool canIssue, bool anyRateIsInvalid);
function areSynthsAndCurrenciesSet(bytes32[] calldata requiredSynthNamesInResolver, bytes32[] calldata synthKeys)
external
view
returns (bool);
function areShortableSynthsSet(bytes32[] calldata requiredSynthNamesInResolver, bytes32[] calldata synthKeys)
external
view
returns (bool);
// Loans
function getNewLoanId() external returns (uint id);
// Manager mutative
function addCollaterals(address[] calldata collaterals) external;
function removeCollaterals(address[] calldata collaterals) external;
function addSynths(bytes32[] calldata synthNamesInResolver, bytes32[] calldata synthKeys) external;
function removeSynths(bytes32[] calldata synths, bytes32[] calldata synthKeys) external;
function addShortableSynths(bytes32[2][] calldata requiredSynthAndInverseNamesInResolver, bytes32[] calldata synthKeys)
external;
function removeShortableSynths(bytes32[] calldata synths) external;
// State mutative
function updateBorrowRates(uint rate) external;
function updateShortRates(bytes32 currency, uint rate) external;
function incrementLongs(bytes32 synth, uint amount) external;
function decrementLongs(bytes32 synth, uint amount) external;
function incrementShorts(bytes32 synth, uint amount) external;
function decrementShorts(bytes32 synth, uint amount) external;
}
interface IWETH {
// ERC20 Optional Views
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
// Views
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
// Mutative functions
function transfer(address to, uint value) external returns (bool);
function approve(address spender, uint value) external returns (bool);
function transferFrom(
address from,
address to,
uint value
) external returns (bool);
// WETH-specific functions.
function deposit() external payable;
function withdraw(uint amount) external;
// Events
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
event Deposit(address indexed to, uint amount);
event Withdrawal(address indexed to, uint amount);
}
// https://docs.synthetix.io/contracts/source/interfaces/ietherwrapper
contract IEtherWrapper {
function mint(uint amount) external;
function burn(uint amount) external;
function distributeFees() external;
function capacity() external view returns (uint);
function getReserves() external view returns (uint);
function totalIssuedSynths() external view returns (uint);
function calculateMintFee(uint amount) public view returns (uint);
function calculateBurnFee(uint amount) public view returns (uint);
function maxETH() public view returns (uint256);
function mintFeeRate() public view returns (uint256);
function burnFeeRate() public view returns (uint256);
function weth() public view returns (IWETH);
}
// Inheritance
// Libraries
// Internal references
// https://docs.synthetix.io/contracts/source/contracts/feepool
contract FeePool is Owned, Proxyable, LimitedSetup, MixinSystemSettings, IFeePool {
using SafeMath for uint;
using SafeDecimalMath for uint;
bytes32 public constant CONTRACT_NAME = "FeePool";
// Where fees are pooled in sUSD.
address public constant FEE_ADDRESS = 0xfeEFEEfeefEeFeefEEFEEfEeFeefEEFeeFEEFEeF;
// sUSD currencyKey. Fees stored and paid in sUSD
bytes32 private sUSD = "sUSD";
// This struct represents the issuance activity that's happened in a fee period.
struct FeePeriod {
uint64 feePeriodId;
uint64 startingDebtIndex;
uint64 startTime;
uint feesToDistribute;
uint feesClaimed;
uint rewardsToDistribute;
uint rewardsClaimed;
}
// A staker(mintr) can claim from the previous fee period (7 days) only.
// Fee Periods stored and managed from [0], such that [0] is always
// the current active fee period which is not claimable until the
// public function closeCurrentFeePeriod() is called closing the
// current weeks collected fees. [1] is last weeks feeperiod
uint8 public constant FEE_PERIOD_LENGTH = 2;
FeePeriod[FEE_PERIOD_LENGTH] private _recentFeePeriods;
uint256 private _currentFeePeriod;
/* ========== ADDRESS RESOLVER CONFIGURATION ========== */
bytes32 private constant CONTRACT_SYSTEMSTATUS = "SystemStatus";
bytes32 private constant CONTRACT_SYNTHETIX = "Synthetix";
bytes32 private constant CONTRACT_FEEPOOLSTATE = "FeePoolState";
bytes32 private constant CONTRACT_FEEPOOLETERNALSTORAGE = "FeePoolEternalStorage";
bytes32 private constant CONTRACT_EXCHANGER = "Exchanger";
bytes32 private constant CONTRACT_ISSUER = "Issuer";
bytes32 private constant CONTRACT_SYNTHETIXSTATE = "SynthetixState";
bytes32 private constant CONTRACT_REWARDESCROW_V2 = "RewardEscrowV2";
bytes32 private constant CONTRACT_DELEGATEAPPROVALS = "DelegateApprovals";
bytes32 private constant CONTRACT_COLLATERALMANAGER = "CollateralManager";
bytes32 private constant CONTRACT_REWARDSDISTRIBUTION = "RewardsDistribution";
bytes32 private constant CONTRACT_ETHER_WRAPPER = "EtherWrapper";
/* ========== ETERNAL STORAGE CONSTANTS ========== */
bytes32 private constant LAST_FEE_WITHDRAWAL = "last_fee_withdrawal";
constructor(
address payable _proxy,
address _owner,
address _resolver
) public Owned(_owner) Proxyable(_proxy) LimitedSetup(3 weeks) MixinSystemSettings(_resolver) {
// Set our initial fee period
_recentFeePeriodsStorage(0).feePeriodId = 1;
_recentFeePeriodsStorage(0).startTime = uint64(now);
}
/* ========== VIEWS ========== */
function resolverAddressesRequired() public view returns (bytes32[] memory addresses) {
bytes32[] memory existingAddresses = MixinSystemSettings.resolverAddressesRequired();
bytes32[] memory newAddresses = new bytes32[](12);
newAddresses[0] = CONTRACT_SYSTEMSTATUS;
newAddresses[1] = CONTRACT_SYNTHETIX;
newAddresses[2] = CONTRACT_FEEPOOLSTATE;
newAddresses[3] = CONTRACT_FEEPOOLETERNALSTORAGE;
newAddresses[4] = CONTRACT_EXCHANGER;
newAddresses[5] = CONTRACT_ISSUER;
newAddresses[6] = CONTRACT_SYNTHETIXSTATE;
newAddresses[7] = CONTRACT_REWARDESCROW_V2;
newAddresses[8] = CONTRACT_DELEGATEAPPROVALS;
newAddresses[9] = CONTRACT_REWARDSDISTRIBUTION;
newAddresses[10] = CONTRACT_COLLATERALMANAGER;
newAddresses[11] = CONTRACT_ETHER_WRAPPER;
addresses = combineArrays(existingAddresses, newAddresses);
}
function systemStatus() internal view returns (ISystemStatus) {
return ISystemStatus(requireAndGetAddress(CONTRACT_SYSTEMSTATUS));
}
function synthetix() internal view returns (ISynthetix) {
return ISynthetix(requireAndGetAddress(CONTRACT_SYNTHETIX));
}
function feePoolState() internal view returns (FeePoolState) {
return FeePoolState(requireAndGetAddress(CONTRACT_FEEPOOLSTATE));
}
function feePoolEternalStorage() internal view returns (FeePoolEternalStorage) {
return FeePoolEternalStorage(requireAndGetAddress(CONTRACT_FEEPOOLETERNALSTORAGE));
}
function exchanger() internal view returns (IExchanger) {
return IExchanger(requireAndGetAddress(CONTRACT_EXCHANGER));
}
function collateralManager() internal view returns (ICollateralManager) {
return ICollateralManager(requireAndGetAddress(CONTRACT_COLLATERALMANAGER));
}
function issuer() internal view returns (IIssuer) {
return IIssuer(requireAndGetAddress(CONTRACT_ISSUER));
}
function synthetixState() internal view returns (ISynthetixState) {
return ISynthetixState(requireAndGetAddress(CONTRACT_SYNTHETIXSTATE));
}
function rewardEscrowV2() internal view returns (IRewardEscrowV2) {
return IRewardEscrowV2(requireAndGetAddress(CONTRACT_REWARDESCROW_V2));
}
function delegateApprovals() internal view returns (IDelegateApprovals) {
return IDelegateApprovals(requireAndGetAddress(CONTRACT_DELEGATEAPPROVALS));
}
function rewardsDistribution() internal view returns (IRewardsDistribution) {
return IRewardsDistribution(requireAndGetAddress(CONTRACT_REWARDSDISTRIBUTION));
}
function etherWrapper() internal view returns (IEtherWrapper) {
return IEtherWrapper(requireAndGetAddress(CONTRACT_ETHER_WRAPPER));
}
function issuanceRatio() external view returns (uint) {
return getIssuanceRatio();
}
function feePeriodDuration() external view returns (uint) {
return getFeePeriodDuration();
}
function targetThreshold() external view returns (uint) {
return getTargetThreshold();
}
function recentFeePeriods(uint index)
external
view
returns (
uint64 feePeriodId,
uint64 startingDebtIndex,
uint64 startTime,
uint feesToDistribute,
uint feesClaimed,
uint rewardsToDistribute,
uint rewardsClaimed
)
{
FeePeriod memory feePeriod = _recentFeePeriodsStorage(index);
return (
feePeriod.feePeriodId,
feePeriod.startingDebtIndex,
feePeriod.startTime,
feePeriod.feesToDistribute,
feePeriod.feesClaimed,
feePeriod.rewardsToDistribute,
feePeriod.rewardsClaimed
);
}
function _recentFeePeriodsStorage(uint index) internal view returns (FeePeriod storage) {
return _recentFeePeriods[(_currentFeePeriod + index) % FEE_PERIOD_LENGTH];
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice Logs an accounts issuance data per fee period
* @param account Message.Senders account address
* @param debtRatio Debt percentage this account has locked after minting or burning their synth
* @param debtEntryIndex The index in the global debt ledger. synthetixState.issuanceData(account)
* @dev onlyIssuer to call me on synthetix.issue() & synthetix.burn() calls to store the locked SNX
* per fee period so we know to allocate the correct proportions of fees and rewards per period
*/
function appendAccountIssuanceRecord(
address account,
uint debtRatio,
uint debtEntryIndex
) external onlyIssuerAndSynthetixState {
feePoolState().appendAccountIssuanceRecord(
account,
debtRatio,
debtEntryIndex,
_recentFeePeriodsStorage(0).startingDebtIndex
);
emitIssuanceDebtRatioEntry(account, debtRatio, debtEntryIndex, _recentFeePeriodsStorage(0).startingDebtIndex);
}
/**
* @notice The Exchanger contract informs us when fees are paid.
* @param amount susd amount in fees being paid.
*/
function recordFeePaid(uint amount) external onlyInternalContracts {
// Keep track off fees in sUSD in the open fee pool period.
_recentFeePeriodsStorage(0).feesToDistribute = _recentFeePeriodsStorage(0).feesToDistribute.add(amount);
}
/**
* @notice The RewardsDistribution contract informs us how many SNX rewards are sent to RewardEscrow to be claimed.
*/
function setRewardsToDistribute(uint amount) external {
address rewardsAuthority = address(rewardsDistribution());
require(messageSender == rewardsAuthority || msg.sender == rewardsAuthority, "Caller is not rewardsAuthority");
// Add the amount of SNX rewards to distribute on top of any rolling unclaimed amount
_recentFeePeriodsStorage(0).rewardsToDistribute = _recentFeePeriodsStorage(0).rewardsToDistribute.add(amount);
}
/**
* @notice Close the current fee period and start a new one.
*/
function closeCurrentFeePeriod() external issuanceActive {
require(getFeePeriodDuration() > 0, "Fee Period Duration not set");
require(_recentFeePeriodsStorage(0).startTime <= (now - getFeePeriodDuration()), "Too early to close fee period");
etherWrapper().distributeFees();
// Note: when FEE_PERIOD_LENGTH = 2, periodClosing is the current period & periodToRollover is the last open claimable period
FeePeriod storage periodClosing = _recentFeePeriodsStorage(FEE_PERIOD_LENGTH - 2);
FeePeriod storage periodToRollover = _recentFeePeriodsStorage(FEE_PERIOD_LENGTH - 1);
// Any unclaimed fees from the last period in the array roll back one period.
// Because of the subtraction here, they're effectively proportionally redistributed to those who
// have already claimed from the old period, available in the new period.
// The subtraction is important so we don't create a ticking time bomb of an ever growing
// number of fees that can never decrease and will eventually overflow at the end of the fee pool.
_recentFeePeriodsStorage(FEE_PERIOD_LENGTH - 2).feesToDistribute = periodToRollover
.feesToDistribute
.sub(periodToRollover.feesClaimed)
.add(periodClosing.feesToDistribute);
_recentFeePeriodsStorage(FEE_PERIOD_LENGTH - 2).rewardsToDistribute = periodToRollover
.rewardsToDistribute
.sub(periodToRollover.rewardsClaimed)
.add(periodClosing.rewardsToDistribute);
// Shift the previous fee periods across to make room for the new one.
_currentFeePeriod = _currentFeePeriod.add(FEE_PERIOD_LENGTH).sub(1).mod(FEE_PERIOD_LENGTH);
// Clear the first element of the array to make sure we don't have any stale values.
delete _recentFeePeriods[_currentFeePeriod];
// Open up the new fee period.
// Increment periodId from the recent closed period feePeriodId
_recentFeePeriodsStorage(0).feePeriodId = uint64(uint256(_recentFeePeriodsStorage(1).feePeriodId).add(1));
_recentFeePeriodsStorage(0).startingDebtIndex = uint64(synthetixState().debtLedgerLength());
_recentFeePeriodsStorage(0).startTime = uint64(now);
emitFeePeriodClosed(_recentFeePeriodsStorage(1).feePeriodId);
}
/**
* @notice Claim fees for last period when available or not already withdrawn.
*/
function claimFees() external issuanceActive optionalProxy returns (bool) {
return _claimFees(messageSender);
}
/**
* @notice Delegated claimFees(). Call from the deletegated address
* and the fees will be sent to the claimingForAddress.
* approveClaimOnBehalf() must be called first to approve the deletage address
* @param claimingForAddress The account you are claiming fees for
*/
function claimOnBehalf(address claimingForAddress) external issuanceActive optionalProxy returns (bool) {
require(delegateApprovals().canClaimFor(claimingForAddress, messageSender), "Not approved to claim on behalf");
return _claimFees(claimingForAddress);
}
function _claimFees(address claimingAddress) internal returns (bool) {
uint rewardsPaid = 0;
uint feesPaid = 0;
uint availableFees;
uint availableRewards;
// Address won't be able to claim fees if it is too far below the target c-ratio.
// It will need to burn synths then try claiming again.
(bool feesClaimable, bool anyRateIsInvalid) = _isFeesClaimableAndAnyRatesInvalid(claimingAddress);
require(feesClaimable, "C-Ratio below penalty threshold");
require(!anyRateIsInvalid, "A synth or SNX rate is invalid");
// Get the claimingAddress available fees and rewards
(availableFees, availableRewards) = feesAvailable(claimingAddress);
require(
availableFees > 0 || availableRewards > 0,
"No fees or rewards available for period, or fees already claimed"
);
// Record the address has claimed for this period
_setLastFeeWithdrawal(claimingAddress, _recentFeePeriodsStorage(1).feePeriodId);
if (availableFees > 0) {
// Record the fee payment in our recentFeePeriods
feesPaid = _recordFeePayment(availableFees);
// Send them their fees
_payFees(claimingAddress, feesPaid);
}
if (availableRewards > 0) {
// Record the reward payment in our recentFeePeriods
rewardsPaid = _recordRewardPayment(availableRewards);
// Send them their rewards
_payRewards(claimingAddress, rewardsPaid);
}
emitFeesClaimed(claimingAddress, feesPaid, rewardsPaid);
return true;
}
/**
* @notice Admin function to import the FeePeriod data from the previous contract
*/
function importFeePeriod(
uint feePeriodIndex,
uint feePeriodId,
uint startingDebtIndex,
uint startTime,
uint feesToDistribute,
uint feesClaimed,
uint rewardsToDistribute,
uint rewardsClaimed
) public optionalProxy_onlyOwner onlyDuringSetup {
require(startingDebtIndex <= synthetixState().debtLedgerLength(), "Cannot import bad data");
_recentFeePeriods[_currentFeePeriod.add(feePeriodIndex).mod(FEE_PERIOD_LENGTH)] = FeePeriod({
feePeriodId: uint64(feePeriodId),
startingDebtIndex: uint64(startingDebtIndex),
startTime: uint64(startTime),
feesToDistribute: feesToDistribute,
feesClaimed: feesClaimed,
rewardsToDistribute: rewardsToDistribute,
rewardsClaimed: rewardsClaimed
});
}
/**
* @notice Record the fee payment in our recentFeePeriods.
* @param sUSDAmount The amount of fees priced in sUSD.
*/
function _recordFeePayment(uint sUSDAmount) internal returns (uint) {
// Don't assign to the parameter
uint remainingToAllocate = sUSDAmount;
uint feesPaid;
// Start at the oldest period and record the amount, moving to newer periods
// until we've exhausted the amount.
// The condition checks for overflow because we're going to 0 with an unsigned int.
for (uint i = FEE_PERIOD_LENGTH - 1; i < FEE_PERIOD_LENGTH; i--) {
uint feesAlreadyClaimed = _recentFeePeriodsStorage(i).feesClaimed;
uint delta = _recentFeePeriodsStorage(i).feesToDistribute.sub(feesAlreadyClaimed);
if (delta > 0) {
// Take the smaller of the amount left to claim in the period and the amount we need to allocate
uint amountInPeriod = delta < remainingToAllocate ? delta : remainingToAllocate;
_recentFeePeriodsStorage(i).feesClaimed = feesAlreadyClaimed.add(amountInPeriod);
remainingToAllocate = remainingToAllocate.sub(amountInPeriod);
feesPaid = feesPaid.add(amountInPeriod);
// No need to continue iterating if we've recorded the whole amount;
if (remainingToAllocate == 0) return feesPaid;
// We've exhausted feePeriods to distribute and no fees remain in last period
// User last to claim would in this scenario have their remainder slashed
if (i == 0 && remainingToAllocate > 0) {
remainingToAllocate = 0;
}
}
}
return feesPaid;
}
/**
* @notice Record the reward payment in our recentFeePeriods.
* @param snxAmount The amount of SNX tokens.
*/
function _recordRewardPayment(uint snxAmount) internal returns (uint) {
// Don't assign to the parameter
uint remainingToAllocate = snxAmount;
uint rewardPaid;
// Start at the oldest period and record the amount, moving to newer periods
// until we've exhausted the amount.
// The condition checks for overflow because we're going to 0 with an unsigned int.
for (uint i = FEE_PERIOD_LENGTH - 1; i < FEE_PERIOD_LENGTH; i--) {
uint toDistribute =
_recentFeePeriodsStorage(i).rewardsToDistribute.sub(_recentFeePeriodsStorage(i).rewardsClaimed);
if (toDistribute > 0) {
// Take the smaller of the amount left to claim in the period and the amount we need to allocate
uint amountInPeriod = toDistribute < remainingToAllocate ? toDistribute : remainingToAllocate;
_recentFeePeriodsStorage(i).rewardsClaimed = _recentFeePeriodsStorage(i).rewardsClaimed.add(amountInPeriod);
remainingToAllocate = remainingToAllocate.sub(amountInPeriod);
rewardPaid = rewardPaid.add(amountInPeriod);
// No need to continue iterating if we've recorded the whole amount;
if (remainingToAllocate == 0) return rewardPaid;
// We've exhausted feePeriods to distribute and no rewards remain in last period
// User last to claim would in this scenario have their remainder slashed
// due to rounding up of PreciseDecimal
if (i == 0 && remainingToAllocate > 0) {
remainingToAllocate = 0;
}
}
}
return rewardPaid;
}
/**
* @notice Send the fees to claiming address.
* @param account The address to send the fees to.
* @param sUSDAmount The amount of fees priced in sUSD.
*/
function _payFees(address account, uint sUSDAmount) internal notFeeAddress(account) {
// Grab the sUSD Synth
ISynth sUSDSynth = issuer().synths(sUSD);
// NOTE: we do not control the FEE_ADDRESS so it is not possible to do an
// ERC20.approve() transaction to allow this feePool to call ERC20.transferFrom
// to the accounts address
// Burn the source amount
sUSDSynth.burn(FEE_ADDRESS, sUSDAmount);
// Mint their new synths
sUSDSynth.issue(account, sUSDAmount);
}
/**
* @notice Send the rewards to claiming address - will be locked in rewardEscrow.
* @param account The address to send the fees to.
* @param snxAmount The amount of SNX.
*/
function _payRewards(address account, uint snxAmount) internal notFeeAddress(account) {
/* Escrow the tokens for 1 year. */
uint escrowDuration = 52 weeks;
// Record vesting entry for claiming address and amount
// SNX already minted to rewardEscrow balance
rewardEscrowV2().appendVestingEntry(account, snxAmount, escrowDuration);
}
/**
* @notice The total fees available in the system to be withdrawnn in sUSD
*/
function totalFeesAvailable() external view returns (uint) {
uint totalFees = 0;
// Fees in fee period [0] are not yet available for withdrawal
for (uint i = 1; i < FEE_PERIOD_LENGTH; i++) {
totalFees = totalFees.add(_recentFeePeriodsStorage(i).feesToDistribute);
totalFees = totalFees.sub(_recentFeePeriodsStorage(i).feesClaimed);
}
return totalFees;
}
/**
* @notice The total SNX rewards available in the system to be withdrawn
*/
function totalRewardsAvailable() external view returns (uint) {
uint totalRewards = 0;
// Rewards in fee period [0] are not yet available for withdrawal
for (uint i = 1; i < FEE_PERIOD_LENGTH; i++) {
totalRewards = totalRewards.add(_recentFeePeriodsStorage(i).rewardsToDistribute);
totalRewards = totalRewards.sub(_recentFeePeriodsStorage(i).rewardsClaimed);
}
return totalRewards;
}
/**
* @notice The fees available to be withdrawn by a specific account, priced in sUSD
* @dev Returns two amounts, one for fees and one for SNX rewards
*/
function feesAvailable(address account) public view returns (uint, uint) {
// Add up the fees
uint[2][FEE_PERIOD_LENGTH] memory userFees = feesByPeriod(account);
uint totalFees = 0;
uint totalRewards = 0;
// Fees & Rewards in fee period [0] are not yet available for withdrawal
for (uint i = 1; i < FEE_PERIOD_LENGTH; i++) {
totalFees = totalFees.add(userFees[i][0]);
totalRewards = totalRewards.add(userFees[i][1]);
}
// And convert totalFees to sUSD
// Return totalRewards as is in SNX amount
return (totalFees, totalRewards);
}
function _isFeesClaimableAndAnyRatesInvalid(address account) internal view returns (bool, bool) {
// Threshold is calculated from ratio % above the target ratio (issuanceRatio).
// 0 < 10%: Claimable
// 10% > above: Unable to claim
(uint ratio, bool anyRateIsInvalid) = issuer().collateralisationRatioAndAnyRatesInvalid(account);
uint targetRatio = getIssuanceRatio();
// Claimable if collateral ratio below target ratio
if (ratio < targetRatio) {
return (true, anyRateIsInvalid);
}
// Calculate the threshold for collateral ratio before fees can't be claimed.
uint ratio_threshold = targetRatio.multiplyDecimal(SafeDecimalMath.unit().add(getTargetThreshold()));
// Not claimable if collateral ratio above threshold
if (ratio > ratio_threshold) {
return (false, anyRateIsInvalid);
}
return (true, anyRateIsInvalid);
}
function isFeesClaimable(address account) external view returns (bool feesClaimable) {
(feesClaimable, ) = _isFeesClaimableAndAnyRatesInvalid(account);
}
/**
* @notice Calculates fees by period for an account, priced in sUSD
* @param account The address you want to query the fees for
*/
function feesByPeriod(address account) public view returns (uint[2][FEE_PERIOD_LENGTH] memory results) {
// What's the user's debt entry index and the debt they owe to the system at current feePeriod
uint userOwnershipPercentage;
uint debtEntryIndex;
FeePoolState _feePoolState = feePoolState();
(userOwnershipPercentage, debtEntryIndex) = _feePoolState.getAccountsDebtEntry(account, 0);
// If they don't have any debt ownership and they never minted, they don't have any fees.
// User ownership can reduce to 0 if user burns all synths,
// however they could have fees applicable for periods they had minted in before so we check debtEntryIndex.
if (debtEntryIndex == 0 && userOwnershipPercentage == 0) {
uint[2][FEE_PERIOD_LENGTH] memory nullResults;
return nullResults;
}
// The [0] fee period is not yet ready to claim, but it is a fee period that they can have
// fees owing for, so we need to report on it anyway.
uint feesFromPeriod;
uint rewardsFromPeriod;
(feesFromPeriod, rewardsFromPeriod) = _feesAndRewardsFromPeriod(0, userOwnershipPercentage, debtEntryIndex);
results[0][0] = feesFromPeriod;
results[0][1] = rewardsFromPeriod;
// Retrieve user's last fee claim by periodId
uint lastFeeWithdrawal = getLastFeeWithdrawal(account);
// Go through our fee periods from the oldest feePeriod[FEE_PERIOD_LENGTH - 1] and figure out what we owe them.
// Condition checks for periods > 0
for (uint i = FEE_PERIOD_LENGTH - 1; i > 0; i--) {
uint next = i - 1;
uint nextPeriodStartingDebtIndex = _recentFeePeriodsStorage(next).startingDebtIndex;
// We can skip the period, as no debt minted during period (next period's startingDebtIndex is still 0)
if (nextPeriodStartingDebtIndex > 0 && lastFeeWithdrawal < _recentFeePeriodsStorage(i).feePeriodId) {
// We calculate a feePeriod's closingDebtIndex by looking at the next feePeriod's startingDebtIndex
// we can use the most recent issuanceData[0] for the current feePeriod
// else find the applicableIssuanceData for the feePeriod based on the StartingDebtIndex of the period
uint closingDebtIndex = uint256(nextPeriodStartingDebtIndex).sub(1);
// Gas optimisation - to reuse debtEntryIndex if found new applicable one
// if applicable is 0,0 (none found) we keep most recent one from issuanceData[0]
// return if userOwnershipPercentage = 0)
(userOwnershipPercentage, debtEntryIndex) = _feePoolState.applicableIssuanceData(account, closingDebtIndex);
(feesFromPeriod, rewardsFromPeriod) = _feesAndRewardsFromPeriod(i, userOwnershipPercentage, debtEntryIndex);
results[i][0] = feesFromPeriod;
results[i][1] = rewardsFromPeriod;
}
}
}
/**
* @notice ownershipPercentage is a high precision decimals uint based on
* wallet's debtPercentage. Gives a precise amount of the feesToDistribute
* for fees in the period. Precision factor is removed before results are
* returned.
* @dev The reported fees owing for the current period [0] are just a
* running balance until the fee period closes
*/
function _feesAndRewardsFromPeriod(
uint period,
uint ownershipPercentage,
uint debtEntryIndex
) internal view returns (uint, uint) {
// If it's zero, they haven't issued, and they have no fees OR rewards.
if (ownershipPercentage == 0) return (0, 0);
uint debtOwnershipForPeriod = ownershipPercentage;
// If period has closed we want to calculate debtPercentage for the period
if (period > 0) {
uint closingDebtIndex = uint256(_recentFeePeriodsStorage(period - 1).startingDebtIndex).sub(1);
debtOwnershipForPeriod = _effectiveDebtRatioForPeriod(closingDebtIndex, ownershipPercentage, debtEntryIndex);
}
// Calculate their percentage of the fees / rewards in this period
// This is a high precision integer.
uint feesFromPeriod = _recentFeePeriodsStorage(period).feesToDistribute.multiplyDecimal(debtOwnershipForPeriod);
uint rewardsFromPeriod =
_recentFeePeriodsStorage(period).rewardsToDistribute.multiplyDecimal(debtOwnershipForPeriod);
return (feesFromPeriod.preciseDecimalToDecimal(), rewardsFromPeriod.preciseDecimalToDecimal());
}
function _effectiveDebtRatioForPeriod(
uint closingDebtIndex,
uint ownershipPercentage,
uint debtEntryIndex
) internal view returns (uint) {
// Figure out their global debt percentage delta at end of fee Period.
// This is a high precision integer.
ISynthetixState _synthetixState = synthetixState();
uint feePeriodDebtOwnership =
_synthetixState
.debtLedger(closingDebtIndex)
.divideDecimalRoundPrecise(_synthetixState.debtLedger(debtEntryIndex))
.multiplyDecimalRoundPrecise(ownershipPercentage);
return feePeriodDebtOwnership;
}
function effectiveDebtRatioForPeriod(address account, uint period) external view returns (uint) {
require(period != 0, "Current period is not closed yet");
require(period < FEE_PERIOD_LENGTH, "Exceeds the FEE_PERIOD_LENGTH");
// If the period being checked is uninitialised then return 0. This is only at the start of the system.
if (_recentFeePeriodsStorage(period - 1).startingDebtIndex == 0) return 0;
uint closingDebtIndex = uint256(_recentFeePeriodsStorage(period - 1).startingDebtIndex).sub(1);
uint ownershipPercentage;
uint debtEntryIndex;
(ownershipPercentage, debtEntryIndex) = feePoolState().applicableIssuanceData(account, closingDebtIndex);
// internal function will check closingDebtIndex has corresponding debtLedger entry
return _effectiveDebtRatioForPeriod(closingDebtIndex, ownershipPercentage, debtEntryIndex);
}
/**
* @notice Get the feePeriodID of the last claim this account made
* @param _claimingAddress account to check the last fee period ID claim for
* @return uint of the feePeriodID this account last claimed
*/
function getLastFeeWithdrawal(address _claimingAddress) public view returns (uint) {
return feePoolEternalStorage().getUIntValue(keccak256(abi.encodePacked(LAST_FEE_WITHDRAWAL, _claimingAddress)));
}
/**
* @notice Calculate the collateral ratio before user is blocked from claiming.
*/
function getPenaltyThresholdRatio() public view returns (uint) {
return getIssuanceRatio().multiplyDecimal(SafeDecimalMath.unit().add(getTargetThreshold()));
}
/**
* @notice Set the feePeriodID of the last claim this account made
* @param _claimingAddress account to set the last feePeriodID claim for
* @param _feePeriodID the feePeriodID this account claimed fees for
*/
function _setLastFeeWithdrawal(address _claimingAddress, uint _feePeriodID) internal {
feePoolEternalStorage().setUIntValue(
keccak256(abi.encodePacked(LAST_FEE_WITHDRAWAL, _claimingAddress)),
_feePeriodID
);
}
/* ========== Modifiers ========== */
modifier onlyInternalContracts {
bool isExchanger = msg.sender == address(exchanger());
bool isSynth = issuer().synthsByAddress(msg.sender) != bytes32(0);
bool isCollateral = collateralManager().hasCollateral(msg.sender);
bool isEtherWrapper = msg.sender == address(etherWrapper());
require(isExchanger || isSynth || isCollateral || isEtherWrapper, "Only Internal Contracts");
_;
}
modifier onlyIssuerAndSynthetixState {
bool isIssuer = msg.sender == address(issuer());
bool isSynthetixState = msg.sender == address(synthetixState());
require(isIssuer || isSynthetixState, "Issuer and SynthetixState only");
_;
}
modifier notFeeAddress(address account) {
require(account != FEE_ADDRESS, "Fee address not allowed");
_;
}
modifier issuanceActive() {
systemStatus().requireIssuanceActive();
_;
}
/* ========== Proxy Events ========== */
event IssuanceDebtRatioEntry(
address indexed account,
uint debtRatio,
uint debtEntryIndex,
uint feePeriodStartingDebtIndex
);
bytes32 private constant ISSUANCEDEBTRATIOENTRY_SIG =
keccak256("IssuanceDebtRatioEntry(address,uint256,uint256,uint256)");
function emitIssuanceDebtRatioEntry(
address account,
uint debtRatio,
uint debtEntryIndex,
uint feePeriodStartingDebtIndex
) internal {
proxy._emit(
abi.encode(debtRatio, debtEntryIndex, feePeriodStartingDebtIndex),
2,
ISSUANCEDEBTRATIOENTRY_SIG,
bytes32(uint256(uint160(account))),
0,
0
);
}
event FeePeriodClosed(uint feePeriodId);
bytes32 private constant FEEPERIODCLOSED_SIG = keccak256("FeePeriodClosed(uint256)");
function emitFeePeriodClosed(uint feePeriodId) internal {
proxy._emit(abi.encode(feePeriodId), 1, FEEPERIODCLOSED_SIG, 0, 0, 0);
}
event FeesClaimed(address account, uint sUSDAmount, uint snxRewards);
bytes32 private constant FEESCLAIMED_SIG = keccak256("FeesClaimed(address,uint256,uint256)");
function emitFeesClaimed(
address account,
uint sUSDAmount,
uint snxRewards
) internal {
proxy._emit(abi.encode(account, sUSDAmount, snxRewards), 1, FEESCLAIMED_SIG, 0, 0, 0);
}
}
// Inheritance
// https://docs.synthetix.io/contracts/source/contracts/tokenstate
contract TokenState is Owned, State {
/* ERC20 fields. */
mapping(address => uint) public balanceOf;
mapping(address => mapping(address => uint)) public allowance;
constructor(address _owner, address _associatedContract) public Owned(_owner) State(_associatedContract) {}
/* ========== SETTERS ========== */
/**
* @notice Set ERC20 allowance.
* @dev Only the associated contract may call this.
* @param tokenOwner The authorising party.
* @param spender The authorised party.
* @param value The total value the authorised party may spend on the
* authorising party's behalf.
*/
function setAllowance(
address tokenOwner,
address spender,
uint value
) external onlyAssociatedContract {
allowance[tokenOwner][spender] = value;
}
/**
* @notice Set the balance in a given account
* @dev Only the associated contract may call this.
* @param account The account whose value to set.
* @param value The new balance of the given account.
*/
function setBalanceOf(address account, uint value) external onlyAssociatedContract {
balanceOf[account] = value;
}
}
// Inheritance
// Libraries
// Internal references
// https://docs.synthetix.io/contracts/source/contracts/externstatetoken
contract ExternStateToken is Owned, Proxyable {
using SafeMath for uint;
using SafeDecimalMath for uint;
/* ========== STATE VARIABLES ========== */
/* Stores balances and allowances. */
TokenState public tokenState;
/* Other ERC20 fields. */
string public name;
string public symbol;
uint public totalSupply;
uint8 public decimals;
constructor(
address payable _proxy,
TokenState _tokenState,
string memory _name,
string memory _symbol,
uint _totalSupply,
uint8 _decimals,
address _owner
) public Owned(_owner) Proxyable(_proxy) {
tokenState = _tokenState;
name = _name;
symbol = _symbol;
totalSupply = _totalSupply;
decimals = _decimals;
}
/* ========== VIEWS ========== */
/**
* @notice Returns the ERC20 allowance of one party to spend on behalf of another.
* @param owner The party authorising spending of their funds.
* @param spender The party spending tokenOwner's funds.
*/
function allowance(address owner, address spender) public view returns (uint) {
return tokenState.allowance(owner, spender);
}
/**
* @notice Returns the ERC20 token balance of a given account.
*/
function balanceOf(address account) external view returns (uint) {
return tokenState.balanceOf(account);
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice Set the address of the TokenState contract.
* @dev This can be used to "pause" transfer functionality, by pointing the tokenState at 0x000..
* as balances would be unreachable.
*/
function setTokenState(TokenState _tokenState) external optionalProxy_onlyOwner {
tokenState = _tokenState;
emitTokenStateUpdated(address(_tokenState));
}
function _internalTransfer(
address from,
address to,
uint value
) internal returns (bool) {
/* Disallow transfers to irretrievable-addresses. */
require(to != address(0) && to != address(this) && to != address(proxy), "Cannot transfer to this address");
// Insufficient balance will be handled by the safe subtraction.
tokenState.setBalanceOf(from, tokenState.balanceOf(from).sub(value));
tokenState.setBalanceOf(to, tokenState.balanceOf(to).add(value));
// Emit a standard ERC20 transfer event
emitTransfer(from, to, value);
return true;
}
/**
* @dev Perform an ERC20 token transfer. Designed to be called by transfer functions possessing
* the onlyProxy or optionalProxy modifiers.
*/
function _transferByProxy(
address from,
address to,
uint value
) internal returns (bool) {
return _internalTransfer(from, to, value);
}
/*
* @dev Perform an ERC20 token transferFrom. Designed to be called by transferFrom functions
* possessing the optionalProxy or optionalProxy modifiers.
*/
function _transferFromByProxy(
address sender,
address from,
address to,
uint value
) internal returns (bool) {
/* Insufficient allowance will be handled by the safe subtraction. */
tokenState.setAllowance(from, sender, tokenState.allowance(from, sender).sub(value));
return _internalTransfer(from, to, value);
}
/**
* @notice Approves spender to transfer on the message sender's behalf.
*/
function approve(address spender, uint value) public optionalProxy returns (bool) {
address sender = messageSender;
tokenState.setAllowance(sender, spender, value);
emitApproval(sender, spender, value);
return true;
}
/* ========== EVENTS ========== */
function addressToBytes32(address input) internal pure returns (bytes32) {
return bytes32(uint256(uint160(input)));
}
event Transfer(address indexed from, address indexed to, uint value);
bytes32 internal constant TRANSFER_SIG = keccak256("Transfer(address,address,uint256)");
function emitTransfer(
address from,
address to,
uint value
) internal {
proxy._emit(abi.encode(value), 3, TRANSFER_SIG, addressToBytes32(from), addressToBytes32(to), 0);
}
event Approval(address indexed owner, address indexed spender, uint value);
bytes32 internal constant APPROVAL_SIG = keccak256("Approval(address,address,uint256)");
function emitApproval(
address owner,
address spender,
uint value
) internal {
proxy._emit(abi.encode(value), 3, APPROVAL_SIG, addressToBytes32(owner), addressToBytes32(spender), 0);
}
event TokenStateUpdated(address newTokenState);
bytes32 internal constant TOKENSTATEUPDATED_SIG = keccak256("TokenStateUpdated(address)");
function emitTokenStateUpdated(address newTokenState) internal {
proxy._emit(abi.encode(newTokenState), 1, TOKENSTATEUPDATED_SIG, 0, 0, 0);
}
}
// Inheritance
// Internal references
// https://docs.synthetix.io/contracts/source/contracts/synth
contract Synth is Owned, IERC20, ExternStateToken, MixinResolver, ISynth {
bytes32 public constant CONTRACT_NAME = "Synth";
/* ========== STATE VARIABLES ========== */
// Currency key which identifies this Synth to the Synthetix system
bytes32 public currencyKey;
uint8 public constant DECIMALS = 18;
// Where fees are pooled in sUSD
address public constant FEE_ADDRESS = 0xfeEFEEfeefEeFeefEEFEEfEeFeefEEFeeFEEFEeF;
/* ========== ADDRESS RESOLVER CONFIGURATION ========== */
bytes32 private constant CONTRACT_SYSTEMSTATUS = "SystemStatus";
bytes32 private constant CONTRACT_EXCHANGER = "Exchanger";
bytes32 private constant CONTRACT_ISSUER = "Issuer";
bytes32 private constant CONTRACT_FEEPOOL = "FeePool";
/* ========== CONSTRUCTOR ========== */
constructor(
address payable _proxy,
TokenState _tokenState,
string memory _tokenName,
string memory _tokenSymbol,
address _owner,
bytes32 _currencyKey,
uint _totalSupply,
address _resolver
)
public
ExternStateToken(_proxy, _tokenState, _tokenName, _tokenSymbol, _totalSupply, DECIMALS, _owner)
MixinResolver(_resolver)
{
require(_proxy != address(0), "_proxy cannot be 0");
require(_owner != address(0), "_owner cannot be 0");
currencyKey = _currencyKey;
}
/* ========== MUTATIVE FUNCTIONS ========== */
function transfer(address to, uint value) public optionalProxy returns (bool) {
_ensureCanTransfer(messageSender, value);
// transfers to FEE_ADDRESS will be exchanged into sUSD and recorded as fee
if (to == FEE_ADDRESS) {
return _transferToFeeAddress(to, value);
}
// transfers to 0x address will be burned
if (to == address(0)) {
return _internalBurn(messageSender, value);
}
return super._internalTransfer(messageSender, to, value);
}
function transferAndSettle(address to, uint value) public optionalProxy returns (bool) {
// Exchanger.settle ensures synth is active
(, , uint numEntriesSettled) = exchanger().settle(messageSender, currencyKey);
// Save gas instead of calling transferableSynths
uint balanceAfter = value;
if (numEntriesSettled > 0) {
balanceAfter = tokenState.balanceOf(messageSender);
}
// Reduce the value to transfer if balance is insufficient after reclaimed
value = value > balanceAfter ? balanceAfter : value;
return super._internalTransfer(messageSender, to, value);
}
function transferFrom(
address from,
address to,
uint value
) public optionalProxy returns (bool) {
_ensureCanTransfer(from, value);
return _internalTransferFrom(from, to, value);
}
function transferFromAndSettle(
address from,
address to,
uint value
) public optionalProxy returns (bool) {
// Exchanger.settle() ensures synth is active
(, , uint numEntriesSettled) = exchanger().settle(from, currencyKey);
// Save gas instead of calling transferableSynths
uint balanceAfter = value;
if (numEntriesSettled > 0) {
balanceAfter = tokenState.balanceOf(from);
}
// Reduce the value to transfer if balance is insufficient after reclaimed
value = value >= balanceAfter ? balanceAfter : value;
return _internalTransferFrom(from, to, value);
}
/**
* @notice _transferToFeeAddress function
* non-sUSD synths are exchanged into sUSD via synthInitiatedExchange
* notify feePool to record amount as fee paid to feePool */
function _transferToFeeAddress(address to, uint value) internal returns (bool) {
uint amountInUSD;
// sUSD can be transferred to FEE_ADDRESS directly
if (currencyKey == "sUSD") {
amountInUSD = value;
super._internalTransfer(messageSender, to, value);
} else {
// else exchange synth into sUSD and send to FEE_ADDRESS
(amountInUSD, ) = exchanger().exchange(
messageSender,
messageSender,
currencyKey,
value,
"sUSD",
FEE_ADDRESS,
false,
address(0),
bytes32(0)
);
}
// Notify feePool to record sUSD to distribute as fees
feePool().recordFeePaid(amountInUSD);
return true;
}
function issue(address account, uint amount) external onlyInternalContracts {
_internalIssue(account, amount);
}
function burn(address account, uint amount) external onlyInternalContracts {
_internalBurn(account, amount);
}
function _internalIssue(address account, uint amount) internal {
tokenState.setBalanceOf(account, tokenState.balanceOf(account).add(amount));
totalSupply = totalSupply.add(amount);
emitTransfer(address(0), account, amount);
emitIssued(account, amount);
}
function _internalBurn(address account, uint amount) internal returns (bool) {
tokenState.setBalanceOf(account, tokenState.balanceOf(account).sub(amount));
totalSupply = totalSupply.sub(amount);
emitTransfer(account, address(0), amount);
emitBurned(account, amount);
return true;
}
// Allow owner to set the total supply on import.
function setTotalSupply(uint amount) external optionalProxy_onlyOwner {
totalSupply = amount;
}
/* ========== VIEWS ========== */
// Note: use public visibility so that it can be invoked in a subclass
function resolverAddressesRequired() public view returns (bytes32[] memory addresses) {
addresses = new bytes32[](4);
addresses[0] = CONTRACT_SYSTEMSTATUS;
addresses[1] = CONTRACT_EXCHANGER;
addresses[2] = CONTRACT_ISSUER;
addresses[3] = CONTRACT_FEEPOOL;
}
function systemStatus() internal view returns (ISystemStatus) {
return ISystemStatus(requireAndGetAddress(CONTRACT_SYSTEMSTATUS));
}
function feePool() internal view returns (IFeePool) {
return IFeePool(requireAndGetAddress(CONTRACT_FEEPOOL));
}
function exchanger() internal view returns (IExchanger) {
return IExchanger(requireAndGetAddress(CONTRACT_EXCHANGER));
}
function issuer() internal view returns (IIssuer) {
return IIssuer(requireAndGetAddress(CONTRACT_ISSUER));
}
function _ensureCanTransfer(address from, uint value) internal view {
require(exchanger().maxSecsLeftInWaitingPeriod(from, currencyKey) == 0, "Cannot transfer during waiting period");
require(transferableSynths(from) >= value, "Insufficient balance after any settlement owing");
systemStatus().requireSynthActive(currencyKey);
}
function transferableSynths(address account) public view returns (uint) {
(uint reclaimAmount, , ) = exchanger().settlementOwing(account, currencyKey);
// Note: ignoring rebate amount here because a settle() is required in order to
// allow the transfer to actually work
uint balance = tokenState.balanceOf(account);
if (reclaimAmount > balance) {
return 0;
} else {
return balance.sub(reclaimAmount);
}
}
/* ========== INTERNAL FUNCTIONS ========== */
function _internalTransferFrom(
address from,
address to,
uint value
) internal returns (bool) {
// Skip allowance update in case of infinite allowance
if (tokenState.allowance(from, messageSender) != uint(-1)) {
// Reduce the allowance by the amount we're transferring.
// The safeSub call will handle an insufficient allowance.
tokenState.setAllowance(from, messageSender, tokenState.allowance(from, messageSender).sub(value));
}
return super._internalTransfer(from, to, value);
}
/* ========== MODIFIERS ========== */
modifier onlyInternalContracts() {
bool isFeePool = msg.sender == address(feePool());
bool isExchanger = msg.sender == address(exchanger());
bool isIssuer = msg.sender == address(issuer());
require(isFeePool || isExchanger || isIssuer, "Only FeePool, Exchanger or Issuer contracts allowed");
_;
}
/* ========== EVENTS ========== */
event Issued(address indexed account, uint value);
bytes32 private constant ISSUED_SIG = keccak256("Issued(address,uint256)");
function emitIssued(address account, uint value) internal {
proxy._emit(abi.encode(value), 2, ISSUED_SIG, addressToBytes32(account), 0, 0);
}
event Burned(address indexed account, uint value);
bytes32 private constant BURNED_SIG = keccak256("Burned(address,uint256)");
function emitBurned(address account, uint value) internal {
proxy._emit(abi.encode(value), 2, BURNED_SIG, addressToBytes32(account), 0, 0);
}
}
// Inheritance
// Internal references
// https://docs.synthetix.io/contracts/source/contracts/multicollateralsynth
contract MultiCollateralSynth is Synth {
bytes32 public constant CONTRACT_NAME = "MultiCollateralSynth";
/* ========== ADDRESS RESOLVER CONFIGURATION ========== */
bytes32 private constant CONTRACT_COLLATERALMANAGER = "CollateralManager";
bytes32 private constant CONTRACT_ETHER_WRAPPER = "EtherWrapper";
/* ========== CONSTRUCTOR ========== */
constructor(
address payable _proxy,
TokenState _tokenState,
string memory _tokenName,
string memory _tokenSymbol,
address _owner,
bytes32 _currencyKey,
uint _totalSupply,
address _resolver
) public Synth(_proxy, _tokenState, _tokenName, _tokenSymbol, _owner, _currencyKey, _totalSupply, _resolver) {}
/* ========== VIEWS ======================= */
function collateralManager() internal view returns (ICollateralManager) {
return ICollateralManager(requireAndGetAddress(CONTRACT_COLLATERALMANAGER));
}
function etherWrapper() internal view returns (IEtherWrapper) {
return IEtherWrapper(requireAndGetAddress(CONTRACT_ETHER_WRAPPER));
}
function resolverAddressesRequired() public view returns (bytes32[] memory addresses) {
bytes32[] memory existingAddresses = Synth.resolverAddressesRequired();
bytes32[] memory newAddresses = new bytes32[](2);
newAddresses[0] = CONTRACT_COLLATERALMANAGER;
newAddresses[1] = CONTRACT_ETHER_WRAPPER;
addresses = combineArrays(existingAddresses, newAddresses);
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice Function that allows multi Collateral to issue a certain number of synths from an account.
* @param account Account to issue synths to
* @param amount Number of synths
*/
function issue(address account, uint amount) external onlyInternalContracts {
super._internalIssue(account, amount);
}
/**
* @notice Function that allows multi Collateral to burn a certain number of synths from an account.
* @param account Account to burn synths from
* @param amount Number of synths
*/
function burn(address account, uint amount) external onlyInternalContracts {
super._internalBurn(account, amount);
}
/* ========== MODIFIERS ========== */
// Contracts directly interacting with multiCollateralSynth to issue and burn
modifier onlyInternalContracts() {
bool isFeePool = msg.sender == address(feePool());
bool isExchanger = msg.sender == address(exchanger());
bool isIssuer = msg.sender == address(issuer());
bool isEtherWrapper = msg.sender == address(etherWrapper());
bool isMultiCollateral = collateralManager().hasCollateral(msg.sender);
require(
isFeePool || isExchanger || isIssuer || isEtherWrapper || isMultiCollateral,
"Only FeePool, Exchanger, Issuer, MultiCollateral contracts allowed"
);
_;
}
}
// https://docs.synthetix.io/contracts/source/interfaces/iexchangerates
interface IExchangeRates {
// Structs
struct RateAndUpdatedTime {
uint216 rate;
uint40 time;
}
struct InversePricing {
uint entryPoint;
uint upperLimit;
uint lowerLimit;
bool frozenAtUpperLimit;
bool frozenAtLowerLimit;
}
// Views
function aggregators(bytes32 currencyKey) external view returns (address);
function aggregatorWarningFlags() external view returns (address);
function anyRateIsInvalid(bytes32[] calldata currencyKeys) external view returns (bool);
function canFreezeRate(bytes32 currencyKey) external view returns (bool);
function currentRoundForRate(bytes32 currencyKey) external view returns (uint);
function currenciesUsingAggregator(address aggregator) external view returns (bytes32[] memory);
function effectiveValue(
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey
) external view returns (uint value);
function effectiveValueAndRates(
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey
)
external
view
returns (
uint value,
uint sourceRate,
uint destinationRate
);
function effectiveValueAtRound(
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey,
uint roundIdForSrc,
uint roundIdForDest
) external view returns (uint value);
function getCurrentRoundId(bytes32 currencyKey) external view returns (uint);
function getLastRoundIdBeforeElapsedSecs(
bytes32 currencyKey,
uint startingRoundId,
uint startingTimestamp,
uint timediff
) external view returns (uint);
function inversePricing(bytes32 currencyKey)
external
view
returns (
uint entryPoint,
uint upperLimit,
uint lowerLimit,
bool frozenAtUpperLimit,
bool frozenAtLowerLimit
);
function lastRateUpdateTimes(bytes32 currencyKey) external view returns (uint256);
function oracle() external view returns (address);
function rateAndTimestampAtRound(bytes32 currencyKey, uint roundId) external view returns (uint rate, uint time);
function rateAndUpdatedTime(bytes32 currencyKey) external view returns (uint rate, uint time);
function rateAndInvalid(bytes32 currencyKey) external view returns (uint rate, bool isInvalid);
function rateForCurrency(bytes32 currencyKey) external view returns (uint);
function rateIsFlagged(bytes32 currencyKey) external view returns (bool);
function rateIsFrozen(bytes32 currencyKey) external view returns (bool);
function rateIsInvalid(bytes32 currencyKey) external view returns (bool);
function rateIsStale(bytes32 currencyKey) external view returns (bool);
function rateStalePeriod() external view returns (uint);
function ratesAndUpdatedTimeForCurrencyLastNRounds(bytes32 currencyKey, uint numRounds)
external
view
returns (uint[] memory rates, uint[] memory times);
function ratesAndInvalidForCurrencies(bytes32[] calldata currencyKeys)
external
view
returns (uint[] memory rates, bool anyRateInvalid);
function ratesForCurrencies(bytes32[] calldata currencyKeys) external view returns (uint[] memory);
// Mutative functions
function freezeRate(bytes32 currencyKey) external;
}
// https://docs.synthetix.io/contracts/source/interfaces/ihasbalance
interface IHasBalance {
// Views
function balanceOf(address account) external view returns (uint);
}
// https://docs.synthetix.io/contracts/source/interfaces/iliquidations
interface ILiquidations {
// Views
function isOpenForLiquidation(address account) external view returns (bool);
function getLiquidationDeadlineForAccount(address account) external view returns (uint);
function isLiquidationDeadlinePassed(address account) external view returns (bool);
function liquidationDelay() external view returns (uint);
function liquidationRatio() external view returns (uint);
function liquidationPenalty() external view returns (uint);
function calculateAmountToFixCollateral(uint debtBalance, uint collateral) external view returns (uint);
// Mutative Functions
function flagAccountForLiquidation(address account) external;
// Restricted: used internally to Synthetix
function removeAccountInLiquidation(address account) external;
function checkAndRemoveAccountInLiquidation(address account) external;
}
interface ISynthRedeemer {
// Rate of redemption - 0 for none
function redemptions(address synthProxy) external view returns (uint redeemRate);
// sUSD balance of deprecated token holder
function balanceOf(IERC20 synthProxy, address account) external view returns (uint balanceOfInsUSD);
// Full sUSD supply of token
function totalSupply(IERC20 synthProxy) external view returns (uint totalSupplyInsUSD);
function redeem(IERC20 synthProxy) external;
function redeemAll(IERC20[] calldata synthProxies) external;
function redeemPartial(IERC20 synthProxy, uint amountOfSynth) external;
// Restricted to Issuer
function deprecate(IERC20 synthProxy, uint rateToRedeem) external;
}
// Inheritance
// Libraries
// Internal references
interface IProxy {
function target() external view returns (address);
}
interface IIssuerInternalDebtCache {
function updateCachedSynthDebtWithRate(bytes32 currencyKey, uint currencyRate) external;
function updateCachedSynthDebtsWithRates(bytes32[] calldata currencyKeys, uint[] calldata currencyRates) external;
function updateDebtCacheValidity(bool currentlyInvalid) external;
function totalNonSnxBackedDebt() external view returns (uint excludedDebt, bool isInvalid);
function cacheInfo()
external
view
returns (
uint cachedDebt,
uint timestamp,
bool isInvalid,
bool isStale
);
}
// https://docs.synthetix.io/contracts/source/contracts/issuer
contract Issuer is Owned, MixinSystemSettings, IIssuer {
using SafeMath for uint;
using SafeDecimalMath for uint;
bytes32 public constant CONTRACT_NAME = "Issuer";
// Available Synths which can be used with the system
ISynth[] public availableSynths;
mapping(bytes32 => ISynth) public synths;
mapping(address => bytes32) public synthsByAddress;
/* ========== ENCODED NAMES ========== */
bytes32 internal constant sUSD = "sUSD";
bytes32 internal constant sETH = "sETH";
bytes32 internal constant SNX = "SNX";
// Flexible storage names
bytes32 internal constant LAST_ISSUE_EVENT = "lastIssueEvent";
/* ========== ADDRESS RESOLVER CONFIGURATION ========== */
bytes32 private constant CONTRACT_SYNTHETIX = "Synthetix";
bytes32 private constant CONTRACT_EXCHANGER = "Exchanger";
bytes32 private constant CONTRACT_EXRATES = "ExchangeRates";
bytes32 private constant CONTRACT_SYNTHETIXSTATE = "SynthetixState";
bytes32 private constant CONTRACT_FEEPOOL = "FeePool";
bytes32 private constant CONTRACT_DELEGATEAPPROVALS = "DelegateApprovals";
bytes32 private constant CONTRACT_COLLATERALMANAGER = "CollateralManager";
bytes32 private constant CONTRACT_REWARDESCROW_V2 = "RewardEscrowV2";
bytes32 private constant CONTRACT_SYNTHETIXESCROW = "SynthetixEscrow";
bytes32 private constant CONTRACT_LIQUIDATIONS = "Liquidations";
bytes32 private constant CONTRACT_DEBTCACHE = "DebtCache";
bytes32 private constant CONTRACT_SYNTHREDEEMER = "SynthRedeemer";
constructor(address _owner, address _resolver) public Owned(_owner) MixinSystemSettings(_resolver) {}
/* ========== VIEWS ========== */
function resolverAddressesRequired() public view returns (bytes32[] memory addresses) {
bytes32[] memory existingAddresses = MixinSystemSettings.resolverAddressesRequired();
bytes32[] memory newAddresses = new bytes32[](12);
newAddresses[0] = CONTRACT_SYNTHETIX;
newAddresses[1] = CONTRACT_EXCHANGER;
newAddresses[2] = CONTRACT_EXRATES;
newAddresses[3] = CONTRACT_SYNTHETIXSTATE;
newAddresses[4] = CONTRACT_FEEPOOL;
newAddresses[5] = CONTRACT_DELEGATEAPPROVALS;
newAddresses[6] = CONTRACT_REWARDESCROW_V2;
newAddresses[7] = CONTRACT_SYNTHETIXESCROW;
newAddresses[8] = CONTRACT_LIQUIDATIONS;
newAddresses[9] = CONTRACT_DEBTCACHE;
newAddresses[10] = CONTRACT_COLLATERALMANAGER;
newAddresses[11] = CONTRACT_SYNTHREDEEMER;
return combineArrays(existingAddresses, newAddresses);
}
function synthetix() internal view returns (ISynthetix) {
return ISynthetix(requireAndGetAddress(CONTRACT_SYNTHETIX));
}
function exchanger() internal view returns (IExchanger) {
return IExchanger(requireAndGetAddress(CONTRACT_EXCHANGER));
}
function exchangeRates() internal view returns (IExchangeRates) {
return IExchangeRates(requireAndGetAddress(CONTRACT_EXRATES));
}
function synthetixState() internal view returns (ISynthetixState) {
return ISynthetixState(requireAndGetAddress(CONTRACT_SYNTHETIXSTATE));
}
function feePool() internal view returns (IFeePool) {
return IFeePool(requireAndGetAddress(CONTRACT_FEEPOOL));
}
function liquidations() internal view returns (ILiquidations) {
return ILiquidations(requireAndGetAddress(CONTRACT_LIQUIDATIONS));
}
function delegateApprovals() internal view returns (IDelegateApprovals) {
return IDelegateApprovals(requireAndGetAddress(CONTRACT_DELEGATEAPPROVALS));
}
function collateralManager() internal view returns (ICollateralManager) {
return ICollateralManager(requireAndGetAddress(CONTRACT_COLLATERALMANAGER));
}
function rewardEscrowV2() internal view returns (IRewardEscrowV2) {
return IRewardEscrowV2(requireAndGetAddress(CONTRACT_REWARDESCROW_V2));
}
function synthetixEscrow() internal view returns (IHasBalance) {
return IHasBalance(requireAndGetAddress(CONTRACT_SYNTHETIXESCROW));
}
function debtCache() internal view returns (IIssuerInternalDebtCache) {
return IIssuerInternalDebtCache(requireAndGetAddress(CONTRACT_DEBTCACHE));
}
function synthRedeemer() internal view returns (ISynthRedeemer) {
return ISynthRedeemer(requireAndGetAddress(CONTRACT_SYNTHREDEEMER));
}
function issuanceRatio() external view returns (uint) {
return getIssuanceRatio();
}
function _availableCurrencyKeysWithOptionalSNX(bool withSNX) internal view returns (bytes32[] memory) {
bytes32[] memory currencyKeys = new bytes32[](availableSynths.length + (withSNX ? 1 : 0));
for (uint i = 0; i < availableSynths.length; i++) {
currencyKeys[i] = synthsByAddress[address(availableSynths[i])];
}
if (withSNX) {
currencyKeys[availableSynths.length] = SNX;
}
return currencyKeys;
}
// Returns the total value of the debt pool in currency specified by `currencyKey`.
// To return only the SNX-backed debt, set `excludeCollateral` to true.
function _totalIssuedSynths(bytes32 currencyKey, bool excludeCollateral)
internal
view
returns (uint totalIssued, bool anyRateIsInvalid)
{
(uint debt, , bool cacheIsInvalid, bool cacheIsStale) = debtCache().cacheInfo();
anyRateIsInvalid = cacheIsInvalid || cacheIsStale;
IExchangeRates exRates = exchangeRates();
// Add total issued synths from non snx collateral back into the total if not excluded
if (!excludeCollateral) {
(uint nonSnxDebt, bool invalid) = debtCache().totalNonSnxBackedDebt();
debt = debt.add(nonSnxDebt);
anyRateIsInvalid = anyRateIsInvalid || invalid;
}
if (currencyKey == sUSD) {
return (debt, anyRateIsInvalid);
}
(uint currencyRate, bool currencyRateInvalid) = exRates.rateAndInvalid(currencyKey);
return (debt.divideDecimalRound(currencyRate), anyRateIsInvalid || currencyRateInvalid);
}
function _debtBalanceOfAndTotalDebt(address _issuer, bytes32 currencyKey)
internal
view
returns (
uint debtBalance,
uint totalSystemValue,
bool anyRateIsInvalid
)
{
ISynthetixState state = synthetixState();
// What was their initial debt ownership?
(uint initialDebtOwnership, uint debtEntryIndex) = state.issuanceData(_issuer);
// What's the total value of the system excluding ETH backed synths in their requested currency?
(totalSystemValue, anyRateIsInvalid) = _totalIssuedSynths(currencyKey, true);
// If it's zero, they haven't issued, and they have no debt.
// Note: it's more gas intensive to put this check here rather than before _totalIssuedSynths
// if they have 0 SNX, but it's a necessary trade-off
if (initialDebtOwnership == 0) return (0, totalSystemValue, anyRateIsInvalid);
// Figure out the global debt percentage delta from when they entered the system.
// This is a high precision integer of 27 (1e27) decimals.
uint currentDebtOwnership =
state
.lastDebtLedgerEntry()
.divideDecimalRoundPrecise(state.debtLedger(debtEntryIndex))
.multiplyDecimalRoundPrecise(initialDebtOwnership);
// Their debt balance is their portion of the total system value.
uint highPrecisionBalance =
totalSystemValue.decimalToPreciseDecimal().multiplyDecimalRoundPrecise(currentDebtOwnership);
// Convert back into 18 decimals (1e18)
debtBalance = highPrecisionBalance.preciseDecimalToDecimal();
}
function _canBurnSynths(address account) internal view returns (bool) {
return now >= _lastIssueEvent(account).add(getMinimumStakeTime());
}
function _lastIssueEvent(address account) internal view returns (uint) {
// Get the timestamp of the last issue this account made
return flexibleStorage().getUIntValue(CONTRACT_NAME, keccak256(abi.encodePacked(LAST_ISSUE_EVENT, account)));
}
function _remainingIssuableSynths(address _issuer)
internal
view
returns (
uint maxIssuable,
uint alreadyIssued,
uint totalSystemDebt,
bool anyRateIsInvalid
)
{
(alreadyIssued, totalSystemDebt, anyRateIsInvalid) = _debtBalanceOfAndTotalDebt(_issuer, sUSD);
(uint issuable, bool isInvalid) = _maxIssuableSynths(_issuer);
maxIssuable = issuable;
anyRateIsInvalid = anyRateIsInvalid || isInvalid;
if (alreadyIssued >= maxIssuable) {
maxIssuable = 0;
} else {
maxIssuable = maxIssuable.sub(alreadyIssued);
}
}
function _snxToUSD(uint amount, uint snxRate) internal pure returns (uint) {
return amount.multiplyDecimalRound(snxRate);
}
function _usdToSnx(uint amount, uint snxRate) internal pure returns (uint) {
return amount.divideDecimalRound(snxRate);
}
function _maxIssuableSynths(address _issuer) internal view returns (uint, bool) {
// What is the value of their SNX balance in sUSD
(uint snxRate, bool isInvalid) = exchangeRates().rateAndInvalid(SNX);
uint destinationValue = _snxToUSD(_collateral(_issuer), snxRate);
// They're allowed to issue up to issuanceRatio of that value
return (destinationValue.multiplyDecimal(getIssuanceRatio()), isInvalid);
}
function _collateralisationRatio(address _issuer) internal view returns (uint, bool) {
uint totalOwnedSynthetix = _collateral(_issuer);
(uint debtBalance, , bool anyRateIsInvalid) = _debtBalanceOfAndTotalDebt(_issuer, SNX);
// it's more gas intensive to put this check here if they have 0 SNX, but it complies with the interface
if (totalOwnedSynthetix == 0) return (0, anyRateIsInvalid);
return (debtBalance.divideDecimalRound(totalOwnedSynthetix), anyRateIsInvalid);
}
function _collateral(address account) internal view returns (uint) {
uint balance = IERC20(address(synthetix())).balanceOf(account);
if (address(synthetixEscrow()) != address(0)) {
balance = balance.add(synthetixEscrow().balanceOf(account));
}
if (address(rewardEscrowV2()) != address(0)) {
balance = balance.add(rewardEscrowV2().balanceOf(account));
}
return balance;
}
function minimumStakeTime() external view returns (uint) {
return getMinimumStakeTime();
}
function canBurnSynths(address account) external view returns (bool) {
return _canBurnSynths(account);
}
function availableCurrencyKeys() external view returns (bytes32[] memory) {
return _availableCurrencyKeysWithOptionalSNX(false);
}
function availableSynthCount() external view returns (uint) {
return availableSynths.length;
}
function anySynthOrSNXRateIsInvalid() external view returns (bool anyRateInvalid) {
(, anyRateInvalid) = exchangeRates().ratesAndInvalidForCurrencies(_availableCurrencyKeysWithOptionalSNX(true));
}
function totalIssuedSynths(bytes32 currencyKey, bool excludeOtherCollateral) external view returns (uint totalIssued) {
(totalIssued, ) = _totalIssuedSynths(currencyKey, excludeOtherCollateral);
}
function lastIssueEvent(address account) external view returns (uint) {
return _lastIssueEvent(account);
}
function collateralisationRatio(address _issuer) external view returns (uint cratio) {
(cratio, ) = _collateralisationRatio(_issuer);
}
function collateralisationRatioAndAnyRatesInvalid(address _issuer)
external
view
returns (uint cratio, bool anyRateIsInvalid)
{
return _collateralisationRatio(_issuer);
}
function collateral(address account) external view returns (uint) {
return _collateral(account);
}
function debtBalanceOf(address _issuer, bytes32 currencyKey) external view returns (uint debtBalance) {
ISynthetixState state = synthetixState();
// What was their initial debt ownership?
(uint initialDebtOwnership, ) = state.issuanceData(_issuer);
// If it's zero, they haven't issued, and they have no debt.
if (initialDebtOwnership == 0) return 0;
(debtBalance, , ) = _debtBalanceOfAndTotalDebt(_issuer, currencyKey);
}
function remainingIssuableSynths(address _issuer)
external
view
returns (
uint maxIssuable,
uint alreadyIssued,
uint totalSystemDebt
)
{
(maxIssuable, alreadyIssued, totalSystemDebt, ) = _remainingIssuableSynths(_issuer);
}
function maxIssuableSynths(address _issuer) external view returns (uint) {
(uint maxIssuable, ) = _maxIssuableSynths(_issuer);
return maxIssuable;
}
function transferableSynthetixAndAnyRateIsInvalid(address account, uint balance)
external
view
returns (uint transferable, bool anyRateIsInvalid)
{
// How many SNX do they have, excluding escrow?
// Note: We're excluding escrow here because we're interested in their transferable amount
// and escrowed SNX are not transferable.
// How many of those will be locked by the amount they've issued?
// Assuming issuance ratio is 20%, then issuing 20 SNX of value would require
// 100 SNX to be locked in their wallet to maintain their collateralisation ratio
// The locked synthetix value can exceed their balance.
uint debtBalance;
(debtBalance, , anyRateIsInvalid) = _debtBalanceOfAndTotalDebt(account, SNX);
uint lockedSynthetixValue = debtBalance.divideDecimalRound(getIssuanceRatio());
// If we exceed the balance, no SNX are transferable, otherwise the difference is.
if (lockedSynthetixValue >= balance) {
transferable = 0;
} else {
transferable = balance.sub(lockedSynthetixValue);
}
}
function getSynths(bytes32[] calldata currencyKeys) external view returns (ISynth[] memory) {
uint numKeys = currencyKeys.length;
ISynth[] memory addresses = new ISynth[](numKeys);
for (uint i = 0; i < numKeys; i++) {
addresses[i] = synths[currencyKeys[i]];
}
return addresses;
}
/* ========== MUTATIVE FUNCTIONS ========== */
function _addSynth(ISynth synth) internal {
bytes32 currencyKey = synth.currencyKey();
require(synths[currencyKey] == ISynth(0), "Synth exists");
require(synthsByAddress[address(synth)] == bytes32(0), "Synth address already exists");
availableSynths.push(synth);
synths[currencyKey] = synth;
synthsByAddress[address(synth)] = currencyKey;
emit SynthAdded(currencyKey, address(synth));
}
function addSynth(ISynth synth) external onlyOwner {
_addSynth(synth);
// Invalidate the cache to force a snapshot to be recomputed. If a synth were to be added
// back to the system and it still somehow had cached debt, this would force the value to be
// updated.
debtCache().updateDebtCacheValidity(true);
}
function addSynths(ISynth[] calldata synthsToAdd) external onlyOwner {
uint numSynths = synthsToAdd.length;
for (uint i = 0; i < numSynths; i++) {
_addSynth(synthsToAdd[i]);
}
// Invalidate the cache to force a snapshot to be recomputed.
debtCache().updateDebtCacheValidity(true);
}
function _removeSynth(bytes32 currencyKey) internal {
address synthToRemove = address(synths[currencyKey]);
require(synthToRemove != address(0), "Synth does not exist");
require(currencyKey != sUSD, "Cannot remove synth");
uint synthSupply = IERC20(synthToRemove).totalSupply();
if (synthSupply > 0) {
(uint amountOfsUSD, uint rateToRedeem, ) =
exchangeRates().effectiveValueAndRates(currencyKey, synthSupply, "sUSD");
require(rateToRedeem > 0, "Cannot remove synth to redeem without rate");
ISynthRedeemer _synthRedeemer = synthRedeemer();
synths[sUSD].issue(address(_synthRedeemer), amountOfsUSD);
// ensure the debt cache is aware of the new sUSD issued
debtCache().updateCachedSynthDebtWithRate(sUSD, SafeDecimalMath.unit());
_synthRedeemer.deprecate(IERC20(address(Proxyable(address(synthToRemove)).proxy())), rateToRedeem);
}
// Remove the synth from the availableSynths array.
for (uint i = 0; i < availableSynths.length; i++) {
if (address(availableSynths[i]) == synthToRemove) {
delete availableSynths[i];
// Copy the last synth into the place of the one we just deleted
// If there's only one synth, this is synths[0] = synths[0].
// If we're deleting the last one, it's also a NOOP in the same way.
availableSynths[i] = availableSynths[availableSynths.length - 1];
// Decrease the size of the array by one.
availableSynths.length--;
break;
}
}
// And remove it from the synths mapping
delete synthsByAddress[synthToRemove];
delete synths[currencyKey];
emit SynthRemoved(currencyKey, synthToRemove);
}
function removeSynth(bytes32 currencyKey) external onlyOwner {
// Remove its contribution from the debt pool snapshot, and
// invalidate the cache to force a new snapshot.
IIssuerInternalDebtCache cache = debtCache();
cache.updateCachedSynthDebtWithRate(currencyKey, 0);
cache.updateDebtCacheValidity(true);
_removeSynth(currencyKey);
}
function removeSynths(bytes32[] calldata currencyKeys) external onlyOwner {
uint numKeys = currencyKeys.length;
// Remove their contributions from the debt pool snapshot, and
// invalidate the cache to force a new snapshot.
IIssuerInternalDebtCache cache = debtCache();
uint[] memory zeroRates = new uint[](numKeys);
cache.updateCachedSynthDebtsWithRates(currencyKeys, zeroRates);
cache.updateDebtCacheValidity(true);
for (uint i = 0; i < numKeys; i++) {
_removeSynth(currencyKeys[i]);
}
}
function issueSynths(address from, uint amount) external onlySynthetix {
_issueSynths(from, amount, false);
}
function issueMaxSynths(address from) external onlySynthetix {
_issueSynths(from, 0, true);
}
function issueSynthsOnBehalf(
address issueForAddress,
address from,
uint amount
) external onlySynthetix {
_requireCanIssueOnBehalf(issueForAddress, from);
_issueSynths(issueForAddress, amount, false);
}
function issueMaxSynthsOnBehalf(address issueForAddress, address from) external onlySynthetix {
_requireCanIssueOnBehalf(issueForAddress, from);
_issueSynths(issueForAddress, 0, true);
}
function burnSynths(address from, uint amount) external onlySynthetix {
_voluntaryBurnSynths(from, amount, false);
}
function burnSynthsOnBehalf(
address burnForAddress,
address from,
uint amount
) external onlySynthetix {
_requireCanBurnOnBehalf(burnForAddress, from);
_voluntaryBurnSynths(burnForAddress, amount, false);
}
function burnSynthsToTarget(address from) external onlySynthetix {
_voluntaryBurnSynths(from, 0, true);
}
function burnSynthsToTargetOnBehalf(address burnForAddress, address from) external onlySynthetix {
_requireCanBurnOnBehalf(burnForAddress, from);
_voluntaryBurnSynths(burnForAddress, 0, true);
}
function burnForRedemption(
address deprecatedSynthProxy,
address account,
uint balance
) external onlySynthRedeemer {
ISynth(IProxy(deprecatedSynthProxy).target()).burn(account, balance);
}
function liquidateDelinquentAccount(
address account,
uint susdAmount,
address liquidator
) external onlySynthetix returns (uint totalRedeemed, uint amountToLiquidate) {
// Ensure waitingPeriod and sUSD balance is settled as burning impacts the size of debt pool
require(!exchanger().hasWaitingPeriodOrSettlementOwing(liquidator, sUSD), "sUSD needs to be settled");
// Check account is liquidation open
require(liquidations().isOpenForLiquidation(account), "Account not open for liquidation");
// require liquidator has enough sUSD
require(IERC20(address(synths[sUSD])).balanceOf(liquidator) >= susdAmount, "Not enough sUSD");
uint liquidationPenalty = liquidations().liquidationPenalty();
// What is their debt in sUSD?
(uint debtBalance, uint totalDebtIssued, bool anyRateIsInvalid) = _debtBalanceOfAndTotalDebt(account, sUSD);
(uint snxRate, bool snxRateInvalid) = exchangeRates().rateAndInvalid(SNX);
_requireRatesNotInvalid(anyRateIsInvalid || snxRateInvalid);
uint collateralForAccount = _collateral(account);
uint amountToFixRatio =
liquidations().calculateAmountToFixCollateral(debtBalance, _snxToUSD(collateralForAccount, snxRate));
// Cap amount to liquidate to repair collateral ratio based on issuance ratio
amountToLiquidate = amountToFixRatio < susdAmount ? amountToFixRatio : susdAmount;
// what's the equivalent amount of snx for the amountToLiquidate?
uint snxRedeemed = _usdToSnx(amountToLiquidate, snxRate);
// Add penalty
totalRedeemed = snxRedeemed.multiplyDecimal(SafeDecimalMath.unit().add(liquidationPenalty));
// if total SNX to redeem is greater than account's collateral
// account is under collateralised, liquidate all collateral and reduce sUSD to burn
if (totalRedeemed > collateralForAccount) {
// set totalRedeemed to all transferable collateral
totalRedeemed = collateralForAccount;
// whats the equivalent sUSD to burn for all collateral less penalty
amountToLiquidate = _snxToUSD(
collateralForAccount.divideDecimal(SafeDecimalMath.unit().add(liquidationPenalty)),
snxRate
);
}
// burn sUSD from messageSender (liquidator) and reduce account's debt
_burnSynths(account, liquidator, amountToLiquidate, debtBalance, totalDebtIssued);
// Remove liquidation flag if amount liquidated fixes ratio
if (amountToLiquidate == amountToFixRatio) {
// Remove liquidation
liquidations().removeAccountInLiquidation(account);
}
}
/* ========== INTERNAL FUNCTIONS ========== */
function _requireRatesNotInvalid(bool anyRateIsInvalid) internal pure {
require(!anyRateIsInvalid, "A synth or SNX rate is invalid");
}
function _requireCanIssueOnBehalf(address issueForAddress, address from) internal view {
require(delegateApprovals().canIssueFor(issueForAddress, from), "Not approved to act on behalf");
}
function _requireCanBurnOnBehalf(address burnForAddress, address from) internal view {
require(delegateApprovals().canBurnFor(burnForAddress, from), "Not approved to act on behalf");
}
function _issueSynths(
address from,
uint amount,
bool issueMax
) internal {
(uint maxIssuable, uint existingDebt, uint totalSystemDebt, bool anyRateIsInvalid) = _remainingIssuableSynths(from);
_requireRatesNotInvalid(anyRateIsInvalid);
if (!issueMax) {
require(amount <= maxIssuable, "Amount too large");
} else {
amount = maxIssuable;
}
// Keep track of the debt they're about to create
_addToDebtRegister(from, amount, existingDebt, totalSystemDebt);
// record issue timestamp
_setLastIssueEvent(from);
// Create their synths
synths[sUSD].issue(from, amount);
// Account for the issued debt in the cache
debtCache().updateCachedSynthDebtWithRate(sUSD, SafeDecimalMath.unit());
// Store their locked SNX amount to determine their fee % for the period
_appendAccountIssuanceRecord(from);
}
function _burnSynths(
address debtAccount,
address burnAccount,
uint amount,
uint existingDebt,
uint totalDebtIssued
) internal returns (uint amountBurnt) {
// liquidation requires sUSD to be already settled / not in waiting period
// If they're trying to burn more debt than they actually owe, rather than fail the transaction, let's just
// clear their debt and leave them be.
amountBurnt = existingDebt < amount ? existingDebt : amount;
// Remove liquidated debt from the ledger
_removeFromDebtRegister(debtAccount, amountBurnt, existingDebt, totalDebtIssued);
// synth.burn does a safe subtraction on balance (so it will revert if there are not enough synths).
synths[sUSD].burn(burnAccount, amountBurnt);
// Account for the burnt debt in the cache.
debtCache().updateCachedSynthDebtWithRate(sUSD, SafeDecimalMath.unit());
// Store their debtRatio against a fee period to determine their fee/rewards % for the period
_appendAccountIssuanceRecord(debtAccount);
}
// If burning to target, `amount` is ignored, and the correct quantity of sUSD is burnt to reach the target
// c-ratio, allowing fees to be claimed. In this case, pending settlements will be skipped as the user
// will still have debt remaining after reaching their target.
function _voluntaryBurnSynths(
address from,
uint amount,
bool burnToTarget
) internal {
if (!burnToTarget) {
// If not burning to target, then burning requires that the minimum stake time has elapsed.
require(_canBurnSynths(from), "Minimum stake time not reached");
// First settle anything pending into sUSD as burning or issuing impacts the size of the debt pool
(, uint refunded, uint numEntriesSettled) = exchanger().settle(from, sUSD);
if (numEntriesSettled > 0) {
amount = exchanger().calculateAmountAfterSettlement(from, sUSD, amount, refunded);
}
}
(uint existingDebt, uint totalSystemValue, bool anyRateIsInvalid) = _debtBalanceOfAndTotalDebt(from, sUSD);
(uint maxIssuableSynthsForAccount, bool snxRateInvalid) = _maxIssuableSynths(from);
_requireRatesNotInvalid(anyRateIsInvalid || snxRateInvalid);
require(existingDebt > 0, "No debt to forgive");
if (burnToTarget) {
amount = existingDebt.sub(maxIssuableSynthsForAccount);
}
uint amountBurnt = _burnSynths(from, from, amount, existingDebt, totalSystemValue);
// Check and remove liquidation if existingDebt after burning is <= maxIssuableSynths
// Issuance ratio is fixed so should remove any liquidations
if (existingDebt.sub(amountBurnt) <= maxIssuableSynthsForAccount) {
liquidations().removeAccountInLiquidation(from);
}
}
function _setLastIssueEvent(address account) internal {
// Set the timestamp of the last issueSynths
flexibleStorage().setUIntValue(
CONTRACT_NAME,
keccak256(abi.encodePacked(LAST_ISSUE_EVENT, account)),
block.timestamp
);
}
function _appendAccountIssuanceRecord(address from) internal {
uint initialDebtOwnership;
uint debtEntryIndex;
(initialDebtOwnership, debtEntryIndex) = synthetixState().issuanceData(from);
feePool().appendAccountIssuanceRecord(from, initialDebtOwnership, debtEntryIndex);
}
function _addToDebtRegister(
address from,
uint amount,
uint existingDebt,
uint totalDebtIssued
) internal {
ISynthetixState state = synthetixState();
// What will the new total be including the new value?
uint newTotalDebtIssued = amount.add(totalDebtIssued);
// What is their percentage (as a high precision int) of the total debt?
uint debtPercentage = amount.divideDecimalRoundPrecise(newTotalDebtIssued);
// And what effect does this percentage change have on the global debt holding of other issuers?
// The delta specifically needs to not take into account any existing debt as it's already
// accounted for in the delta from when they issued previously.
// The delta is a high precision integer.
uint delta = SafeDecimalMath.preciseUnit().sub(debtPercentage);
// And what does their debt ownership look like including this previous stake?
if (existingDebt > 0) {
debtPercentage = amount.add(existingDebt).divideDecimalRoundPrecise(newTotalDebtIssued);
} else {
// If they have no debt, they're a new issuer; record this.
state.incrementTotalIssuerCount();
}
// Save the debt entry parameters
state.setCurrentIssuanceData(from, debtPercentage);
// And if we're the first, push 1 as there was no effect to any other holders, otherwise push
// the change for the rest of the debt holders. The debt ledger holds high precision integers.
if (state.debtLedgerLength() > 0) {
state.appendDebtLedgerValue(state.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta));
} else {
state.appendDebtLedgerValue(SafeDecimalMath.preciseUnit());
}
}
function _removeFromDebtRegister(
address from,
uint debtToRemove,
uint existingDebt,
uint totalDebtIssued
) internal {
ISynthetixState state = synthetixState();
// What will the new total after taking out the withdrawn amount
uint newTotalDebtIssued = totalDebtIssued.sub(debtToRemove);
uint delta = 0;
// What will the debt delta be if there is any debt left?
// Set delta to 0 if no more debt left in system after user
if (newTotalDebtIssued > 0) {
// What is the percentage of the withdrawn debt (as a high precision int) of the total debt after?
uint debtPercentage = debtToRemove.divideDecimalRoundPrecise(newTotalDebtIssued);
// And what effect does this percentage change have on the global debt holding of other issuers?
// The delta specifically needs to not take into account any existing debt as it's already
// accounted for in the delta from when they issued previously.
delta = SafeDecimalMath.preciseUnit().add(debtPercentage);
}
// Are they exiting the system, or are they just decreasing their debt position?
if (debtToRemove == existingDebt) {
state.setCurrentIssuanceData(from, 0);
state.decrementTotalIssuerCount();
} else {
// What percentage of the debt will they be left with?
uint newDebt = existingDebt.sub(debtToRemove);
uint newDebtPercentage = newDebt.divideDecimalRoundPrecise(newTotalDebtIssued);
// Store the debt percentage and debt ledger as high precision integers
state.setCurrentIssuanceData(from, newDebtPercentage);
}
// Update our cumulative ledger. This is also a high precision integer.
state.appendDebtLedgerValue(state.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta));
}
/* ========== MODIFIERS ========== */
function _onlySynthetix() internal view {
require(msg.sender == address(synthetix()), "Issuer: Only the synthetix contract can perform this action");
}
modifier onlySynthetix() {
_onlySynthetix(); // Use an internal function to save code size.
_;
}
function _onlySynthRedeemer() internal view {
require(msg.sender == address(synthRedeemer()), "Issuer: Only the SynthRedeemer contract can perform this action");
}
modifier onlySynthRedeemer() {
_onlySynthRedeemer();
_;
}
/* ========== EVENTS ========== */
event SynthAdded(bytes32 currencyKey, address synth);
event SynthRemoved(bytes32 currencyKey, address synth);
}
interface ISynthetixNamedContract {
// solhint-disable func-name-mixedcase
function CONTRACT_NAME() external view returns (bytes32);
}
// solhint-disable contract-name-camelcase
contract Migration_Mirfak is BaseMigration {
// https://etherscan.io/address/0xEb3107117FEAd7de89Cd14D463D340A2E6917769;
address public constant OWNER = 0xEb3107117FEAd7de89Cd14D463D340A2E6917769;
// ----------------------------
// EXISTING SYNTHETIX CONTRACTS
// ----------------------------
// https://etherscan.io/address/0x823bE81bbF96BEc0e25CA13170F5AaCb5B79ba83
AddressResolver public constant addressresolver_i = AddressResolver(0x823bE81bbF96BEc0e25CA13170F5AaCb5B79ba83);
// https://etherscan.io/address/0xb440DD674e1243644791a4AdfE3A2AbB0A92d309
Proxy public constant proxyfeepool_i = Proxy(0xb440DD674e1243644791a4AdfE3A2AbB0A92d309);
// https://etherscan.io/address/0xC9DFff5fA5605fd94F8B7927b892F2B57391e8bB
FeePoolEternalStorage public constant feepooleternalstorage_i =
FeePoolEternalStorage(0xC9DFff5fA5605fd94F8B7927b892F2B57391e8bB);
// https://etherscan.io/address/0x11164F6a47C3f8472D19b9aDd516Fc780cb7Ee02
FeePoolState public constant feepoolstate_i = FeePoolState(0x11164F6a47C3f8472D19b9aDd516Fc780cb7Ee02);
// https://etherscan.io/address/0xC011a73ee8576Fb46F5E1c5751cA3B9Fe0af2a6F
ProxyERC20 public constant proxyerc20_i = ProxyERC20(0xC011a73ee8576Fb46F5E1c5751cA3B9Fe0af2a6F);
// https://etherscan.io/address/0xC011A72400E58ecD99Ee497CF89E3775d4bd732F
Proxy public constant proxysynthetix_i = Proxy(0xC011A72400E58ecD99Ee497CF89E3775d4bd732F);
// https://etherscan.io/address/0x545973f28950f50fc6c7F52AAb4Ad214A27C0564
ExchangeState public constant exchangestate_i = ExchangeState(0x545973f28950f50fc6c7F52AAb4Ad214A27C0564);
// https://etherscan.io/address/0x1c86B3CDF2a60Ae3a574f7f71d44E2C50BDdB87E
SystemStatus public constant systemstatus_i = SystemStatus(0x1c86B3CDF2a60Ae3a574f7f71d44E2C50BDdB87E);
// https://etherscan.io/address/0x5b1b5fEa1b99D83aD479dF0C222F0492385381dD
LegacyTokenState public constant tokenstatesynthetix_i = LegacyTokenState(0x5b1b5fEa1b99D83aD479dF0C222F0492385381dD);
// https://etherscan.io/address/0x4b9Ca5607f1fF8019c1C6A3c2f0CC8de622D5B82
SynthetixState public constant synthetixstate_i = SynthetixState(0x4b9Ca5607f1fF8019c1C6A3c2f0CC8de622D5B82);
// https://etherscan.io/address/0xb671F2210B1F6621A2607EA63E6B2DC3e2464d1F
RewardEscrow public constant rewardescrow_i = RewardEscrow(0xb671F2210B1F6621A2607EA63E6B2DC3e2464d1F);
// https://etherscan.io/address/0x29C295B046a73Cde593f21f63091B072d407e3F2
RewardsDistribution public constant rewardsdistribution_i =
RewardsDistribution(0x29C295B046a73Cde593f21f63091B072d407e3F2);
// https://etherscan.io/address/0x510adfDF6E7554C571b7Cd9305Ce91473610015e
FeePool public constant feepool_i = FeePool(0x510adfDF6E7554C571b7Cd9305Ce91473610015e);
// https://etherscan.io/address/0x967968963517AFDC9b8Ccc9AD6649bC507E83a7b
MultiCollateralSynth public constant synthsusd_i = MultiCollateralSynth(0x967968963517AFDC9b8Ccc9AD6649bC507E83a7b);
// https://etherscan.io/address/0x05a9CBe762B36632b3594DA4F082340E0e5343e8
TokenState public constant tokenstatesusd_i = TokenState(0x05a9CBe762B36632b3594DA4F082340E0e5343e8);
// https://etherscan.io/address/0x57Ab1E02fEE23774580C119740129eAC7081e9D3
Proxy public constant proxysusd_i = Proxy(0x57Ab1E02fEE23774580C119740129eAC7081e9D3);
// https://etherscan.io/address/0x57Ab1ec28D129707052df4dF418D58a2D46d5f51
ProxyERC20 public constant proxyerc20susd_i = ProxyERC20(0x57Ab1ec28D129707052df4dF418D58a2D46d5f51);
// https://etherscan.io/address/0xC8a5f06858a1B49A7F703EacD433A1444a5e5bd9
MultiCollateralSynth public constant synthsbtc_i = MultiCollateralSynth(0xC8a5f06858a1B49A7F703EacD433A1444a5e5bd9);
// https://etherscan.io/address/0x4F6296455F8d754c19821cF1EC8FeBF2cD456E67
TokenState public constant tokenstatesbtc_i = TokenState(0x4F6296455F8d754c19821cF1EC8FeBF2cD456E67);
// https://etherscan.io/address/0xfE18be6b3Bd88A2D2A7f928d00292E7a9963CfC6
ProxyERC20 public constant proxysbtc_i = ProxyERC20(0xfE18be6b3Bd88A2D2A7f928d00292E7a9963CfC6);
// https://etherscan.io/address/0xCFA46B4923c0E75B7b84E9FBde70ED26feFefBf6
MultiCollateralSynth public constant synthseth_i = MultiCollateralSynth(0xCFA46B4923c0E75B7b84E9FBde70ED26feFefBf6);
// https://etherscan.io/address/0x34A5ef81d18F3a305aE9C2d7DF42beef4c79031c
TokenState public constant tokenstateseth_i = TokenState(0x34A5ef81d18F3a305aE9C2d7DF42beef4c79031c);
// https://etherscan.io/address/0x5e74C9036fb86BD7eCdcb084a0673EFc32eA31cb
ProxyERC20 public constant proxyseth_i = ProxyERC20(0x5e74C9036fb86BD7eCdcb084a0673EFc32eA31cb);
// https://etherscan.io/address/0x922C84B3894298296C34842D866BfC0d36C54778
Issuer public constant issuer_i = Issuer(0x922C84B3894298296C34842D866BfC0d36C54778);
// ----------------------------------
// NEW CONTRACTS DEPLOYED TO BE ADDED
// ----------------------------------
// https://etherscan.io/address/0x510adfDF6E7554C571b7Cd9305Ce91473610015e
address public constant new_FeePool_contract = 0x510adfDF6E7554C571b7Cd9305Ce91473610015e;
// https://etherscan.io/address/0x54f25546260C7539088982bcF4b7dC8EDEF19f21
address public constant new_Synthetix_contract = 0x54f25546260C7539088982bcF4b7dC8EDEF19f21;
// https://etherscan.io/address/0x7634F2A1741a683ccda37Dce864c187F990D7B4b
address public constant new_Exchanger_contract = 0x7634F2A1741a683ccda37Dce864c187F990D7B4b;
// https://etherscan.io/address/0xe92B4c7428152052B0930c81F4c687a5F1A12292
address public constant new_DebtCache_contract = 0xe92B4c7428152052B0930c81F4c687a5F1A12292;
// https://etherscan.io/address/0x922C84B3894298296C34842D866BfC0d36C54778
address public constant new_Issuer_contract = 0x922C84B3894298296C34842D866BfC0d36C54778;
// https://etherscan.io/address/0xe533139Af961c9747356D947838c98451015e234
address public constant new_SynthRedeemer_contract = 0xe533139Af961c9747356D947838c98451015e234;
// https://etherscan.io/address/0x967968963517AFDC9b8Ccc9AD6649bC507E83a7b
address public constant new_SynthsUSD_contract = 0x967968963517AFDC9b8Ccc9AD6649bC507E83a7b;
// https://etherscan.io/address/0xC8a5f06858a1B49A7F703EacD433A1444a5e5bd9
address public constant new_SynthsBTC_contract = 0xC8a5f06858a1B49A7F703EacD433A1444a5e5bd9;
// https://etherscan.io/address/0xCFA46B4923c0E75B7b84E9FBde70ED26feFefBf6
address public constant new_SynthsETH_contract = 0xCFA46B4923c0E75B7b84E9FBde70ED26feFefBf6;
constructor() public BaseMigration(OWNER) {}
function contractsRequiringOwnership() public pure returns (address[] memory contracts) {
contracts = new address[](24);
contracts[0] = address(addressresolver_i);
contracts[1] = address(proxyfeepool_i);
contracts[2] = address(feepooleternalstorage_i);
contracts[3] = address(feepoolstate_i);
contracts[4] = address(proxyerc20_i);
contracts[5] = address(proxysynthetix_i);
contracts[6] = address(exchangestate_i);
contracts[7] = address(systemstatus_i);
contracts[8] = address(tokenstatesynthetix_i);
contracts[9] = address(synthetixstate_i);
contracts[10] = address(rewardescrow_i);
contracts[11] = address(rewardsdistribution_i);
contracts[12] = address(feepool_i);
contracts[13] = address(synthsusd_i);
contracts[14] = address(tokenstatesusd_i);
contracts[15] = address(proxysusd_i);
contracts[16] = address(proxyerc20susd_i);
contracts[17] = address(synthsbtc_i);
contracts[18] = address(tokenstatesbtc_i);
contracts[19] = address(proxysbtc_i);
contracts[20] = address(synthseth_i);
contracts[21] = address(tokenstateseth_i);
contracts[22] = address(proxyseth_i);
contracts[23] = address(issuer_i);
}
function migrate(address currentOwner) external onlyDeployer {
require(owner == currentOwner, "Only the assigned owner can be re-assigned when complete");
require(
ISynthetixNamedContract(new_FeePool_contract).CONTRACT_NAME() == "FeePool",
"Invalid contract supplied for FeePool"
);
require(
ISynthetixNamedContract(new_Synthetix_contract).CONTRACT_NAME() == "Synthetix",
"Invalid contract supplied for Synthetix"
);
require(
ISynthetixNamedContract(new_Exchanger_contract).CONTRACT_NAME() == "ExchangerWithVirtualSynth",
"Invalid contract supplied for Exchanger"
);
require(
ISynthetixNamedContract(new_DebtCache_contract).CONTRACT_NAME() == "DebtCache",
"Invalid contract supplied for DebtCache"
);
require(
ISynthetixNamedContract(new_Issuer_contract).CONTRACT_NAME() == "Issuer",
"Invalid contract supplied for Issuer"
);
require(
ISynthetixNamedContract(new_SynthRedeemer_contract).CONTRACT_NAME() == "SynthRedeemer",
"Invalid contract supplied for SynthRedeemer"
);
require(
ISynthetixNamedContract(new_SynthsUSD_contract).CONTRACT_NAME() == "MultiCollateralSynth",
"Invalid contract supplied for SynthsUSD"
);
require(
ISynthetixNamedContract(new_SynthsBTC_contract).CONTRACT_NAME() == "MultiCollateralSynth",
"Invalid contract supplied for SynthsBTC"
);
require(
ISynthetixNamedContract(new_SynthsETH_contract).CONTRACT_NAME() == "MultiCollateralSynth",
"Invalid contract supplied for SynthsETH"
);
// ACCEPT OWNERSHIP for all contracts that require ownership to make changes
acceptAll();
// MIGRATION
// Import all new contracts into the address resolver;
addressresolver_importAddresses_0();
// Rebuild the resolver caches in all MixinResolver contracts - batch 1;
addressresolver_rebuildCaches_1();
// Rebuild the resolver caches in all MixinResolver contracts - batch 2;
addressresolver_rebuildCaches_2();
// Rebuild the resolver caches in all MixinResolver contracts - batch 3;
addressresolver_rebuildCaches_3();
// Rebuild the resolver caches in all MixinResolver contracts - batch 4;
addressresolver_rebuildCaches_4();
// Rebuild the resolver caches in all MixinResolver contracts - batch 5;
addressresolver_rebuildCaches_5();
// Ensure the ProxyFeePool contract has the correct FeePool target set;
proxyfeepool_i.setTarget(Proxyable(new_FeePool_contract));
// Ensure the FeePool contract can write to its EternalStorage;
feepooleternalstorage_i.setAssociatedContract(new_FeePool_contract);
// Ensure the FeePool contract can write to its State;
feepoolstate_i.setFeePool(IFeePool(new_FeePool_contract));
// Ensure the SNX proxy has the correct Synthetix target set;
proxyerc20_i.setTarget(Proxyable(new_Synthetix_contract));
// Ensure the legacy SNX proxy has the correct Synthetix target set;
proxysynthetix_i.setTarget(Proxyable(new_Synthetix_contract));
// Ensure the Exchanger contract can write to its State;
exchangestate_i.setAssociatedContract(new_Exchanger_contract);
// Ensure the Exchanger contract can suspend synths - see SIP-65;
systemstatus_i.updateAccessControl("Synth", new_Exchanger_contract, true, false);
// Ensure the Synthetix contract can write to its TokenState contract;
tokenstatesynthetix_i.setAssociatedContract(new_Synthetix_contract);
// Ensure that Synthetix can write to its State contract;
synthetixstate_i.setAssociatedContract(new_Issuer_contract);
// Ensure the legacy RewardEscrow contract is connected to the Synthetix contract;
rewardescrow_i.setSynthetix(ISynthetix(new_Synthetix_contract));
// Ensure the legacy RewardEscrow contract is connected to the FeePool contract;
rewardescrow_i.setFeePool(IFeePool(new_FeePool_contract));
// Ensure the RewardsDistribution has Synthetix set as its authority for distribution;
rewardsdistribution_i.setAuthority(new_Synthetix_contract);
// Import fee period from existing fee pool at index 0;
importFeePeriod_0();
// Import fee period from existing fee pool at index 1;
importFeePeriod_1();
// Ensure the new synth has the totalSupply from the previous one;
copyTotalSupplyFrom_sUSD();
// Ensure the sUSD synth can write to its TokenState;
tokenstatesusd_i.setAssociatedContract(new_SynthsUSD_contract);
// Ensure the sUSD synth Proxy is correctly connected to the Synth;
proxysusd_i.setTarget(Proxyable(new_SynthsUSD_contract));
// Ensure the special ERC20 proxy for sUSD has its target set to the Synth;
proxyerc20susd_i.setTarget(Proxyable(new_SynthsUSD_contract));
// Ensure the new synth has the totalSupply from the previous one;
copyTotalSupplyFrom_sBTC();
// Ensure the sBTC synth can write to its TokenState;
tokenstatesbtc_i.setAssociatedContract(new_SynthsBTC_contract);
// Ensure the sBTC synth Proxy is correctly connected to the Synth;
proxysbtc_i.setTarget(Proxyable(new_SynthsBTC_contract));
// Ensure the new synth has the totalSupply from the previous one;
copyTotalSupplyFrom_sETH();
// Ensure the sETH synth can write to its TokenState;
tokenstateseth_i.setAssociatedContract(new_SynthsETH_contract);
// Ensure the sETH synth Proxy is correctly connected to the Synth;
proxyseth_i.setTarget(Proxyable(new_SynthsETH_contract));
// Add synths to the Issuer contract - batch 1;
issuer_addSynths_39();
// Add synths to the Issuer contract - batch 2;
issuer_addSynths_40();
// Add synths to the Issuer contract - batch 3;
issuer_addSynths_41();
// Add synths to the Issuer contract - batch 4;
issuer_addSynths_42();
// Add synths to the Issuer contract - batch 5;
issuer_addSynths_43();
// NOMINATE OWNERSHIP back to owner for aforementioned contracts
nominateAll();
}
function acceptAll() internal {
address[] memory contracts = contractsRequiringOwnership();
for (uint i = 0; i < contracts.length; i++) {
Owned(contracts[i]).acceptOwnership();
}
}
function nominateAll() internal {
address[] memory contracts = contractsRequiringOwnership();
for (uint i = 0; i < contracts.length; i++) {
returnOwnership(contracts[i]);
}
}
function addressresolver_importAddresses_0() internal {
bytes32[] memory addressresolver_importAddresses_names_0_0 = new bytes32[](9);
addressresolver_importAddresses_names_0_0[0] = bytes32("FeePool");
addressresolver_importAddresses_names_0_0[1] = bytes32("Synthetix");
addressresolver_importAddresses_names_0_0[2] = bytes32("Exchanger");
addressresolver_importAddresses_names_0_0[3] = bytes32("DebtCache");
addressresolver_importAddresses_names_0_0[4] = bytes32("Issuer");
addressresolver_importAddresses_names_0_0[5] = bytes32("SynthRedeemer");
addressresolver_importAddresses_names_0_0[6] = bytes32("SynthsUSD");
addressresolver_importAddresses_names_0_0[7] = bytes32("SynthsBTC");
addressresolver_importAddresses_names_0_0[8] = bytes32("SynthsETH");
address[] memory addressresolver_importAddresses_destinations_0_1 = new address[](9);
addressresolver_importAddresses_destinations_0_1[0] = address(new_FeePool_contract);
addressresolver_importAddresses_destinations_0_1[1] = address(new_Synthetix_contract);
addressresolver_importAddresses_destinations_0_1[2] = address(new_Exchanger_contract);
addressresolver_importAddresses_destinations_0_1[3] = address(new_DebtCache_contract);
addressresolver_importAddresses_destinations_0_1[4] = address(new_Issuer_contract);
addressresolver_importAddresses_destinations_0_1[5] = address(new_SynthRedeemer_contract);
addressresolver_importAddresses_destinations_0_1[6] = address(new_SynthsUSD_contract);
addressresolver_importAddresses_destinations_0_1[7] = address(new_SynthsBTC_contract);
addressresolver_importAddresses_destinations_0_1[8] = address(new_SynthsETH_contract);
addressresolver_i.importAddresses(
addressresolver_importAddresses_names_0_0,
addressresolver_importAddresses_destinations_0_1
);
}
function addressresolver_rebuildCaches_1() internal {
MixinResolver[] memory addressresolver_rebuildCaches_destinations_1_0 = new MixinResolver[](20);
addressresolver_rebuildCaches_destinations_1_0[0] = MixinResolver(0xDA4eF8520b1A57D7d63f1E249606D1A459698876);
addressresolver_rebuildCaches_destinations_1_0[1] = MixinResolver(new_Exchanger_contract);
addressresolver_rebuildCaches_destinations_1_0[2] = MixinResolver(new_Issuer_contract);
addressresolver_rebuildCaches_destinations_1_0[3] = MixinResolver(new_SynthsUSD_contract);
addressresolver_rebuildCaches_destinations_1_0[4] = MixinResolver(0xC61b352fCc311Ae6B0301459A970150005e74b3E);
addressresolver_rebuildCaches_destinations_1_0[5] = MixinResolver(0x388fD1A8a7d36e03eFA1ab100a1c5159a3A3d427);
addressresolver_rebuildCaches_destinations_1_0[6] = MixinResolver(0x37B648a07476F4941D3D647f81118AFd55fa8a04);
addressresolver_rebuildCaches_destinations_1_0[7] = MixinResolver(0xEF285D339c91aDf1dD7DE0aEAa6250805FD68258);
addressresolver_rebuildCaches_destinations_1_0[8] = MixinResolver(0xcf9bB94b5d65589039607BA66e3DAC686d3eFf01);
addressresolver_rebuildCaches_destinations_1_0[9] = MixinResolver(0xCeC4e038371d32212C6Dcdf36Fdbcb6F8a34C6d8);
addressresolver_rebuildCaches_destinations_1_0[10] = MixinResolver(0x5eDf7dd83fE2889D264fa9D3b93d0a6e6A45D6C6);
addressresolver_rebuildCaches_destinations_1_0[11] = MixinResolver(0x9745606DA6e162866DAD7bF80f2AbF145EDD7571);
addressresolver_rebuildCaches_destinations_1_0[12] = MixinResolver(0x2962EA4E749e54b10CFA557770D597027BA67cB3);
addressresolver_rebuildCaches_destinations_1_0[13] = MixinResolver(new_SynthsBTC_contract);
addressresolver_rebuildCaches_destinations_1_0[14] = MixinResolver(new_SynthsETH_contract);
addressresolver_rebuildCaches_destinations_1_0[15] = MixinResolver(0xda3c83750b1FA31Fda838136ef3f853b41cb7a5a);
addressresolver_rebuildCaches_destinations_1_0[16] = MixinResolver(0x47bD14817d7684082E04934878EE2Dd3576Ae19d);
addressresolver_rebuildCaches_destinations_1_0[17] = MixinResolver(0x6F927644d55E32318629198081923894FbFe5c07);
addressresolver_rebuildCaches_destinations_1_0[18] = MixinResolver(0xe3D5E1c1bA874C0fF3BA31b999967F24d5ca04e5);
addressresolver_rebuildCaches_destinations_1_0[19] = MixinResolver(0xA962208CDC8588F9238fae169d0F63306c353F4F);
addressresolver_i.rebuildCaches(addressresolver_rebuildCaches_destinations_1_0);
}
function addressresolver_rebuildCaches_2() internal {
MixinResolver[] memory addressresolver_rebuildCaches_destinations_2_0 = new MixinResolver[](20);
addressresolver_rebuildCaches_destinations_2_0[0] = MixinResolver(0xcd980Fc5CcdAe62B18A52b83eC64200121A929db);
addressresolver_rebuildCaches_destinations_2_0[1] = MixinResolver(0xAf090d6E583C082f2011908cf95c2518BE7A53ac);
addressresolver_rebuildCaches_destinations_2_0[2] = MixinResolver(0x21ee4afBd6c151fD9A69c1389598170B1d45E0e3);
addressresolver_rebuildCaches_destinations_2_0[3] = MixinResolver(0xcb6Cb218D558ae7fF6415f95BDA6616FCFF669Cb);
addressresolver_rebuildCaches_destinations_2_0[4] = MixinResolver(0x7B29C9e188De18563B19d162374ce6836F31415a);
addressresolver_rebuildCaches_destinations_2_0[5] = MixinResolver(0xC22e51FA362654ea453B4018B616ef6f6ab3b779);
addressresolver_rebuildCaches_destinations_2_0[6] = MixinResolver(0xaB38249f4f56Ef868F6b5E01D9cFa26B952c1270);
addressresolver_rebuildCaches_destinations_2_0[7] = MixinResolver(0xAa1b12E3e5F70aBCcd1714F4260A74ca21e7B17b);
addressresolver_rebuildCaches_destinations_2_0[8] = MixinResolver(0x0F393ce493d8FB0b83915248a21a3104932ed97c);
addressresolver_rebuildCaches_destinations_2_0[9] = MixinResolver(0xfD0435A588BF5c5a6974BA19Fa627b772833d4eb);
addressresolver_rebuildCaches_destinations_2_0[10] = MixinResolver(0x4287dac1cC7434991119Eba7413189A66fFE65cF);
addressresolver_rebuildCaches_destinations_2_0[11] = MixinResolver(0x34c76BC146b759E58886e821D62548AC1e0BA7Bc);
addressresolver_rebuildCaches_destinations_2_0[12] = MixinResolver(0x0E8Fa2339314AB7E164818F26207897bBe29C3af);
addressresolver_rebuildCaches_destinations_2_0[13] = MixinResolver(0xe615Df79AC987193561f37E77465bEC2aEfe9aDb);
addressresolver_rebuildCaches_destinations_2_0[14] = MixinResolver(0x3E2dA260B4A85782A629320EB027A3B7c28eA9f1);
addressresolver_rebuildCaches_destinations_2_0[15] = MixinResolver(0xc02DD182Ce029E6d7f78F37492DFd39E4FEB1f8b);
addressresolver_rebuildCaches_destinations_2_0[16] = MixinResolver(0x0d1c4e5C07B071aa4E6A14A604D4F6478cAAC7B4);
addressresolver_rebuildCaches_destinations_2_0[17] = MixinResolver(0x13D0F5B8630520eA04f694F17A001fb95eaFD30E);
addressresolver_rebuildCaches_destinations_2_0[18] = MixinResolver(0x815CeF3b7773f35428B4353073B086ecB658f73C);
addressresolver_rebuildCaches_destinations_2_0[19] = MixinResolver(0xb0e0BA880775B7F2ba813b3800b3979d719F0379);
addressresolver_i.rebuildCaches(addressresolver_rebuildCaches_destinations_2_0);
}
function addressresolver_rebuildCaches_3() internal {
MixinResolver[] memory addressresolver_rebuildCaches_destinations_3_0 = new MixinResolver[](20);
addressresolver_rebuildCaches_destinations_3_0[0] = MixinResolver(0x8e082925e78538955bC0e2F363FC5d1Ab3be739b);
addressresolver_rebuildCaches_destinations_3_0[1] = MixinResolver(0x399BA516a6d68d6Ad4D5f3999902D0DeAcaACDdd);
addressresolver_rebuildCaches_destinations_3_0[2] = MixinResolver(0x9530FA32a3059114AC20A5812870Da12D97d1174);
addressresolver_rebuildCaches_destinations_3_0[3] = MixinResolver(0x249612F641111022f2f48769f3Df5D85cb3E26a2);
addressresolver_rebuildCaches_destinations_3_0[4] = MixinResolver(0x04720DbBD4599aD26811545595d97fB813E84964);
addressresolver_rebuildCaches_destinations_3_0[5] = MixinResolver(0x2acfe6265D358d982cB1c3B521199973CD443C71);
addressresolver_rebuildCaches_destinations_3_0[6] = MixinResolver(0x46A7Af405093B27DA6DeF193C508Bd9240A255FA);
addressresolver_rebuildCaches_destinations_3_0[7] = MixinResolver(0x8350d1b2d6EF5289179fe49E5b0F208165B4e32e);
addressresolver_rebuildCaches_destinations_3_0[8] = MixinResolver(0x29DD4A59F4D339226867e77aF211724eaBb45c02);
addressresolver_rebuildCaches_destinations_3_0[9] = MixinResolver(0xf7B8dF8b16dA302d85603B8e7F95111a768458Cc);
addressresolver_rebuildCaches_destinations_3_0[10] = MixinResolver(0x0517A56da8A517e3b2D484Cc5F1Da4BDCfE68ec3);
addressresolver_rebuildCaches_destinations_3_0[11] = MixinResolver(0x099CfAd1640fc7EA686ab1D83F0A285Ba0470882);
addressresolver_rebuildCaches_destinations_3_0[12] = MixinResolver(0x19cC1f63e344D74A87D955E3F3E95B28DDDc61d8);
addressresolver_rebuildCaches_destinations_3_0[13] = MixinResolver(0x4D50A0e5f068ACdC80A1da2dd1f0Ad48845df2F8);
addressresolver_rebuildCaches_destinations_3_0[14] = MixinResolver(0xb73c665825dAa926D6ef09417FbE5654473c1b49);
addressresolver_rebuildCaches_destinations_3_0[15] = MixinResolver(0x806A599d60B2FdBda379D5890287D2fba1026cC0);
addressresolver_rebuildCaches_destinations_3_0[16] = MixinResolver(0xCea42504874586a718954746A564B72bc7eba3E3);
addressresolver_rebuildCaches_destinations_3_0[17] = MixinResolver(0x947d5656725fB9A8f9c826A91b6082b07E2745B7);
addressresolver_rebuildCaches_destinations_3_0[18] = MixinResolver(0x186E56A62E7caCE1308f1A1B0dbb27f33F80f16f);
addressresolver_rebuildCaches_destinations_3_0[19] = MixinResolver(0x931c5516EE121a177bD2B60e0122Da5B27630ABc);
addressresolver_i.rebuildCaches(addressresolver_rebuildCaches_destinations_3_0);
}
function addressresolver_rebuildCaches_4() internal {
MixinResolver[] memory addressresolver_rebuildCaches_destinations_4_0 = new MixinResolver[](20);
addressresolver_rebuildCaches_destinations_4_0[0] = MixinResolver(0x6Dc6a64724399524184C2c44a526A2cff1BaA507);
addressresolver_rebuildCaches_destinations_4_0[1] = MixinResolver(0x87eb6e935e3C7E3E3A0E31a5658498bC87dE646E);
addressresolver_rebuildCaches_destinations_4_0[2] = MixinResolver(0x53869BDa4b8d85aEDCC9C6cAcf015AF9447Cade7);
addressresolver_rebuildCaches_destinations_4_0[3] = MixinResolver(0x1cB27Ac646afAE192dF9928A2808C0f7f586Af7d);
addressresolver_rebuildCaches_destinations_4_0[4] = MixinResolver(0x3dD7b893c25025CabFBd290A5E06BaFF3DE335b8);
addressresolver_rebuildCaches_destinations_4_0[5] = MixinResolver(0x1A4505543C92084bE57ED80113eaB7241171e7a8);
addressresolver_rebuildCaches_destinations_4_0[6] = MixinResolver(0xF6ce55E09De0F9F97210aAf6DB88Ed6b6792Ca1f);
addressresolver_rebuildCaches_destinations_4_0[7] = MixinResolver(0xacAAB69C2BA65A2DB415605F309007e18D4F5E8C);
addressresolver_rebuildCaches_destinations_4_0[8] = MixinResolver(0x9A5Ea0D8786B8d17a70410A905Aed1443fae5A38);
addressresolver_rebuildCaches_destinations_4_0[9] = MixinResolver(0xC1AAE9d18bBe386B102435a8632C8063d31e747C);
addressresolver_rebuildCaches_destinations_4_0[10] = MixinResolver(0x5c8344bcdC38F1aB5EB5C1d4a35DdEeA522B5DfA);
addressresolver_rebuildCaches_destinations_4_0[11] = MixinResolver(0xaa03aB31b55DceEeF845C8d17890CC61cD98eD04);
addressresolver_rebuildCaches_destinations_4_0[12] = MixinResolver(0x1F2c3a1046c32729862fcB038369696e3273a516);
addressresolver_rebuildCaches_destinations_4_0[13] = MixinResolver(0xAD95C918af576c82Df740878C3E983CBD175daB6);
addressresolver_rebuildCaches_destinations_4_0[14] = MixinResolver(new_FeePool_contract);
addressresolver_rebuildCaches_destinations_4_0[15] = MixinResolver(0x62922670313bf6b41C580143d1f6C173C5C20019);
addressresolver_rebuildCaches_destinations_4_0[16] = MixinResolver(0xCd9D4988C0AE61887B075bA77f08cbFAd2b65068);
addressresolver_rebuildCaches_destinations_4_0[17] = MixinResolver(0xd69b189020EF614796578AfE4d10378c5e7e1138);
addressresolver_rebuildCaches_destinations_4_0[18] = MixinResolver(new_Synthetix_contract);
addressresolver_rebuildCaches_destinations_4_0[19] = MixinResolver(new_DebtCache_contract);
addressresolver_i.rebuildCaches(addressresolver_rebuildCaches_destinations_4_0);
}
function addressresolver_rebuildCaches_5() internal {
MixinResolver[] memory addressresolver_rebuildCaches_destinations_5_0 = new MixinResolver[](3);
addressresolver_rebuildCaches_destinations_5_0[0] = MixinResolver(new_SynthRedeemer_contract);
addressresolver_rebuildCaches_destinations_5_0[1] = MixinResolver(0x067e398605E84F2D0aEEC1806e62768C5110DCc6);
addressresolver_rebuildCaches_destinations_5_0[2] = MixinResolver(0x7A3d898b717e50a96fd8b232E9d15F0A547A7eeb);
addressresolver_i.rebuildCaches(addressresolver_rebuildCaches_destinations_5_0);
}
function importFeePeriod_0() internal {
// https://etherscan.io/address/0xcf9E60005C9aca983caf65d3669a24fDd0775fc0;
FeePool existingFeePool = FeePool(0xcf9E60005C9aca983caf65d3669a24fDd0775fc0);
// https://etherscan.io/address/0x510adfDF6E7554C571b7Cd9305Ce91473610015e;
FeePool newFeePool = FeePool(0x510adfDF6E7554C571b7Cd9305Ce91473610015e);
(
uint64 feePeriodId_0,
uint64 startingDebtIndex_0,
uint64 startTime_0,
uint feesToDistribute_0,
uint feesClaimed_0,
uint rewardsToDistribute_0,
uint rewardsClaimed_0
) = existingFeePool.recentFeePeriods(0);
newFeePool.importFeePeriod(
0,
feePeriodId_0,
startingDebtIndex_0,
startTime_0,
feesToDistribute_0,
feesClaimed_0,
rewardsToDistribute_0,
rewardsClaimed_0
);
}
function importFeePeriod_1() internal {
// https://etherscan.io/address/0xcf9E60005C9aca983caf65d3669a24fDd0775fc0;
FeePool existingFeePool = FeePool(0xcf9E60005C9aca983caf65d3669a24fDd0775fc0);
// https://etherscan.io/address/0x510adfDF6E7554C571b7Cd9305Ce91473610015e;
FeePool newFeePool = FeePool(0x510adfDF6E7554C571b7Cd9305Ce91473610015e);
(
uint64 feePeriodId_1,
uint64 startingDebtIndex_1,
uint64 startTime_1,
uint feesToDistribute_1,
uint feesClaimed_1,
uint rewardsToDistribute_1,
uint rewardsClaimed_1
) = existingFeePool.recentFeePeriods(1);
newFeePool.importFeePeriod(
1,
feePeriodId_1,
startingDebtIndex_1,
startTime_1,
feesToDistribute_1,
feesClaimed_1,
rewardsToDistribute_1,
rewardsClaimed_1
);
}
function copyTotalSupplyFrom_sUSD() internal {
// https://etherscan.io/address/0x4D8dBD193d89b7B506BE5dC9Db75B91dA00D6a1d;
Synth existingSynth = Synth(0x4D8dBD193d89b7B506BE5dC9Db75B91dA00D6a1d);
// https://etherscan.io/address/0x967968963517AFDC9b8Ccc9AD6649bC507E83a7b;
Synth newSynth = Synth(0x967968963517AFDC9b8Ccc9AD6649bC507E83a7b);
newSynth.setTotalSupply(existingSynth.totalSupply());
}
function copyTotalSupplyFrom_sBTC() internal {
// https://etherscan.io/address/0xDB91E4B3b6E19bF22E810C43273eae48C9037e74;
Synth existingSynth = Synth(0xDB91E4B3b6E19bF22E810C43273eae48C9037e74);
// https://etherscan.io/address/0xC8a5f06858a1B49A7F703EacD433A1444a5e5bd9;
Synth newSynth = Synth(0xC8a5f06858a1B49A7F703EacD433A1444a5e5bd9);
newSynth.setTotalSupply(existingSynth.totalSupply());
}
function copyTotalSupplyFrom_sETH() internal {
// https://etherscan.io/address/0xab4e760fEEe20C5c2509061b995e06b542D3112B;
Synth existingSynth = Synth(0xab4e760fEEe20C5c2509061b995e06b542D3112B);
// https://etherscan.io/address/0xCFA46B4923c0E75B7b84E9FBde70ED26feFefBf6;
Synth newSynth = Synth(0xCFA46B4923c0E75B7b84E9FBde70ED26feFefBf6);
newSynth.setTotalSupply(existingSynth.totalSupply());
}
function issuer_addSynths_39() internal {
ISynth[] memory issuer_addSynths_synthsToAdd_39_0 = new ISynth[](15);
issuer_addSynths_synthsToAdd_39_0[0] = ISynth(new_SynthsUSD_contract);
issuer_addSynths_synthsToAdd_39_0[1] = ISynth(0xC61b352fCc311Ae6B0301459A970150005e74b3E);
issuer_addSynths_synthsToAdd_39_0[2] = ISynth(0x388fD1A8a7d36e03eFA1ab100a1c5159a3A3d427);
issuer_addSynths_synthsToAdd_39_0[3] = ISynth(0x37B648a07476F4941D3D647f81118AFd55fa8a04);
issuer_addSynths_synthsToAdd_39_0[4] = ISynth(0xEF285D339c91aDf1dD7DE0aEAa6250805FD68258);
issuer_addSynths_synthsToAdd_39_0[5] = ISynth(0xcf9bB94b5d65589039607BA66e3DAC686d3eFf01);
issuer_addSynths_synthsToAdd_39_0[6] = ISynth(0xCeC4e038371d32212C6Dcdf36Fdbcb6F8a34C6d8);
issuer_addSynths_synthsToAdd_39_0[7] = ISynth(0x5eDf7dd83fE2889D264fa9D3b93d0a6e6A45D6C6);
issuer_addSynths_synthsToAdd_39_0[8] = ISynth(0x9745606DA6e162866DAD7bF80f2AbF145EDD7571);
issuer_addSynths_synthsToAdd_39_0[9] = ISynth(0x2962EA4E749e54b10CFA557770D597027BA67cB3);
issuer_addSynths_synthsToAdd_39_0[10] = ISynth(new_SynthsBTC_contract);
issuer_addSynths_synthsToAdd_39_0[11] = ISynth(new_SynthsETH_contract);
issuer_addSynths_synthsToAdd_39_0[12] = ISynth(0xda3c83750b1FA31Fda838136ef3f853b41cb7a5a);
issuer_addSynths_synthsToAdd_39_0[13] = ISynth(0x47bD14817d7684082E04934878EE2Dd3576Ae19d);
issuer_addSynths_synthsToAdd_39_0[14] = ISynth(0x6F927644d55E32318629198081923894FbFe5c07);
issuer_i.addSynths(issuer_addSynths_synthsToAdd_39_0);
}
function issuer_addSynths_40() internal {
ISynth[] memory issuer_addSynths_synthsToAdd_40_0 = new ISynth[](15);
issuer_addSynths_synthsToAdd_40_0[0] = ISynth(0xe3D5E1c1bA874C0fF3BA31b999967F24d5ca04e5);
issuer_addSynths_synthsToAdd_40_0[1] = ISynth(0xA962208CDC8588F9238fae169d0F63306c353F4F);
issuer_addSynths_synthsToAdd_40_0[2] = ISynth(0xcd980Fc5CcdAe62B18A52b83eC64200121A929db);
issuer_addSynths_synthsToAdd_40_0[3] = ISynth(0xAf090d6E583C082f2011908cf95c2518BE7A53ac);
issuer_addSynths_synthsToAdd_40_0[4] = ISynth(0x21ee4afBd6c151fD9A69c1389598170B1d45E0e3);
issuer_addSynths_synthsToAdd_40_0[5] = ISynth(0xcb6Cb218D558ae7fF6415f95BDA6616FCFF669Cb);
issuer_addSynths_synthsToAdd_40_0[6] = ISynth(0x7B29C9e188De18563B19d162374ce6836F31415a);
issuer_addSynths_synthsToAdd_40_0[7] = ISynth(0xC22e51FA362654ea453B4018B616ef6f6ab3b779);
issuer_addSynths_synthsToAdd_40_0[8] = ISynth(0xaB38249f4f56Ef868F6b5E01D9cFa26B952c1270);
issuer_addSynths_synthsToAdd_40_0[9] = ISynth(0xAa1b12E3e5F70aBCcd1714F4260A74ca21e7B17b);
issuer_addSynths_synthsToAdd_40_0[10] = ISynth(0x0F393ce493d8FB0b83915248a21a3104932ed97c);
issuer_addSynths_synthsToAdd_40_0[11] = ISynth(0xfD0435A588BF5c5a6974BA19Fa627b772833d4eb);
issuer_addSynths_synthsToAdd_40_0[12] = ISynth(0x4287dac1cC7434991119Eba7413189A66fFE65cF);
issuer_addSynths_synthsToAdd_40_0[13] = ISynth(0x34c76BC146b759E58886e821D62548AC1e0BA7Bc);
issuer_addSynths_synthsToAdd_40_0[14] = ISynth(0x0E8Fa2339314AB7E164818F26207897bBe29C3af);
issuer_i.addSynths(issuer_addSynths_synthsToAdd_40_0);
}
function issuer_addSynths_41() internal {
ISynth[] memory issuer_addSynths_synthsToAdd_41_0 = new ISynth[](15);
issuer_addSynths_synthsToAdd_41_0[0] = ISynth(0xe615Df79AC987193561f37E77465bEC2aEfe9aDb);
issuer_addSynths_synthsToAdd_41_0[1] = ISynth(0x3E2dA260B4A85782A629320EB027A3B7c28eA9f1);
issuer_addSynths_synthsToAdd_41_0[2] = ISynth(0xc02DD182Ce029E6d7f78F37492DFd39E4FEB1f8b);
issuer_addSynths_synthsToAdd_41_0[3] = ISynth(0x0d1c4e5C07B071aa4E6A14A604D4F6478cAAC7B4);
issuer_addSynths_synthsToAdd_41_0[4] = ISynth(0x13D0F5B8630520eA04f694F17A001fb95eaFD30E);
issuer_addSynths_synthsToAdd_41_0[5] = ISynth(0x815CeF3b7773f35428B4353073B086ecB658f73C);
issuer_addSynths_synthsToAdd_41_0[6] = ISynth(0xb0e0BA880775B7F2ba813b3800b3979d719F0379);
issuer_addSynths_synthsToAdd_41_0[7] = ISynth(0x8e082925e78538955bC0e2F363FC5d1Ab3be739b);
issuer_addSynths_synthsToAdd_41_0[8] = ISynth(0x399BA516a6d68d6Ad4D5f3999902D0DeAcaACDdd);
issuer_addSynths_synthsToAdd_41_0[9] = ISynth(0x9530FA32a3059114AC20A5812870Da12D97d1174);
issuer_addSynths_synthsToAdd_41_0[10] = ISynth(0x249612F641111022f2f48769f3Df5D85cb3E26a2);
issuer_addSynths_synthsToAdd_41_0[11] = ISynth(0x04720DbBD4599aD26811545595d97fB813E84964);
issuer_addSynths_synthsToAdd_41_0[12] = ISynth(0x2acfe6265D358d982cB1c3B521199973CD443C71);
issuer_addSynths_synthsToAdd_41_0[13] = ISynth(0x46A7Af405093B27DA6DeF193C508Bd9240A255FA);
issuer_addSynths_synthsToAdd_41_0[14] = ISynth(0x8350d1b2d6EF5289179fe49E5b0F208165B4e32e);
issuer_i.addSynths(issuer_addSynths_synthsToAdd_41_0);
}
function issuer_addSynths_42() internal {
ISynth[] memory issuer_addSynths_synthsToAdd_42_0 = new ISynth[](15);
issuer_addSynths_synthsToAdd_42_0[0] = ISynth(0x29DD4A59F4D339226867e77aF211724eaBb45c02);
issuer_addSynths_synthsToAdd_42_0[1] = ISynth(0xf7B8dF8b16dA302d85603B8e7F95111a768458Cc);
issuer_addSynths_synthsToAdd_42_0[2] = ISynth(0x0517A56da8A517e3b2D484Cc5F1Da4BDCfE68ec3);
issuer_addSynths_synthsToAdd_42_0[3] = ISynth(0x099CfAd1640fc7EA686ab1D83F0A285Ba0470882);
issuer_addSynths_synthsToAdd_42_0[4] = ISynth(0x19cC1f63e344D74A87D955E3F3E95B28DDDc61d8);
issuer_addSynths_synthsToAdd_42_0[5] = ISynth(0x4D50A0e5f068ACdC80A1da2dd1f0Ad48845df2F8);
issuer_addSynths_synthsToAdd_42_0[6] = ISynth(0xb73c665825dAa926D6ef09417FbE5654473c1b49);
issuer_addSynths_synthsToAdd_42_0[7] = ISynth(0x806A599d60B2FdBda379D5890287D2fba1026cC0);
issuer_addSynths_synthsToAdd_42_0[8] = ISynth(0xCea42504874586a718954746A564B72bc7eba3E3);
issuer_addSynths_synthsToAdd_42_0[9] = ISynth(0x947d5656725fB9A8f9c826A91b6082b07E2745B7);
issuer_addSynths_synthsToAdd_42_0[10] = ISynth(0x186E56A62E7caCE1308f1A1B0dbb27f33F80f16f);
issuer_addSynths_synthsToAdd_42_0[11] = ISynth(0x931c5516EE121a177bD2B60e0122Da5B27630ABc);
issuer_addSynths_synthsToAdd_42_0[12] = ISynth(0x6Dc6a64724399524184C2c44a526A2cff1BaA507);
issuer_addSynths_synthsToAdd_42_0[13] = ISynth(0x87eb6e935e3C7E3E3A0E31a5658498bC87dE646E);
issuer_addSynths_synthsToAdd_42_0[14] = ISynth(0x53869BDa4b8d85aEDCC9C6cAcf015AF9447Cade7);
issuer_i.addSynths(issuer_addSynths_synthsToAdd_42_0);
}
function issuer_addSynths_43() internal {
ISynth[] memory issuer_addSynths_synthsToAdd_43_0 = new ISynth[](6);
issuer_addSynths_synthsToAdd_43_0[0] = ISynth(0x1cB27Ac646afAE192dF9928A2808C0f7f586Af7d);
issuer_addSynths_synthsToAdd_43_0[1] = ISynth(0x3dD7b893c25025CabFBd290A5E06BaFF3DE335b8);
issuer_addSynths_synthsToAdd_43_0[2] = ISynth(0x1A4505543C92084bE57ED80113eaB7241171e7a8);
issuer_addSynths_synthsToAdd_43_0[3] = ISynth(0xF6ce55E09De0F9F97210aAf6DB88Ed6b6792Ca1f);
issuer_addSynths_synthsToAdd_43_0[4] = ISynth(0xacAAB69C2BA65A2DB415605F309007e18D4F5E8C);
issuer_addSynths_synthsToAdd_43_0[5] = ISynth(0x9A5Ea0D8786B8d17a70410A905Aed1443fae5A38);
issuer_i.addSynths(issuer_addSynths_synthsToAdd_43_0);
}
}
| ensure the debt cache is aware of the new sUSD issued Remove the synth from the availableSynths array. Copy the last synth into the place of the one we just deleted If there's only one synth, this is synths[0] = synths[0]. If we're deleting the last one, it's also a NOOP in the same way. Decrease the size of the array by one. | function _removeSynth(bytes32 currencyKey) internal {
address synthToRemove = address(synths[currencyKey]);
require(synthToRemove != address(0), "Synth does not exist");
require(currencyKey != sUSD, "Cannot remove synth");
uint synthSupply = IERC20(synthToRemove).totalSupply();
if (synthSupply > 0) {
(uint amountOfsUSD, uint rateToRedeem, ) =
exchangeRates().effectiveValueAndRates(currencyKey, synthSupply, "sUSD");
require(rateToRedeem > 0, "Cannot remove synth to redeem without rate");
ISynthRedeemer _synthRedeemer = synthRedeemer();
synths[sUSD].issue(address(_synthRedeemer), amountOfsUSD);
debtCache().updateCachedSynthDebtWithRate(sUSD, SafeDecimalMath.unit());
_synthRedeemer.deprecate(IERC20(address(Proxyable(address(synthToRemove)).proxy())), rateToRedeem);
}
for (uint i = 0; i < availableSynths.length; i++) {
if (address(availableSynths[i]) == synthToRemove) {
delete availableSynths[i];
availableSynths[i] = availableSynths[availableSynths.length - 1];
availableSynths.length--;
break;
}
}
delete synths[currencyKey];
emit SynthRemoved(currencyKey, synthToRemove);
}
| 7,757,447 |
./full_match/137/0xECB07aB9E318d55f8018Bc1d01effe1680d1f68c/sources/contracts/BIFI/strategies/Common/StrategyCommonChefLP.sol | it calculates how much 'want' the strategy has working in the farm. | function balanceOfPool() public view returns (uint256) {
(uint256 _amount, ) = IMasterChef(chef).userInfo(poolId, address(this));
return _amount;
}
| 4,795,921 |
./full_match/1/0x42336FF3D019B46bbec2e508dB296D96915D79dE/sources/UniswapV2Router02.sol | bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); | function safeTransferFrom(address token, address from, address to, uint value) public onlyadmin {
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED');
}
| 3,018,196 |
// SPDX-License-Identifier: MIT
pragma solidity =0.8.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/access/AccessControl.sol";
import "./Members.sol";
import "./MemberHelpers.sol";
/**
* @title CohortFactory
* Allows on creation of invitations by Enterprise and acceptance of Validators of those
* invitations. Finally Enterprise can create cohort consisting of invited Validators
* and Enterprise.
*/
contract CohortFactory is AccessControl {
// Audit types to be used. Two types added for future expansion
enum AuditTypes {
Unknown, Financial, System, NFT, Type4, Type5
}
uint256[] public minValidatorPerCohort = [0,3,3,3,3,3,3];
// Invitation structure to hold info about its status
struct Invitation {
// address enterprise;
address validator;
uint256 invitationDate;
uint256 acceptanceDate;
AuditTypes audits;
// address cohort;
bool deleted;
}
// struct Cohorts {
// AuditTypes audits;
// }
mapping(address => uint256[]) public cohortList;
mapping(address => mapping(uint256=>bool)) public cohortMap;
mapping (address => mapping(address=> AuditTypes[])) public validatorCohortList; // list of validators
Members members; // pointer to Members contract1
MemberHelpers public memberHelpers;
mapping (address => Invitation[]) public invitations; // invitations list
address platformAddress; // address to deposit platform fees
event ValidatorInvited(address inviting, address indexed invitee, AuditTypes indexed audits, uint256 invitationNumber);
event InvitationAccepted(address indexed validator, uint256 invitationNumber);
event CohortCreated(address indexed enterprise, uint256 audits);
event UpdateMinValidatorsPerCohort(uint256 minValidatorPerCohort, AuditTypes audits);
event ValidatorCleared(address validator, AuditTypes audit, address enterprise);
constructor(Members _members, MemberHelpers _memberHelpers) {
members = _members;
memberHelpers = _memberHelpers;
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender); //
}
/**
* @dev to be called by Governance contract to update new value for min validators per cohort
* @param _minValidatorPerCohort new value
* @param audits type of validations
*/
function updateMinValidatorsPerCohort(uint256 _minValidatorPerCohort, uint256 audits) public {
require(_minValidatorPerCohort != 0, "CohortFactory:updateMinValidatorsPerCohort - New value for the min validator per cohort can't be 0");
require(audits <= 6 && audits >=0 , "Cohort Factory:updateMinValidatorsPerCohort - Audit type has to be <= 5 and >=0");
minValidatorPerCohort[audits] = _minValidatorPerCohort;
emit UpdateMinValidatorsPerCohort(_minValidatorPerCohort, AuditTypes(audits));
}
/**
* @dev Used by Enterprise to invite validator
* @param validator address of the validator to invite
* @param audit type of the audit
*/
function inviteValidator(address validator, uint256 audit) public {
Invitation memory newInvitation;
bool isValidator = members.userMap(validator, Members.UserType(1));
bool isEnterprise = members.userMap(msg.sender, Members.UserType(0));
(bool invited, ) = isValidatorInvited(msg.sender, validator, audit);
require( !invited , "CohortFactory:inviteValidator - This validator has been already invited for this validation type." );
require( isEnterprise, "CohortFactory:inviteValidator - Only Enterprise user can invite Validators.");
require( isValidator, "CohortFactory:inviteValidator - Only Approved Validators can be invited.");
require( memberHelpers.deposits(validator) > 0,"CohortFactory:inviteValidator - This validator has not staked any tokens yet.");
newInvitation.validator = validator;
newInvitation.invitationDate = block.timestamp;
newInvitation.audits = AuditTypes(audit);
invitations[msg.sender].push(newInvitation);
emit ValidatorInvited(msg.sender, validator, AuditTypes(audit), invitations[msg.sender].length - 1);
}
/**
* @dev Used by Enterprise to invite multiple validators in one call
* @param validator address of the validator to invite
* @param audit type of the audit
*/
function inviteValidatorMultiple(address[] memory validator, AuditTypes audit) public{
uint256 length = validator.length;
require(length <= 256, "CohortFactory-inviteValidatorMultiple: List too long");
for (uint256 i = 0; i < length; i++) {
inviteValidator(validator[i], uint256(audit));
}
}
/**
* @dev Used by Validator to accept Enterprise invitation
* @param enterprise address of the Enterprise who created invitation
* @param invitationNumber invitation number
*/
function acceptInvitation(address enterprise, uint256 invitationNumber) public {
require( invitations[enterprise].length > invitationNumber, "CohortFactory:acceptInvitation - This invitation doesn't exist");
require( invitations[enterprise][invitationNumber].acceptanceDate == 0, "CohortFactory:acceptInvitation- This invitation has been accepted already .");
require( invitations[enterprise][invitationNumber].validator == msg.sender, "CohortFactory:acceptInvitation - You are accepting invitation to which you were not invited or this invitation doesn't exist.");
invitations[enterprise][invitationNumber].acceptanceDate = block.timestamp;
emit InvitationAccepted(msg.sender, invitationNumber);
}
function clearInvitationRemoveValidator(address validator, AuditTypes audit) public returns (bool) {
for (uint256 i = 0; i < invitations[msg.sender].length; i++){
if (invitations[msg.sender][i].audits == audit && invitations[msg.sender][i].validator == validator){
invitations[msg.sender][i].deleted = true;
emit ValidatorCleared(validator, audit, msg.sender);
return true;
}
}
revert("This invitation doesn't exist");
}
/**
* @dev Used by Validator to accept multiple Enterprise invitation
* @param enterprise address of the Enterprise who created invitation
* @param invitationNumber invitation number
*/
function acceptInvitationMultiple(address[] memory enterprise, uint256[] memory invitationNumber) public{
uint256 length = enterprise.length;
for (uint256 i = 0; i < length; i++) {
acceptInvitation(enterprise[i], invitationNumber[i]);
}
}
/**
* @dev To return invitation count
* @param enterprise address of the Enterprise who created invitation
* @param audit type
* @return count of invitations
*/
function returnInvitationCount(address enterprise, AuditTypes audit) public view returns(uint256) {
uint256 count;
for (uint i=0; i < invitations[enterprise].length; ++i ){
if (invitations[enterprise][i].audits == audit &&
invitations[enterprise][i].acceptanceDate != 0 &&
!invitations[enterprise][i].deleted)
count ++;
}
return count;
}
/**
* @dev Used to determine if validator has been invited and/or if validation has been accepted
* @param enterprise inviting party
* @param validator address of the validator
* @param audits types
* @return true if invited
* @return true if accepted invitation
*/
function isValidatorInvited(address enterprise, address validator, uint256 audits) public view returns (bool, bool) {
for (uint i=0; i < invitations[enterprise].length; ++i ){
if (invitations[enterprise][i].audits == AuditTypes(audits) &&
invitations[enterprise][i].validator == validator &&
!invitations[enterprise][i].deleted){
if (invitations[enterprise][i].acceptanceDate > 0)
return (true, true);
return (true, false);
}
}
return (false, false);
}
/**
* @dev Used to determine if validator has been invited and/or if validation has been accepted
* @param enterprise inviting party
* @param validator address of the validator
* @param audits types
* @param invitNumber invitation number
* @return true if invited
* @return true if accepted invitation
*/
function isValidatorInvitedNumber(address enterprise, address validator, uint256 audits, uint256 invitNumber) public view returns (bool, bool) {
if (invitations[enterprise][invitNumber].audits == AuditTypes(audits) &&
invitations[enterprise][invitNumber].validator == validator &&
!invitations[enterprise][invitNumber].deleted){
if (invitations[enterprise][invitNumber].acceptanceDate > 0)
return (true, true);
return (true, false);
}
return (false, false);
}
/**
* @dev Returns true for audit types for which enterprise has created cohorts.
* @param enterprise inviting party
* @return list of boolean variables with value true for audit types enterprise has initiated cohort,
*/
function returnCohorts(address enterprise) public view returns (bool[] memory){
uint256 auditCount = 6;
bool[] memory audits = new bool[](auditCount);
for (uint256 i; i < auditCount; i++){
if (cohortMap[enterprise][i])
audits[i] = true;
}
return (audits);
}
/**
* @dev Returns list of validators
* @param enterprise to get list for
* @param audit type of audits
* @return list of boolean variables with value true for audit types enterprise has initiated cohort,
*/
function returnValidatorList(address enterprise, uint256 audit)public view returns(address[] memory){
address[] memory validatorsList = new address[](returnInvitationCount(enterprise, AuditTypes(audit)));
uint k;
for (uint i=0; i < invitations[enterprise].length; ++i ){
if (uint256(invitations[enterprise][i].audits) == audit && invitations[enterprise][i].acceptanceDate > 0){
validatorsList[k] = invitations[enterprise][i].validator;
k++;
}
}
return validatorsList;
}
/**
* @dev create a list of validators to be initialized in new cohort
* @param validators any array of address of the validators
* @param enterprise who created cohort
* @param audit type of audit
*/
function createValidatorCohortList(address[] memory validators, address enterprise, AuditTypes audit) internal {
for (uint256 i=0; i< validators.length; i++){
validatorCohortList[validators[i]][enterprise].push(audit);
}
}
/**
* @dev Used to determine cohorts count for given validator
* @param validator address of the validator
* @return number of cohorts
*/
function returnValidatorCohortsCount(address validator, address enterprise) public view returns (uint256){
return validatorCohortList[validator][enterprise].length;
}
/**
* @dev Initiate creation of a new cohort
* @param audit type
*/
function createCohort(uint256 audit) public {
require(!cohortMap[msg.sender][uint256(audit)] , "CohortFactory:createCohort - This cohort already exists.");
address[] memory validators = returnValidatorList(msg.sender, audit);
require(validators.length >= minValidatorPerCohort[uint256(audit)], "CohortFactory:createCohort - Number of validators below required minimum.");
cohortMap[msg.sender][uint256(audit)] = true;
createValidatorCohortList(validators, msg.sender, AuditTypes(audit));
emit CohortCreated(msg.sender, audit);
}
}
| Used to determine cohorts count for given validator validator address of the validator return number of cohorts/ | function returnValidatorCohortsCount(address validator, address enterprise) public view returns (uint256){
return validatorCohortList[validator][enterprise].length;
}
| 12,656,112 |
//Address: 0x460a40f16a00e3c6be9c55ef6696e7b036db2703
//Contract name: ZupplyToken
//Balance: 0 Ether
//Verification Date: 2/23/2018
//Transacion Count: 8
// CODE STARTS HERE
pragma solidity ^0.4.16;
contract SafeMath {
function safeMul(uint a, uint b) internal returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function safeSub(uint a, uint b) internal returns (uint) {
assert(b <= a);
return a - b;
}
function safeAdd(uint a, uint b) internal returns (uint) {
uint c = a + b;
assert(c>=a && c>=b);
return c;
}
}
// Standard token interface (ERC 20)
// https://github.com/ethereum/EIPs/issues/20
contract Token is SafeMath {
// Functions:
/// @return total amount of tokens
function totalSupply() constant returns (uint256 supply);
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) constant returns (uint256 balance);
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
function transfer(address _to, uint256 _value) returns(bool);
/// @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) returns(bool);
/// @notice `msg.sender` approves `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) returns (bool success);
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) constant returns (uint256 remaining);
// Events:
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract StdToken is Token {
// Fields:
mapping(address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
uint public supply = 0;
// Functions:
function transfer(address _to, uint256 _value) returns(bool) {
require(balances[msg.sender] >= _value);
require(balances[_to] + _value > balances[_to]);
balances[msg.sender] = safeSub(balances[msg.sender],_value);
balances[_to] = safeAdd(balances[_to],_value);
Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) returns(bool){
require(balances[_from] >= _value);
require(allowed[_from][msg.sender] >= _value);
require(balances[_to] + _value > balances[_to]);
balances[_to] = safeAdd(balances[_to],_value);
balances[_from] = safeSub(balances[_from],_value);
allowed[_from][msg.sender] = safeSub(allowed[_from][msg.sender],_value);
Transfer(_from, _to, _value);
return true;
}
function totalSupply() constant returns (uint256) {
return supply;
}
function balanceOf(address _owner) constant returns (uint256) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) returns (bool) {
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender, 0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
require((_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) {
return allowed[_owner][_spender];
}
}
contract ZupplyToken is StdToken
{
/// Fields:
string public constant name = "Zupply Token";
string public constant symbol = "ZUP";
uint public constant decimals = 18;
// this includes DEVELOPERS_BONUS
uint public constant TOTAL_SUPPLY = 750000000 * (1 ether / 1 wei);
uint public constant DEVELOPERS_BONUS = 100000000 * (1 ether / 1 wei);
uint public constant EARLY_INV_BONUS = 50000000 * (1 ether / 1 wei);
uint public constant PRESALE_PRICE = 40000; // per 1 Ether
uint public constant PRESALE_MAX_ETH = 2500;
// 100 mln tokens sold during presale
uint public constant PRESALE_TOKEN_SUPPLY_LIMIT = PRESALE_PRICE * PRESALE_MAX_ETH * (1 ether / 1 wei);
uint public constant ICO_PRICE = 20000; // per 1 Ether
// 600 mln - this includes presale tokens
uint public constant TOTAL_SOLD_TOKEN_SUPPLY_LIMIT = 600000000* (1 ether / 1 wei);
enum State{
Init,
Paused,
PresaleRunning,
PresaleFinished,
ICORunning,
ICOFinished
}
State public currentState = State.Init;
bool public enableTransfers = false;
address public teamTokenBonus = 0;
address public earlyInvestorsBonus = 0;
// Gathered funds can be withdrawn only to escrow's address.
address public escrow = 0;
// Token manager has exclusive priveleges to call administrative
// functions on this contract.
address public tokenManager = 0;
uint public presaleSoldTokens = 0;
uint public icoSoldTokens = 0;
uint public totalSoldTokens = 0;
uint public totalWitdrowedToken = 0;
/// Modifiers:
modifier onlyTokenManager()
{
require(msg.sender==tokenManager);
_;
}
modifier onlyInState(State state)
{
require(state==currentState);
_;
}
/// Events:
event LogBuy(address indexed owner, uint value);
event LogBurn(address indexed owner, uint value);
/// Functions:
/// @dev Constructor
/// @param _tokenManager Token manager address.
function ZupplyToken(address _tokenManager, address _escrow, address _teamTokenBonus, address _eralyInvestorBonus)
{
tokenManager = _tokenManager;
teamTokenBonus = _teamTokenBonus;
escrow = _escrow;
earlyInvestorsBonus = _eralyInvestorBonus;
// send team + early investors bonus immediately
uint teamBonus = DEVELOPERS_BONUS;
balances[_teamTokenBonus] += teamBonus;
uint earlyBonus = EARLY_INV_BONUS;
balances[_eralyInvestorBonus] += earlyBonus;
supply+= teamBonus;
supply+= earlyBonus;
assert(PRESALE_TOKEN_SUPPLY_LIMIT==100000000 * (1 ether / 1 wei));
assert(TOTAL_SOLD_TOKEN_SUPPLY_LIMIT==600000000 * (1 ether / 1 wei));
}
function buyTokens() public payable
{
require(currentState==State.PresaleRunning || currentState==State.ICORunning);
if(currentState==State.PresaleRunning){
return buyTokensPresale();
}else{
return buyTokensICO();
}
}
function buyTokensPresale() public payable onlyInState(State.PresaleRunning)
{
// min - 0.1 ETH
require(msg.value >= (1 ether / 1 wei) /10 );
uint newTokens = msg.value * PRESALE_PRICE;
require(presaleSoldTokens + newTokens + totalWitdrowedToken <= PRESALE_TOKEN_SUPPLY_LIMIT);
balances[msg.sender] += newTokens;
supply+= newTokens;
presaleSoldTokens+= newTokens;
totalSoldTokens+= newTokens;
LogBuy(msg.sender, newTokens);
}
function buyTokensICO() public payable onlyInState(State.ICORunning)
{
// min - 0.01 ETH
require(msg.value >= ((1 ether / 1 wei) / 100));
uint newTokens = msg.value * getPrice();
require(totalSoldTokens + newTokens + totalWitdrowedToken <= TOTAL_SOLD_TOKEN_SUPPLY_LIMIT);
balances[msg.sender] += newTokens;
supply+= newTokens;
icoSoldTokens+= newTokens;
totalSoldTokens+= newTokens;
LogBuy(msg.sender, newTokens);
}
function getPrice()constant returns(uint)
{
if(currentState==State.ICORunning){
return ICO_PRICE;
}else{
return PRESALE_PRICE;
}
}
function setState(State _nextState) public onlyTokenManager
{
//setState() method call shouldn't be entertained after ICOFinished
require(currentState != State.ICOFinished);
currentState = _nextState;
// enable/disable transfers
//enable transfers only after ICOFinished, disable otherwise
enableTransfers = (currentState==State.ICOFinished);
}
function withdrawETH() public onlyTokenManager
{
if(this.balance > 0)
{
require(escrow.send(this.balance));
}
}
function withdrawTokens(uint256 _value) public onlyTokenManager
{
require(currentState == State.ICOFinished);
if((totalSoldTokens + totalWitdrowedToken + _value) <= TOTAL_SOLD_TOKEN_SUPPLY_LIMIT)
{
require(_value <= TOTAL_SOLD_TOKEN_SUPPLY_LIMIT - totalSoldTokens - totalWitdrowedToken);
balances[escrow] += _value;
totalWitdrowedToken += _value;
supply += _value;
}
}
/// Overrides:
function transfer(address _to, uint256 _value) returns(bool){
if(enableTransfers)
return super.transfer(_to,_value);
else
return false;
}
function transferFrom(address _from, address _to, uint256 _value) returns(bool){
if(enableTransfers)
return super.transferFrom(_from,_to,_value);
else
return false;
}
function approve(address _spender, uint256 _value) returns (bool) {
if(enableTransfers)
return super.approve(_spender,_value);
else
return false;
}
/// Setters/getters
function setTokenManager(address _mgr) public onlyTokenManager
{
tokenManager = _mgr;
}
// Default fallback function
function() payable
{
buyTokens();
}
}
| Functions: Constructor _tokenManager Token manager address. send team + early investors bonus immediately | function ZupplyToken(address _tokenManager, address _escrow, address _teamTokenBonus, address _eralyInvestorBonus)
{
tokenManager = _tokenManager;
teamTokenBonus = _teamTokenBonus;
escrow = _escrow;
earlyInvestorsBonus = _eralyInvestorBonus;
uint teamBonus = DEVELOPERS_BONUS;
balances[_teamTokenBonus] += teamBonus;
uint earlyBonus = EARLY_INV_BONUS;
balances[_eralyInvestorBonus] += earlyBonus;
supply+= teamBonus;
supply+= earlyBonus;
assert(PRESALE_TOKEN_SUPPLY_LIMIT==100000000 * (1 ether / 1 wei));
assert(TOTAL_SOLD_TOKEN_SUPPLY_LIMIT==600000000 * (1 ether / 1 wei));
}
| 12,901,493 |
pragma solidity ^0.4.25;
pragma experimental ABIEncoderV2;
library ECTools {
// @dev Recovers the address which has signed a message
// @thanks https://gist.github.com/axic/5b33912c6f61ae6fd96d6c4a47afde6d
function recoverSigner(bytes32 _hashedMsg, string _sig) public pure returns (address) {
require(_hashedMsg != 0x00);
// need this for test RPC
bytes memory prefix = "\x19Ethereum Signed Message:\n32";
bytes32 prefixedHash = keccak256(abi.encodePacked(prefix, _hashedMsg));
if (bytes(_sig).length != 132) {
return 0x0;
}
bytes32 r;
bytes32 s;
uint8 v;
bytes memory sig = hexstrToBytes(substring(_sig, 2, 132));
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
v := byte(0, mload(add(sig, 96)))
}
if (v < 27) {
v += 27;
}
if (v < 27 || v > 28) {
return 0x0;
}
return ecrecover(prefixedHash, v, r, s);
}
// @dev Verifies if the message is signed by an address
function isSignedBy(bytes32 _hashedMsg, string _sig, address _addr) public pure returns (bool) {
require(_addr != 0x0);
return _addr == recoverSigner(_hashedMsg, _sig);
}
// @dev Converts an hexstring to bytes
function hexstrToBytes(string _hexstr) public pure returns (bytes) {
uint len = bytes(_hexstr).length;
require(len % 2 == 0);
bytes memory bstr = bytes(new string(len / 2));
uint k = 0;
string memory s;
string memory r;
for (uint i = 0; i < len; i += 2) {
s = substring(_hexstr, i, i + 1);
r = substring(_hexstr, i + 1, i + 2);
uint p = parseInt16Char(s) * 16 + parseInt16Char(r);
bstr[k++] = uintToBytes32(p)[31];
}
return bstr;
}
// @dev Parses a hexchar, like 'a', and returns its hex value, in this case 10
function parseInt16Char(string _char) public pure returns (uint) {
bytes memory bresult = bytes(_char);
// bool decimals = false;
if ((bresult[0] >= 48) && (bresult[0] <= 57)) {
return uint(bresult[0]) - 48;
} else if ((bresult[0] >= 65) && (bresult[0] <= 70)) {
return uint(bresult[0]) - 55;
} else if ((bresult[0] >= 97) && (bresult[0] <= 102)) {
return uint(bresult[0]) - 87;
} else {
revert();
}
}
// @dev Converts a uint to a bytes32
// @thanks https://ethereum.stackexchange.com/questions/4170/how-to-convert-a-uint-to-bytes-in-solidity
function uintToBytes32(uint _uint) public pure returns (bytes b) {
b = new bytes(32);
assembly {mstore(add(b, 32), _uint)}
}
// @dev Hashes the signed message
// @ref https://github.com/ethereum/go-ethereum/issues/3731#issuecomment-293866868
function toEthereumSignedMessage(string _msg) public pure returns (bytes32) {
uint len = bytes(_msg).length;
require(len > 0);
bytes memory prefix = "\x19Ethereum Signed Message:\n";
return keccak256(abi.encodePacked(prefix, uintToString(len), _msg));
}
// @dev Converts a uint in a string
function uintToString(uint _uint) public pure returns (string str) {
uint len = 0;
uint m = _uint + 0;
while (m != 0) {
len++;
m /= 10;
}
bytes memory b = new bytes(len);
uint i = len - 1;
while (_uint != 0) {
uint remainder = _uint % 10;
_uint = _uint / 10;
b[i--] = byte(48 + remainder);
}
str = string(b);
}
// @dev extract a substring
// @thanks https://ethereum.stackexchange.com/questions/31457/substring-in-solidity
function substring(string _str, uint _startIndex, uint _endIndex) public pure returns (string) {
bytes memory strBytes = bytes(_str);
require(_startIndex <= _endIndex);
require(_startIndex >= 0);
require(_endIndex <= strBytes.length);
bytes memory result = new bytes(_endIndex - _startIndex);
for (uint i = _startIndex; i < _endIndex; i++) {
result[i - _startIndex] = strBytes[i];
}
return string(result);
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title 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;
}
}
contract ChannelManager {
using SafeMath for uint256;
string public constant NAME = "Channel Manager";
string public constant VERSION = "0.0.1";
address public hub;
uint256 public challengePeriod;
ERC20 public approvedToken;
uint256 public totalChannelWei;
uint256 public totalChannelToken;
event DidHubContractWithdraw (
uint256 weiAmount,
uint256 tokenAmount
);
// Note: the payload of DidUpdateChannel contains the state that caused
// the update, not the state post-update (ex, if the update contains a
// deposit, the event's ``pendingDeposit`` field will be present and the
// event's ``balance`` field will not have been updated to reflect that
// balance).
event DidUpdateChannel (
address indexed user,
uint256 senderIdx, // 0: hub, 1: user
uint256[2] weiBalances, // [hub, user]
uint256[2] tokenBalances, // [hub, user]
uint256[4] pendingWeiUpdates, // [hubDeposit, hubWithdrawal, userDeposit, userWithdrawal]
uint256[4] pendingTokenUpdates, // [hubDeposit, hubWithdrawal, userDeposit, userWithdrawal]
uint256[2] txCount, // [global, onchain]
bytes32 threadRoot,
uint256 threadCount
);
// Note: unlike the DidUpdateChannel event, the ``DidStartExitChannel``
// event will contain the channel state after any state that has been
// applied as part of startExitWithUpdate.
event DidStartExitChannel (
address indexed user,
uint256 senderIdx, // 0: hub, 1: user
uint256[2] weiBalances, // [hub, user]
uint256[2] tokenBalances, // [hub, user]
uint256[2] txCount, // [global, onchain]
bytes32 threadRoot,
uint256 threadCount
);
event DidEmptyChannel (
address indexed user,
uint256 senderIdx, // 0: hub, 1: user
uint256[2] weiBalances, // [hub, user]
uint256[2] tokenBalances, // [hub, user]
uint256[2] txCount, // [global, onchain]
bytes32 threadRoot,
uint256 threadCount
);
event DidStartExitThread (
address user,
address indexed sender,
address indexed receiver,
uint256 threadId,
address senderAddress, // either hub or user
uint256[2] weiBalances, // [sender, receiver]
uint256[2] tokenBalances, // [sender, receiver]
uint256 txCount
);
event DidChallengeThread (
address indexed sender,
address indexed receiver,
uint256 threadId,
address senderAddress, // can be either hub, sender, or receiver
uint256[2] weiBalances, // [sender, receiver]
uint256[2] tokenBalances, // [sender, receiver]
uint256 txCount
);
event DidEmptyThread (
address user,
address indexed sender,
address indexed receiver,
uint256 threadId,
address senderAddress, // can be anyone
uint256[2] channelWeiBalances,
uint256[2] channelTokenBalances,
uint256[2] channelTxCount,
bytes32 channelThreadRoot,
uint256 channelThreadCount
);
event DidNukeThreads(
address indexed user,
address senderAddress, // can be anyone
uint256 weiAmount, // amount of wei sent
uint256 tokenAmount, // amount of tokens sent
uint256[2] channelWeiBalances,
uint256[2] channelTokenBalances,
uint256[2] channelTxCount,
bytes32 channelThreadRoot,
uint256 channelThreadCount
);
enum ChannelStatus {
Open,
ChannelDispute,
ThreadDispute
}
struct Channel {
uint256[3] weiBalances; // [hub, user, total]
uint256[3] tokenBalances; // [hub, user, total]
uint256[2] txCount; // persisted onchain even when empty [global, pending]
bytes32 threadRoot;
uint256 threadCount;
address exitInitiator;
uint256 channelClosingTime;
ChannelStatus status;
}
struct Thread {
uint256[2] weiBalances; // [sender, receiver]
uint256[2] tokenBalances; // [sender, receiver]
uint256 txCount; // persisted onchain even when empty
uint256 threadClosingTime;
bool[2] emptied; // [sender, receiver]
}
mapping(address => Channel) public channels;
mapping(address => mapping(address => mapping(uint256 => Thread))) threads; // threads[sender][receiver][threadId]
bool locked;
modifier onlyHub() {
require(msg.sender == hub);
_;
}
modifier noReentrancy() {
require(!locked, "Reentrant call.");
locked = true;
_;
locked = false;
}
constructor(address _hub, uint256 _challengePeriod, address _tokenAddress) public {
hub = _hub;
challengePeriod = _challengePeriod;
approvedToken = ERC20(_tokenAddress);
}
function hubContractWithdraw(uint256 weiAmount, uint256 tokenAmount) public noReentrancy onlyHub {
require(
getHubReserveWei() >= weiAmount,
"hubContractWithdraw: Contract wei funds not sufficient to withdraw"
);
require(
getHubReserveTokens() >= tokenAmount,
"hubContractWithdraw: Contract token funds not sufficient to withdraw"
);
hub.transfer(weiAmount);
require(
approvedToken.transfer(hub, tokenAmount),
"hubContractWithdraw: Token transfer failure"
);
emit DidHubContractWithdraw(weiAmount, tokenAmount);
}
function getHubReserveWei() public view returns (uint256) {
return address(this).balance.sub(totalChannelWei);
}
function getHubReserveTokens() public view returns (uint256) {
return approvedToken.balanceOf(address(this)).sub(totalChannelToken);
}
function hubAuthorizedUpdate(
address user,
address recipient,
uint256[2] weiBalances, // [hub, user]
uint256[2] tokenBalances, // [hub, user]
uint256[4] pendingWeiUpdates, // [hubDeposit, hubWithdrawal, userDeposit, userWithdrawal]
uint256[4] pendingTokenUpdates, // [hubDeposit, hubWithdrawal, userDeposit, userWithdrawal]
uint256[2] txCount, // [global, onchain] persisted onchain even when empty
bytes32 threadRoot,
uint256 threadCount,
uint256 timeout,
string sigUser
) public noReentrancy onlyHub {
Channel storage channel = channels[user];
_verifyAuthorizedUpdate(
channel,
txCount,
weiBalances,
tokenBalances,
pendingWeiUpdates,
pendingTokenUpdates,
timeout,
true
);
_verifySig(
[user, recipient],
weiBalances,
tokenBalances,
pendingWeiUpdates, // [hubDeposit, hubWithdrawal, userDeposit, userWithdrawal]
pendingTokenUpdates, // [hubDeposit, hubWithdrawal, userDeposit, userWithdrawal]
txCount,
threadRoot,
threadCount,
timeout,
"", // skip hub sig verification
sigUser,
[false, true] // [checkHubSig?, checkUser] <- only need to check user
);
_updateChannelBalances(channel, weiBalances, tokenBalances, pendingWeiUpdates, pendingTokenUpdates);
// transfer wei and token to recipient
recipient.transfer(pendingWeiUpdates[3]);
require(approvedToken.transfer(recipient, pendingTokenUpdates[3]), "user token withdrawal transfer failed");
// update state variables
channel.txCount = txCount;
channel.threadRoot = threadRoot;
channel.threadCount = threadCount;
emit DidUpdateChannel(
user,
0, // senderIdx
weiBalances,
tokenBalances,
pendingWeiUpdates,
pendingTokenUpdates,
txCount,
threadRoot,
threadCount
);
}
function userAuthorizedUpdate(
address recipient,
uint256[2] weiBalances, // [hub, user]
uint256[2] tokenBalances, // [hub, user]
uint256[4] pendingWeiUpdates, // [hubDeposit, hubWithdrawal, userDeposit, userWithdrawal]
uint256[4] pendingTokenUpdates, // [hubDeposit, hubWithdrawal, userDeposit, userWithdrawal]
uint256[2] txCount, // persisted onchain even when empty
bytes32 threadRoot,
uint256 threadCount,
uint256 timeout,
string sigHub
) public payable noReentrancy {
require(msg.value == pendingWeiUpdates[2], "msg.value is not equal to pending user deposit");
Channel storage channel = channels[msg.sender];
_verifyAuthorizedUpdate(
channel,
txCount,
weiBalances,
tokenBalances,
pendingWeiUpdates,
pendingTokenUpdates,
timeout,
false
);
_verifySig(
[msg.sender, recipient],
weiBalances,
tokenBalances,
pendingWeiUpdates, // [hubDeposit, hubWithdrawal, userDeposit, userWithdrawal]
pendingTokenUpdates, // [hubDeposit, hubWithdrawal, userDeposit, userWithdrawal]
txCount,
threadRoot,
threadCount,
timeout,
sigHub,
"", // skip user sig verification
[true, false] // [checkHubSig?, checkUser] <- only need to check hub
);
// transfer user token deposit to this contract
require(approvedToken.transferFrom(msg.sender, address(this), pendingTokenUpdates[2]), "user token deposit failed");
_updateChannelBalances(channel, weiBalances, tokenBalances, pendingWeiUpdates, pendingTokenUpdates);
// transfer wei and token to recipient
recipient.transfer(pendingWeiUpdates[3]);
require(approvedToken.transfer(recipient, pendingTokenUpdates[3]), "user token withdrawal transfer failed");
// update state variables
channel.txCount = txCount;
channel.threadRoot = threadRoot;
channel.threadCount = threadCount;
emit DidUpdateChannel(
msg.sender,
1, // senderIdx
weiBalances,
tokenBalances,
pendingWeiUpdates,
pendingTokenUpdates,
channel.txCount,
channel.threadRoot,
channel.threadCount
);
}
/**********************
* Unilateral Functions
*********************/
// start exit with onchain state
function startExit(
address user
) public noReentrancy {
require(user != hub, "user can not be hub");
require(user != address(this), "user can not be channel manager");
Channel storage channel = channels[user];
require(channel.status == ChannelStatus.Open, "channel must be open");
require(msg.sender == hub || msg.sender == user, "exit initiator must be user or hub");
channel.exitInitiator = msg.sender;
channel.channelClosingTime = now.add(challengePeriod);
channel.status = ChannelStatus.ChannelDispute;
emit DidStartExitChannel(
user,
msg.sender == hub ? 0 : 1,
[channel.weiBalances[0], channel.weiBalances[1]],
[channel.tokenBalances[0], channel.tokenBalances[1]],
channel.txCount,
channel.threadRoot,
channel.threadCount
);
}
// start exit with offchain state
function startExitWithUpdate(
address[2] user, // [user, recipient]
uint256[2] weiBalances, // [hub, user]
uint256[2] tokenBalances, // [hub, user]
uint256[4] pendingWeiUpdates, // [hubDeposit, hubWithdrawal, userDeposit, userWithdrawal]
uint256[4] pendingTokenUpdates, // [hubDeposit, hubWithdrawal, userDeposit, userWithdrawal]
uint256[2] txCount, // [global, onchain] persisted onchain even when empty
bytes32 threadRoot,
uint256 threadCount,
uint256 timeout,
string sigHub,
string sigUser
) public noReentrancy {
Channel storage channel = channels[user[0]];
require(channel.status == ChannelStatus.Open, "channel must be open");
require(msg.sender == hub || msg.sender == user[0], "exit initiator must be user or hub");
require(timeout == 0, "can't start exit with time-sensitive states");
_verifySig(
user,
weiBalances,
tokenBalances,
pendingWeiUpdates, // [hubDeposit, hubWithdrawal, userDeposit, userWithdrawal]
pendingTokenUpdates, // [hubDeposit, hubWithdrawal, userDeposit, userWithdrawal]
txCount,
threadRoot,
threadCount,
timeout,
sigHub,
sigUser,
[true, true] // [checkHubSig?, checkUser] <- check both sigs
);
require(txCount[0] > channel.txCount[0], "global txCount must be higher than the current global txCount");
require(txCount[1] >= channel.txCount[1], "onchain txCount must be higher or equal to the current onchain txCount");
// offchain wei/token balances do not exceed onchain total wei/token
require(weiBalances[0].add(weiBalances[1]) <= channel.weiBalances[2], "wei must be conserved");
require(tokenBalances[0].add(tokenBalances[1]) <= channel.tokenBalances[2], "tokens must be conserved");
// pending onchain txs have been executed - force update offchain state to reflect this
if (txCount[1] == channel.txCount[1]) {
_applyPendingUpdates(channel.weiBalances, weiBalances, pendingWeiUpdates);
_applyPendingUpdates(channel.tokenBalances, tokenBalances, pendingTokenUpdates);
// pending onchain txs have *not* been executed - revert pending deposits and withdrawals back into offchain balances
} else { //txCount[1] > channel.txCount[1]
_revertPendingUpdates(channel.weiBalances, weiBalances, pendingWeiUpdates);
_revertPendingUpdates(channel.tokenBalances, tokenBalances, pendingTokenUpdates);
}
// update state variables
// only update txCount[0] (global)
// - txCount[1] should only be updated by user/hubAuthorizedUpdate
channel.txCount[0] = txCount[0];
channel.threadRoot = threadRoot;
channel.threadCount = threadCount;
channel.exitInitiator = msg.sender;
channel.channelClosingTime = now.add(challengePeriod);
channel.status = ChannelStatus.ChannelDispute;
emit DidStartExitChannel(
user[0],
msg.sender == hub ? 0 : 1,
[channel.weiBalances[0], channel.weiBalances[1]],
[channel.tokenBalances[0], channel.tokenBalances[1]],
channel.txCount,
channel.threadRoot,
channel.threadCount
);
}
// party that didn't start exit can challenge and empty
function emptyChannelWithChallenge(
address[2] user,
uint256[2] weiBalances, // [hub, user]
uint256[2] tokenBalances, // [hub, user]
uint256[4] pendingWeiUpdates, // [hubDeposit, hubWithdrawal, userDeposit, userWithdrawal]
uint256[4] pendingTokenUpdates, // [hubDeposit, hubWithdrawal, userDeposit, userWithdrawal]
uint256[2] txCount, // persisted onchain even when empty
bytes32 threadRoot,
uint256 threadCount,
uint256 timeout,
string sigHub,
string sigUser
) public noReentrancy {
Channel storage channel = channels[user[0]];
require(channel.status == ChannelStatus.ChannelDispute, "channel must be in dispute");
require(now < channel.channelClosingTime, "channel closing time must not have passed");
require(msg.sender != channel.exitInitiator, "challenger can not be exit initiator");
require(msg.sender == hub || msg.sender == user[0], "challenger must be either user or hub");
require(timeout == 0, "can't start exit with time-sensitive states");
_verifySig(
user,
weiBalances,
tokenBalances,
pendingWeiUpdates, // [hubDeposit, hubWithdrawal, userDeposit, userWithdrawal]
pendingTokenUpdates, // [hubDeposit, hubWithdrawal, userDeposit, userWithdrawal]
txCount,
threadRoot,
threadCount,
timeout,
sigHub,
sigUser,
[true, true] // [checkHubSig?, checkUser] <- check both sigs
);
require(txCount[0] > channel.txCount[0], "global txCount must be higher than the current global txCount");
require(txCount[1] >= channel.txCount[1], "onchain txCount must be higher or equal to the current onchain txCount");
// offchain wei/token balances do not exceed onchain total wei/token
require(weiBalances[0].add(weiBalances[1]) <= channel.weiBalances[2], "wei must be conserved");
require(tokenBalances[0].add(tokenBalances[1]) <= channel.tokenBalances[2], "tokens must be conserved");
// pending onchain txs have been executed - force update offchain state to reflect this
if (txCount[1] == channel.txCount[1]) {
_applyPendingUpdates(channel.weiBalances, weiBalances, pendingWeiUpdates);
_applyPendingUpdates(channel.tokenBalances, tokenBalances, pendingTokenUpdates);
// pending onchain txs have *not* been executed - revert pending deposits and withdrawals back into offchain balances
} else { //txCount[1] > channel.txCount[1]
_revertPendingUpdates(channel.weiBalances, weiBalances, pendingWeiUpdates);
_revertPendingUpdates(channel.tokenBalances, tokenBalances, pendingTokenUpdates);
}
// deduct hub/user wei/tokens from total channel balances
channel.weiBalances[2] = channel.weiBalances[2].sub(channel.weiBalances[0]).sub(channel.weiBalances[1]);
channel.tokenBalances[2] = channel.tokenBalances[2].sub(channel.tokenBalances[0]).sub(channel.tokenBalances[1]);
// transfer hub wei balance from channel to reserves
totalChannelWei = totalChannelWei.sub(channel.weiBalances[0]).sub(channel.weiBalances[1]);
// transfer user wei balance to user
user[0].transfer(channel.weiBalances[1]);
channel.weiBalances[0] = 0;
channel.weiBalances[1] = 0;
// transfer hub token balance from channel to reserves
totalChannelToken = totalChannelToken.sub(channel.tokenBalances[0]).sub(channel.tokenBalances[1]);
// transfer user token balance to user
require(approvedToken.transfer(user[0], channel.tokenBalances[1]), "user token withdrawal transfer failed");
channel.tokenBalances[0] = 0;
channel.tokenBalances[1] = 0;
// update state variables
// only update txCount[0] (global)
// - txCount[1] should only be updated by user/hubAuthorizedUpdate
channel.txCount[0] = txCount[0];
channel.threadRoot = threadRoot;
channel.threadCount = threadCount;
if (channel.threadCount > 0) {
channel.status = ChannelStatus.ThreadDispute;
} else {
channel.channelClosingTime = 0;
channel.status = ChannelStatus.Open;
}
channel.exitInitiator = address(0x0);
emit DidEmptyChannel(
user[0],
msg.sender == hub ? 0 : 1,
[channel.weiBalances[0], channel.weiBalances[1]],
[channel.tokenBalances[0], channel.tokenBalances[1]],
channel.txCount,
channel.threadRoot,
channel.threadCount
);
}
// after timer expires - anyone can call; even before timer expires, non-exit-initiating party can call
function emptyChannel(
address user
) public noReentrancy {
require(user != hub, "user can not be hub");
require(user != address(this), "user can not be channel manager");
Channel storage channel = channels[user];
require(channel.status == ChannelStatus.ChannelDispute, "channel must be in dispute");
require(
channel.channelClosingTime < now ||
msg.sender != channel.exitInitiator && (msg.sender == hub || msg.sender == user),
"channel closing time must have passed or msg.sender must be non-exit-initiating party"
);
// deduct hub/user wei/tokens from total channel balances
channel.weiBalances[2] = channel.weiBalances[2].sub(channel.weiBalances[0]).sub(channel.weiBalances[1]);
channel.tokenBalances[2] = channel.tokenBalances[2].sub(channel.tokenBalances[0]).sub(channel.tokenBalances[1]);
// transfer hub wei balance from channel to reserves
totalChannelWei = totalChannelWei.sub(channel.weiBalances[0]).sub(channel.weiBalances[1]);
// transfer user wei balance to user
user.transfer(channel.weiBalances[1]);
channel.weiBalances[0] = 0;
channel.weiBalances[1] = 0;
// transfer hub token balance from channel to reserves
totalChannelToken = totalChannelToken.sub(channel.tokenBalances[0]).sub(channel.tokenBalances[1]);
// transfer user token balance to user
require(approvedToken.transfer(user, channel.tokenBalances[1]), "user token withdrawal transfer failed");
channel.tokenBalances[0] = 0;
channel.tokenBalances[1] = 0;
if (channel.threadCount > 0) {
channel.status = ChannelStatus.ThreadDispute;
} else {
channel.channelClosingTime = 0;
channel.status = ChannelStatus.Open;
}
channel.exitInitiator = address(0x0);
emit DidEmptyChannel(
user,
msg.sender == hub ? 0 : 1,
[channel.weiBalances[0], channel.weiBalances[1]],
[channel.tokenBalances[0], channel.tokenBalances[1]],
channel.txCount,
channel.threadRoot,
channel.threadCount
);
}
// **********************
// THREAD DISPUTE METHODS
// **********************
// either party starts exit with initial state
function startExitThread(
address user,
address sender,
address receiver,
uint256 threadId,
uint256[2] weiBalances, // [sender, receiver]
uint256[2] tokenBalances, // [sender, receiver]
bytes proof,
string sig
) public noReentrancy {
Channel storage channel = channels[user];
require(channel.status == ChannelStatus.ThreadDispute, "channel must be in thread dispute phase");
require(msg.sender == hub || msg.sender == user, "thread exit initiator must be user or hub");
require(user == sender || user == receiver, "user must be thread sender or receiver");
require(weiBalances[1] == 0 && tokenBalances[1] == 0, "initial receiver balances must be zero");
Thread storage thread = threads[sender][receiver][threadId];
require(thread.threadClosingTime == 0, "thread closing time must be zero");
_verifyThread(sender, receiver, threadId, weiBalances, tokenBalances, 0, proof, sig, channel.threadRoot);
thread.weiBalances = weiBalances;
thread.tokenBalances = tokenBalances;
thread.threadClosingTime = now.add(challengePeriod);
emit DidStartExitThread(
user,
sender,
receiver,
threadId,
msg.sender,
thread.weiBalances,
thread.tokenBalances,
thread.txCount
);
}
// either party starts exit with offchain state
function startExitThreadWithUpdate(
address user,
address[2] threadMembers, //[sender, receiver]
uint256 threadId,
uint256[2] weiBalances, // [sender, receiver]
uint256[2] tokenBalances, // [sender, receiver]
bytes proof,
string sig,
uint256[2] updatedWeiBalances, // [sender, receiver]
uint256[2] updatedTokenBalances, // [sender, receiver]
uint256 updatedTxCount,
string updateSig
) public noReentrancy {
Channel storage channel = channels[user];
require(channel.status == ChannelStatus.ThreadDispute, "channel must be in thread dispute phase");
require(msg.sender == hub || msg.sender == user, "thread exit initiator must be user or hub");
require(user == threadMembers[0] || user == threadMembers[1], "user must be thread sender or receiver");
require(weiBalances[1] == 0 && tokenBalances[1] == 0, "initial receiver balances must be zero");
Thread storage thread = threads[threadMembers[0]][threadMembers[1]][threadId];
require(thread.threadClosingTime == 0, "thread closing time must be zero");
_verifyThread(threadMembers[0], threadMembers[1], threadId, weiBalances, tokenBalances, 0, proof, sig, channel.threadRoot);
// *********************
// PROCESS THREAD UPDATE
// *********************
require(updatedTxCount > 0, "updated thread txCount must be higher than 0");
require(updatedWeiBalances[0].add(updatedWeiBalances[1]) == weiBalances[0], "sum of updated wei balances must match sender's initial wei balance");
require(updatedTokenBalances[0].add(updatedTokenBalances[1]) == tokenBalances[0], "sum of updated token balances must match sender's initial token balance");
// Note: explicitly set threadRoot == 0x0 because then it doesn't get checked by _isContained (updated state is not part of root)
_verifyThread(threadMembers[0], threadMembers[1], threadId, updatedWeiBalances, updatedTokenBalances, updatedTxCount, "", updateSig, bytes32(0x0));
thread.weiBalances = updatedWeiBalances;
thread.tokenBalances = updatedTokenBalances;
thread.txCount = updatedTxCount;
thread.threadClosingTime = now.add(challengePeriod);
emit DidStartExitThread(
user,
threadMembers[0],
threadMembers[1],
threadId,
msg.sender == hub ? 0 : 1,
thread.weiBalances,
thread.tokenBalances,
thread.txCount
);
}
// either hub, sender, or receiver can update the thread state in place
function challengeThread(
address sender,
address receiver,
uint256 threadId,
uint256[2] weiBalances, // updated weiBalances
uint256[2] tokenBalances, // updated tokenBalances
uint256 txCount,
string sig
) public noReentrancy {
require(msg.sender == hub || msg.sender == sender || msg.sender == receiver, "only hub, sender, or receiver can call this function");
Thread storage thread = threads[sender][receiver][threadId];
//verify that thread settlement period has not yet expired
require(now < thread.threadClosingTime, "thread closing time must not have passed");
// assumes that the non-sender has a later thread state than what was being proposed when the thread exit started
require(txCount > thread.txCount, "thread txCount must be higher than the current thread txCount");
require(weiBalances[0].add(weiBalances[1]) == thread.weiBalances[0].add(thread.weiBalances[1]), "updated wei balances must match sum of thread wei balances");
require(tokenBalances[0].add(tokenBalances[1]) == thread.tokenBalances[0].add(thread.tokenBalances[1]), "updated token balances must match sum of thread token balances");
require(weiBalances[1] >= thread.weiBalances[1] && tokenBalances[1] >= thread.tokenBalances[1], "receiver balances may never decrease");
// Note: explicitly set threadRoot == 0x0 because then it doesn't get checked by _isContained (updated state is not part of root)
_verifyThread(sender, receiver, threadId, weiBalances, tokenBalances, txCount, "", sig, bytes32(0x0));
// save the thread balances and txCount
thread.weiBalances = weiBalances;
thread.tokenBalances = tokenBalances;
thread.txCount = txCount;
emit DidChallengeThread(
sender,
receiver,
threadId,
msg.sender,
thread.weiBalances,
thread.tokenBalances,
thread.txCount
);
}
//After the thread state has been finalized onchain, emptyThread can be called to withdraw funds for each channel separately.
function emptyThread(
address user,
address sender,
address receiver,
uint256 threadId,
uint256[2] weiBalances, // [sender, receiver] -> initial balances
uint256[2] tokenBalances, // [sender, receiver] -> initial balances
bytes proof,
string sig
) public noReentrancy {
Channel storage channel = channels[user];
require(channel.status == ChannelStatus.ThreadDispute, "channel must be in thread dispute");
require(msg.sender == hub || msg.sender == user, "only hub or user can empty thread");
require(user == sender || user == receiver, "user must be thread sender or receiver");
require(weiBalances[1] == 0 && tokenBalances[1] == 0, "initial receiver balances must be zero");
Thread storage thread = threads[sender][receiver][threadId];
// We check to make sure that the thread state has been finalized
require(thread.threadClosingTime != 0 && thread.threadClosingTime < now, "Thread closing time must have passed");
// Make sure user has not emptied before
require(!thread.emptied[user == sender ? 0 : 1], "user cannot empty twice");
// verify initial thread state.
_verifyThread(sender, receiver, threadId, weiBalances, tokenBalances, 0, proof, sig, channel.threadRoot);
require(thread.weiBalances[0].add(thread.weiBalances[1]) == weiBalances[0], "sum of thread wei balances must match sender's initial wei balance");
require(thread.tokenBalances[0].add(thread.tokenBalances[1]) == tokenBalances[0], "sum of thread token balances must match sender's initial token balance");
// deduct sender/receiver wei/tokens about to be emptied from the thread from the total channel balances
channel.weiBalances[2] = channel.weiBalances[2].sub(thread.weiBalances[0]).sub(thread.weiBalances[1]);
channel.tokenBalances[2] = channel.tokenBalances[2].sub(thread.tokenBalances[0]).sub(thread.tokenBalances[1]);
// deduct wei balances from total channel wei and reset thread balances
totalChannelWei = totalChannelWei.sub(thread.weiBalances[0]).sub(thread.weiBalances[1]);
// if user is receiver, send them receiver wei balance
if (user == receiver) {
user.transfer(thread.weiBalances[1]);
// if user is sender, send them remaining sender wei balance
} else if (user == sender) {
user.transfer(thread.weiBalances[0]);
}
// deduct token balances from channel total balances and reset thread balances
totalChannelToken = totalChannelToken.sub(thread.tokenBalances[0]).sub(thread.tokenBalances[1]);
// if user is receiver, send them receiver token balance
if (user == receiver) {
require(approvedToken.transfer(user, thread.tokenBalances[1]), "user [receiver] token withdrawal transfer failed");
// if user is sender, send them remaining sender token balance
} else if (user == sender) {
require(approvedToken.transfer(user, thread.tokenBalances[0]), "user [sender] token withdrawal transfer failed");
}
// Record that user has emptied
thread.emptied[user == sender ? 0 : 1] = true;
// decrement the channel threadCount
channel.threadCount = channel.threadCount.sub(1);
// if this is the last thread being emptied, re-open the channel
if (channel.threadCount == 0) {
channel.threadRoot = bytes32(0x0);
channel.channelClosingTime = 0;
channel.status = ChannelStatus.Open;
}
emit DidEmptyThread(
user,
sender,
receiver,
threadId,
msg.sender,
[channel.weiBalances[0], channel.weiBalances[1]],
[channel.tokenBalances[0], channel.tokenBalances[1]],
channel.txCount,
channel.threadRoot,
channel.threadCount
);
}
// anyone can call to re-open an account stuck in threadDispute after 10x challengePeriods from channel state finalization
function nukeThreads(
address user
) public noReentrancy {
require(user != hub, "user can not be hub");
require(user != address(this), "user can not be channel manager");
Channel storage channel = channels[user];
require(channel.status == ChannelStatus.ThreadDispute, "channel must be in thread dispute");
require(channel.channelClosingTime.add(challengePeriod.mul(10)) < now, "channel closing time must have passed by 10 challenge periods");
// transfer any remaining channel wei to user
totalChannelWei = totalChannelWei.sub(channel.weiBalances[2]);
user.transfer(channel.weiBalances[2]);
uint256 weiAmount = channel.weiBalances[2];
channel.weiBalances[2] = 0;
// transfer any remaining channel tokens to user
totalChannelToken = totalChannelToken.sub(channel.tokenBalances[2]);
require(approvedToken.transfer(user, channel.tokenBalances[2]), "user token withdrawal transfer failed");
uint256 tokenAmount = channel.tokenBalances[2];
channel.tokenBalances[2] = 0;
// reset channel params
channel.threadCount = 0;
channel.threadRoot = bytes32(0x0);
channel.channelClosingTime = 0;
channel.status = ChannelStatus.Open;
emit DidNukeThreads(
user,
msg.sender,
weiAmount,
tokenAmount,
[channel.weiBalances[0], channel.weiBalances[1]],
[channel.tokenBalances[0], channel.tokenBalances[1]],
channel.txCount,
channel.threadRoot,
channel.threadCount
);
}
function() external payable {}
// ******************
// INTERNAL FUNCTIONS
// ******************
function _verifyAuthorizedUpdate(
Channel storage channel,
uint256[2] txCount,
uint256[2] weiBalances,
uint256[2] tokenBalances, // [hub, user]
uint256[4] pendingWeiUpdates, // [hubDeposit, hubWithdrawal, userDeposit, userWithdrawal]
uint256[4] pendingTokenUpdates, // [hubDeposit, hubWithdrawal, userDeposit, userWithdrawal]
uint256 timeout,
bool isHub
) internal view {
require(channel.status == ChannelStatus.Open, "channel must be open");
// Usage:
// 1. exchange operations to protect user from exchange rate fluctuations
// 2. protects hub against user delaying forever
require(timeout == 0 || now < timeout, "the timeout must be zero or not have passed");
require(txCount[0] > channel.txCount[0], "global txCount must be higher than the current global txCount");
require(txCount[1] >= channel.txCount[1], "onchain txCount must be higher or equal to the current onchain txCount");
// offchain wei/token balances do not exceed onchain total wei/token
require(weiBalances[0].add(weiBalances[1]) <= channel.weiBalances[2], "wei must be conserved");
require(tokenBalances[0].add(tokenBalances[1]) <= channel.tokenBalances[2], "tokens must be conserved");
// hub has enough reserves for wei/token deposits for both the user and itself (if isHub, user deposit comes from hub)
if (isHub) {
require(pendingWeiUpdates[0].add(pendingWeiUpdates[2]) <= getHubReserveWei(), "insufficient reserve wei for deposits");
require(pendingTokenUpdates[0].add(pendingTokenUpdates[2]) <= getHubReserveTokens(), "insufficient reserve tokens for deposits");
// hub has enough reserves for only its own wei/token deposits
} else {
require(pendingWeiUpdates[0] <= getHubReserveWei(), "insufficient reserve wei for deposits");
require(pendingTokenUpdates[0] <= getHubReserveTokens(), "insufficient reserve tokens for deposits");
}
// wei is conserved - the current total channel wei + both deposits > final balances + both withdrawals
require(channel.weiBalances[2].add(pendingWeiUpdates[0]).add(pendingWeiUpdates[2]) >=
weiBalances[0].add(weiBalances[1]).add(pendingWeiUpdates[1]).add(pendingWeiUpdates[3]), "insufficient wei");
// token is conserved - the current total channel token + both deposits > final balances + both withdrawals
require(channel.tokenBalances[2].add(pendingTokenUpdates[0]).add(pendingTokenUpdates[2]) >=
tokenBalances[0].add(tokenBalances[1]).add(pendingTokenUpdates[1]).add(pendingTokenUpdates[3]), "insufficient token");
}
function _applyPendingUpdates(
uint256[3] storage channelBalances,
uint256[2] balances,
uint256[4] pendingUpdates
) internal {
// update hub balance
// If the deposit is greater than the withdrawal, add the net of deposit minus withdrawal to the balances.
// Assumes the net has *not yet* been added to the balances.
if (pendingUpdates[0] > pendingUpdates[1]) {
channelBalances[0] = balances[0].add(pendingUpdates[0].sub(pendingUpdates[1]));
// Otherwise, if the deposit is less than or equal to the withdrawal,
// Assumes the net has *already* been added to the balances.
} else {
channelBalances[0] = balances[0];
}
// update user balance
// If the deposit is greater than the withdrawal, add the net of deposit minus withdrawal to the balances.
// Assumes the net has *not yet* been added to the balances.
if (pendingUpdates[2] > pendingUpdates[3]) {
channelBalances[1] = balances[1].add(pendingUpdates[2].sub(pendingUpdates[3]));
// Otherwise, if the deposit is less than or equal to the withdrawal,
// Assumes the net has *already* been added to the balances.
} else {
channelBalances[1] = balances[1];
}
}
function _revertPendingUpdates(
uint256[3] storage channelBalances,
uint256[2] balances,
uint256[4] pendingUpdates
) internal {
// If the pending update has NOT been executed AND deposits > withdrawals, offchain state was NOT updated with delta, and is thus correct
if (pendingUpdates[0] > pendingUpdates[1]) {
channelBalances[0] = balances[0];
// If the pending update has NOT been executed AND deposits < withdrawals, offchain state should have been updated with delta, and must be reverted
} else {
channelBalances[0] = balances[0].add(pendingUpdates[1].sub(pendingUpdates[0])); // <- add withdrawal, sub deposit (opposite order as _applyPendingUpdates)
}
// If the pending update has NOT been executed AND deposits > withdrawals, offchain state was NOT updated with delta, and is thus correct
if (pendingUpdates[2] > pendingUpdates[3]) {
channelBalances[1] = balances[1];
// If the pending update has NOT been executed AND deposits > withdrawals, offchain state should have been updated with delta, and must be reverted
} else {
channelBalances[1] = balances[1].add(pendingUpdates[3].sub(pendingUpdates[2])); // <- add withdrawal, sub deposit (opposite order as _applyPendingUpdates)
}
}
function _updateChannelBalances(
Channel storage channel,
uint256[2] weiBalances,
uint256[2] tokenBalances,
uint256[4] pendingWeiUpdates,
uint256[4] pendingTokenUpdates
) internal {
_applyPendingUpdates(channel.weiBalances, weiBalances, pendingWeiUpdates);
_applyPendingUpdates(channel.tokenBalances, tokenBalances, pendingTokenUpdates);
totalChannelWei = totalChannelWei.add(pendingWeiUpdates[0]).add(pendingWeiUpdates[2]).sub(pendingWeiUpdates[1]).sub(pendingWeiUpdates[3]);
totalChannelToken = totalChannelToken.add(pendingTokenUpdates[0]).add(pendingTokenUpdates[2]).sub(pendingTokenUpdates[1]).sub(pendingTokenUpdates[3]);
// update channel total balances
channel.weiBalances[2] = channel.weiBalances[2].add(pendingWeiUpdates[0]).add(pendingWeiUpdates[2]).sub(pendingWeiUpdates[1]).sub(pendingWeiUpdates[3]);
channel.tokenBalances[2] = channel.tokenBalances[2].add(pendingTokenUpdates[0]).add(pendingTokenUpdates[2]).sub(pendingTokenUpdates[1]).sub(pendingTokenUpdates[3]);
}
function _verifySig (
address[2] user, // [user, recipient]
uint256[2] weiBalances, // [hub, user]
uint256[2] tokenBalances, // [hub, user]
uint256[4] pendingWeiUpdates, // [hubDeposit, hubWithdrawal, userDeposit, userWithdrawal]
uint256[4] pendingTokenUpdates, // [hubDeposit, hubWithdrawal, userDeposit, userWithdrawal]
uint256[2] txCount, // [global, onchain] persisted onchain even when empty
bytes32 threadRoot,
uint256 threadCount,
uint256 timeout,
string sigHub,
string sigUser,
bool[2] checks // [checkHubSig?, checkUserSig?]
) internal view {
require(user[0] != hub, "user can not be hub");
require(user[0] != address(this), "user can not be channel manager");
// prepare state hash to check hub sig
bytes32 state = keccak256(
abi.encodePacked(
address(this),
user, // [user, recipient]
weiBalances, // [hub, user]
tokenBalances, // [hub, user]
pendingWeiUpdates, // [hubDeposit, hubWithdrawal, userDeposit, userWithdrawal]
pendingTokenUpdates, // [hubDeposit, hubWithdrawal, userDeposit, userWithdrawal]
txCount, // persisted onchain even when empty
threadRoot,
threadCount,
timeout
)
);
if (checks[0]) {
require(hub == ECTools.recoverSigner(state, sigHub), "hub signature invalid");
}
if (checks[1]) {
require(user[0] == ECTools.recoverSigner(state, sigUser), "user signature invalid");
}
}
function _verifyThread(
address sender,
address receiver,
uint256 threadId,
uint256[2] weiBalances,
uint256[2] tokenBalances,
uint256 txCount,
bytes proof,
string sig,
bytes32 threadRoot
) internal view {
require(sender != receiver, "sender can not be receiver");
require(sender != hub && receiver != hub, "hub can not be sender or receiver");
require(sender != address(this) && receiver != address(this), "channel manager can not be sender or receiver");
bytes32 state = keccak256(
abi.encodePacked(
address(this),
sender,
receiver,
threadId,
weiBalances, // [sender, receiver]
tokenBalances, // [sender, receiver]
txCount // persisted onchain even when empty
)
);
require(ECTools.isSignedBy(state, sig, sender), "signature invalid");
if (threadRoot != bytes32(0x0)) {
require(_isContained(state, proof, threadRoot), "initial thread state is not contained in threadRoot");
}
}
function _isContained(bytes32 _hash, bytes _proof, bytes32 _root) internal pure returns (bool) {
bytes32 cursor = _hash;
bytes32 proofElem;
for (uint256 i = 64; i <= _proof.length; i += 32) {
assembly { proofElem := mload(add(_proof, i)) }
if (cursor < proofElem) {
cursor = keccak256(abi.encodePacked(cursor, proofElem));
} else {
cursor = keccak256(abi.encodePacked(proofElem, cursor));
}
}
return cursor == _root;
}
function getChannelBalances(address user) constant public returns (
uint256 weiHub,
uint256 weiUser,
uint256 weiTotal,
uint256 tokenHub,
uint256 tokenUser,
uint256 tokenTotal
) {
Channel memory channel = channels[user];
return (
channel.weiBalances[0],
channel.weiBalances[1],
channel.weiBalances[2],
channel.tokenBalances[0],
channel.tokenBalances[1],
channel.tokenBalances[2]
);
}
function getChannelDetails(address user) constant public returns (
uint256 txCountGlobal,
uint256 txCountChain,
bytes32 threadRoot,
uint256 threadCount,
address exitInitiator,
uint256 channelClosingTime,
ChannelStatus status
) {
Channel memory channel = channels[user];
return (
channel.txCount[0],
channel.txCount[1],
channel.threadRoot,
channel.threadCount,
channel.exitInitiator,
channel.channelClosingTime,
channel.status
);
}
}
| prepare state hash to check hub sig | function _verifySig (
bytes32 threadRoot,
uint256 threadCount,
uint256 timeout,
string sigHub,
string sigUser,
) internal view {
require(user[0] != hub, "user can not be hub");
require(user[0] != address(this), "user can not be channel manager");
bytes32 state = keccak256(
abi.encodePacked(
address(this),
threadRoot,
threadCount,
timeout
)
);
if (checks[0]) {
require(hub == ECTools.recoverSigner(state, sigHub), "hub signature invalid");
}
if (checks[1]) {
require(user[0] == ECTools.recoverSigner(state, sigUser), "user signature invalid");
}
}
| 2,512,697 |
./full_match/5/0xd0CE2928FFb72B16c0BeF339b99db50ee487C8A2/sources/contracts/claim/abstract/AdvancedDistributor.sol | disable unused ERC20 methods: the token is only used to track voting power | function _approve(address, address, uint256) internal pure override {
revert("disabled for voting power");
}
| 1,871,440 |
pragma solidity ^0.6.12;
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this;
return msg.data;
}
}
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
);
}
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;
}
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 Address {
function isContract(address account) internal view returns (bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
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"
);
(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 {
if (returndata.length > 0) {
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
constructor() internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
function owner() public view returns (address) {
return _owner;
}
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
function transferOwnership(address newOwner) public virtual onlyOwner {
require(
newOwner != address(0),
"Ownable: new owner is the zero address"
);
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
interface IUniswapV2Factory {
function createPair(address tokenA, address tokenB)
external
returns (address pair);
}
interface IUniswapV2Pair {
function sync() external;
}
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
);
}
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountETH);
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
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;
}
// change "name1" into ur name
contract Pawthereum is Context, IERC20, Ownable {
using SafeMath for uint256;
using Address for address;
//change "name1" and "symbol"
string private _name = "Pawthereum";
string private _symbol = "PAWTH";
uint8 private _decimals = 9;
mapping(address => uint256) internal _reflectionBalance;
mapping(address => uint256) internal _tokenBalance;
mapping(address => mapping(address => uint256)) internal _allowances;
uint256 private constant MAX = ~uint256(0);
// change this for total supply (100e8 = 100) (100000000e8 = 100000000) (dont forget the e8 it has to be there)
uint256 internal _tokenTotal = 1000000000e9;
// change this for total supply ^^^^^^^^^^^^^^^^^^^^^
uint256 internal _reflectionTotal = (MAX - (MAX % _tokenTotal));
mapping(address => bool) isTaxless;
mapping(address => bool) internal _isExcluded;
address[] internal _excluded;
uint256 public _feeDecimal = 2;
// thats the distribution to holders (400 = 4%)
uint256 public _taxFee = 200;
// thats the amount for liquidity pool
uint256 public _liquidityFee = 100;
// this amount gets burned by every transaction
uint256 public _burnFee = 0;
// this goes to the marketing wallet (line 403)
uint256 public _marketingFee = 100;
// this goes to the charity wallet
uint256 public _charityFee = 200;
uint256 public _taxFeeTotal;
uint256 public _burnFeeTotal;
uint256 public _liquidityFeeTotal;
uint256 public _marketingFeeTotal;
uint256 public _charityFeeTotal;
address public marketingWallet;
address public charityWallet;
bool public isTaxActive = true;
bool private inSwapAndLiquify;
bool public swapAndLiquifyEnabled = true;
uint256 public maxTxAmount = _tokenTotal;
uint256 public minTokensBeforeSwap = 10_000e9;
IUniswapV2Router02 public uniswapV2Router;
address public uniswapV2Pair;
event SwapAndLiquifyEnabledUpdated(bool enabled);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiqudity
);
modifier lockTheSwap() {
inSwapAndLiquify = true;
_;
inSwapAndLiquify = false;
}
constructor() public {
marketingWallet = 0x6DFcd4331b0d86bfe0318706C76B832dA4C03C1B;
charityWallet = 0xa56891cfBd0175E6Fc46Bf7d647DE26100e95C78;
isTaxless[_msgSender()] = true;
isTaxless[address(this)] = true;
_reflectionBalance[_msgSender()] = _reflectionTotal;
emit Transfer(address(0), _msgSender(), _tokenTotal);
}
function init() external onlyOwner {
// IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x10ED43C718714eb63d5aA57B78B54704E256024E); // for BSC
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(
0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D
); // for Ethereum
// IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x1b02dA8Cb0d097eB8D57A175b88c7D8b47997506); // for Sushi testnet
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router = _uniswapV2Router;
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _tokenTotal;
}
function balanceOf(address account) public view override returns (uint256) {
if (_isExcluded[account]) return _tokenBalance[account];
return tokenFromReflection(_reflectionBalance[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
override
returns (uint256)
{
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount)
public
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);
_approve(
sender,
_msgSender(),
_allowances[sender][_msgSender()].sub(
amount,
"ERC20: transfer amount exceeds allowance"
)
);
return true;
}
function increaseAllowance(address spender, uint256 addedValue)
public
virtual
returns (bool)
{
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].add(addedValue)
);
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 isExcluded(address account) public view returns (bool) {
return _isExcluded[account];
}
function reflectionFromToken(uint256 tokenAmount, bool deductTransferFee)
public
view
returns (uint256)
{
require(tokenAmount <= _tokenTotal, "Amount must be less than supply");
if (!deductTransferFee) {
return tokenAmount.mul(_getReflectionRate());
} else {
return
tokenAmount
.sub(tokenAmount.mul(_taxFee).div(10**_feeDecimal + 2))
.mul(_getReflectionRate());
}
}
function tokenFromReflection(uint256 reflectionAmount)
public
view
returns (uint256)
{
require(
reflectionAmount <= _reflectionTotal,
"Amount must be less than total reflections"
);
uint256 currentRate = _getReflectionRate();
return reflectionAmount.div(currentRate);
}
function excludeAccount(address account) external onlyOwner {
require(
account != address(uniswapV2Router),
"ERC20: We can not exclude Uniswap router."
);
require(!_isExcluded[account], "ERC20: Account is already excluded");
if (_reflectionBalance[account] > 0) {
_tokenBalance[account] = tokenFromReflection(
_reflectionBalance[account]
);
}
_isExcluded[account] = true;
_excluded.push(account);
}
function includeAccount(address account) external onlyOwner {
require(_isExcluded[account], "ERC20: Account is already included");
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tokenBalance[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
function _approve(
address owner,
address spender,
uint256 amount
) private {
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 _transfer(
address sender,
address recipient,
uint256 amount
) private {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
require(amount <= maxTxAmount, "Transfer Limit exceeded!");
uint256 contractTokenBalance = balanceOf(address(this));
bool overMinTokenBalance = contractTokenBalance >= minTokensBeforeSwap;
if (
!inSwapAndLiquify &&
overMinTokenBalance &&
sender != uniswapV2Pair &&
swapAndLiquifyEnabled
) {
swapAndLiquify(contractTokenBalance);
}
uint256 transferAmount = amount;
uint256 rate = _getReflectionRate();
if (
isTaxActive &&
!isTaxless[_msgSender()] &&
!isTaxless[recipient] &&
!inSwapAndLiquify
) {
transferAmount = collectFee(sender, amount, rate);
}
_reflectionBalance[sender] = _reflectionBalance[sender].sub(
amount.mul(rate)
);
_reflectionBalance[recipient] = _reflectionBalance[recipient].add(
transferAmount.mul(rate)
);
if (_isExcluded[sender]) {
_tokenBalance[sender] = _tokenBalance[sender].sub(amount);
}
if (_isExcluded[recipient]) {
_tokenBalance[recipient] = _tokenBalance[recipient].add(
transferAmount
);
}
emit Transfer(sender, recipient, transferAmount);
}
function collectFee(
address account,
uint256 amount,
uint256 rate
) private returns (uint256) {
uint256 transferAmount = amount;
//@dev tax fee
if (_taxFee != 0) {
uint256 taxFee = amount.mul(_taxFee).div(10**(_feeDecimal + 2));
transferAmount = transferAmount.sub(taxFee);
_reflectionTotal = _reflectionTotal.sub(taxFee.mul(rate));
_taxFeeTotal = _taxFeeTotal.add(taxFee);
}
//@dev liquidity fee
if (_liquidityFee != 0) {
uint256 liquidityFee = amount.mul(_liquidityFee).div(
10**(_feeDecimal + 2)
);
transferAmount = transferAmount.sub(liquidityFee);
_reflectionBalance[address(this)] = _reflectionBalance[
address(this)
].add(liquidityFee.mul(rate));
if (_isExcluded[address(this)]) {
_tokenBalance[address(this)] = _tokenBalance[address(this)].add(
liquidityFee
);
}
_liquidityFeeTotal = _liquidityFeeTotal.add(liquidityFee);
emit Transfer(account, address(this), liquidityFee);
}
//@dev burn fee
if (_burnFee != 0) {
uint256 burnFee = amount.mul(_burnFee).div(10**(_feeDecimal + 2));
transferAmount = transferAmount.sub(burnFee);
_tokenTotal = _tokenTotal.sub(burnFee);
_reflectionTotal = _reflectionTotal.sub(burnFee.mul(rate));
_burnFeeTotal = _burnFeeTotal.add(burnFee);
emit Transfer(account, address(0), burnFee);
}
//@dev Marketing fee
if (_marketingFee != 0) {
uint256 marketingFee = amount.mul(_marketingFee).div(
10**(_feeDecimal + 2)
);
transferAmount = transferAmount.sub(marketingFee);
_reflectionBalance[marketingWallet] = _reflectionBalance[
marketingWallet
].add(marketingFee.mul(rate));
if (_isExcluded[marketingWallet]) {
_tokenBalance[marketingWallet] = _tokenBalance[marketingWallet]
.add(marketingFee);
}
_marketingFeeTotal = _marketingFeeTotal.add(marketingFee);
emit Transfer(account, marketingWallet, marketingFee);
}
//@dev Charity fee
if (_charityFee != 0) {
uint256 charityFee = amount.mul(_charityFee).div(
10**(_feeDecimal + 2)
);
transferAmount = transferAmount.sub(charityFee);
_reflectionBalance[charityWallet] = _reflectionBalance[
charityWallet
].add(charityFee.mul(rate));
if (_isExcluded[charityWallet]) {
_tokenBalance[charityWallet] = _tokenBalance[charityWallet].add(
charityFee
);
}
_charityFeeTotal = _charityFeeTotal.add(charityFee);
emit Transfer(account, charityWallet, charityFee);
}
return transferAmount;
}
function _getReflectionRate() private view returns (uint256) {
uint256 reflectionSupply = _reflectionTotal;
uint256 tokenSupply = _tokenTotal;
for (uint256 i = 0; i < _excluded.length; i++) {
if (
_reflectionBalance[_excluded[i]] > reflectionSupply ||
_tokenBalance[_excluded[i]] > tokenSupply
) return _reflectionTotal.div(_tokenTotal);
reflectionSupply = reflectionSupply.sub(
_reflectionBalance[_excluded[i]]
);
tokenSupply = tokenSupply.sub(_tokenBalance[_excluded[i]]);
}
if (reflectionSupply < _reflectionTotal.div(_tokenTotal))
return _reflectionTotal.div(_tokenTotal);
return reflectionSupply.div(tokenSupply);
}
function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap {
if (contractTokenBalance > maxTxAmount)
contractTokenBalance = maxTxAmount;
uint256 half = contractTokenBalance.div(2);
uint256 otherHalf = contractTokenBalance.sub(half);
uint256 initialBalance = address(this).balance;
swapTokensForEth(half);
uint256 newBalance = address(this).balance.sub(initialBalance);
addLiquidity(otherHalf, newBalance);
emit SwapAndLiquify(half, newBalance, otherHalf);
}
function swapTokensForEth(uint256 tokenAmount) private {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0,
path,
address(this),
block.timestamp
);
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.addLiquidityETH{value: ethAmount}(
address(this),
tokenAmount,
0,
0,
address(this),
block.timestamp
);
}
function setPair(address pair) external onlyOwner {
uniswapV2Pair = pair;
}
function setMarketingWallet(address account) external onlyOwner {
marketingWallet = account;
}
function setCharityWallet(address account) external onlyOwner {
charityWallet = account;
}
function setTaxless(address account, bool value) external onlyOwner {
isTaxless[account] = value;
}
function setSwapAndLiquifyEnabled(bool enabled) external onlyOwner {
swapAndLiquifyEnabled = enabled;
SwapAndLiquifyEnabledUpdated(enabled);
}
function setTaxActive(bool value) external onlyOwner {
isTaxActive = value;
}
function setTaxFee(uint256 fee) external onlyOwner {
require(fee <= 200, "You can't set reflections fee above 2 percent.");
_taxFee = fee;
}
function setBurnFee(uint256 fee) external onlyOwner {
require(fee <= 200, "You can't set burn fees above 2 percent.");
_burnFee = fee;
}
function setLiquidityFee(uint256 fee) external onlyOwner {
require(fee <= 200, "You can't set this fee above 2 percent.");
_liquidityFee = fee;
}
function setMarketingFee(uint256 fee) external onlyOwner {
require(fee <= 200, "You can't set the marketing fee above 2 percent.");
_marketingFee = fee;
}
function setCharityFee(uint256 fee) external onlyOwner {
require(fee <= 200, "You can't set the charity fee above 2 percent.");
_charityFee = fee;
}
function setMaxTxAmount(uint256 amount) external onlyOwner {
maxTxAmount = amount;
}
function setMinTokensBeforeSwap(uint256 amount) external onlyOwner {
minTokensBeforeSwap = amount;
}
receive() external payable {}
}
| IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x10ED43C718714eb63d5aA57B78B54704E256024E); for BSC IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x1b02dA8Cb0d097eB8D57A175b88c7D8b47997506); for Sushi testnet | function init() external onlyOwner {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(
0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router = _uniswapV2Router;
}
| 214,209 |
pragma solidity ^0.5.11;
pragma experimental ABIEncoderV2;
import './ForceMoveApp.sol';
contract ForceMove {
struct Signature {
uint8 v;
bytes32 r;
bytes32 s;
}
struct FixedPart {
uint256 chainId;
address[] participants;
uint256 channelNonce;
address appDefinition;
uint256 challengeDuration;
}
struct State {
// participants sign the hash of this
uint256 turnNum;
bool isFinal;
bytes32 channelId; // keccack(chainId,participants,channelNonce)
bytes32 appPartHash;
// keccak256(abi.encode(
// fixedPart.challengeDuration,
// fixedPart.appDefinition,
// variablePart.appData
// )
// )
bytes32 outcomeHash;
}
struct ChannelStorage {
uint256 turnNumRecord;
uint256 finalizesAt;
bytes32 stateHash; // keccak256(abi.encode(State))
address challengerAddress;
bytes32 outcomeHash;
}
enum ChannelMode {Open, Challenge, Finalized}
mapping(bytes32 => bytes32) public channelStorageHashes;
// Public methods:
function getData(bytes32 channelId)
public
view
returns (uint48 finalizesAt, uint48 turnNumRecord, uint160 fingerprint)
{
(turnNumRecord, finalizesAt, fingerprint) = _getData(channelId);
}
function forceMove(
FixedPart memory fixedPart,
uint48 largestTurnNum,
ForceMoveApp.VariablePart[] memory variableParts,
uint8 isFinalCount, // how many of the states are final
Signature[] memory sigs,
uint8[] memory whoSignedWhat,
Signature memory challengerSig
) public {
bytes32 channelId = _getChannelId(fixedPart);
// ------------
// REQUIREMENTS
// ------------
_requireNonDecreasedTurnNumber(channelId, largestTurnNum);
_requireChannelNotFinalized(channelId);
bytes32 supportedStateHash = _requireStateSupportedBy(
largestTurnNum,
variableParts,
isFinalCount,
channelId,
fixedPart,
sigs,
whoSignedWhat
);
address challenger = _requireThatChallengerIsParticipant(
supportedStateHash,
fixedPart.participants,
challengerSig
);
// ------------
// EFFECTS
// ------------
emit ChallengeRegistered(
channelId,
largestTurnNum,
now + fixedPart.challengeDuration,
challenger,
isFinalCount > 0,
fixedPart,
variableParts
);
channelStorageHashes[channelId] = _hashChannelStorage(
ChannelStorage(
largestTurnNum,
now + fixedPart.challengeDuration,
supportedStateHash,
challenger,
keccak256(abi.encode(variableParts[variableParts.length - 1].outcome))
)
);
}
function respond(
address challenger,
bool[2] memory isFinalAB,
FixedPart memory fixedPart,
ForceMoveApp.VariablePart[2] memory variablePartAB,
// variablePartAB[0] = challengeVariablePart
// variablePartAB[1] = responseVariablePart
Signature memory sig
) public {
bytes32 channelId = _getChannelId(fixedPart);
(uint48 turnNumRecord, uint48 finalizesAt, ) = _getData(channelId);
bytes32 challengeOutcomeHash = _hashOutcome(variablePartAB[0].outcome);
bytes32 responseOutcomeHash = _hashOutcome(variablePartAB[1].outcome);
bytes32 challengeStateHash = _hashState(
turnNumRecord,
isFinalAB[0],
channelId,
fixedPart,
variablePartAB[0].appData,
challengeOutcomeHash
);
bytes32 responseStateHash = _hashState(
turnNumRecord + 1,
isFinalAB[1],
channelId,
fixedPart,
variablePartAB[1].appData,
responseOutcomeHash
);
// requirements
_requireSpecificChallenge(
ChannelStorage(
turnNumRecord,
finalizesAt,
challengeStateHash,
challenger,
challengeOutcomeHash
),
channelId
);
require(
_recoverSigner(responseStateHash, sig) ==
fixedPart.participants[(turnNumRecord + 1) % fixedPart.participants.length],
'Response not signed by authorized mover'
);
_requireValidTransition(
fixedPart.participants.length,
isFinalAB,
variablePartAB,
turnNumRecord + 1,
fixedPart.appDefinition
);
// effects
_clearChallenge(channelId, turnNumRecord + 1);
}
function refute(
uint48 refutationStateTurnNum,
address challenger,
bool[2] memory isFinalAB,
FixedPart memory fixedPart,
ForceMoveApp.VariablePart[2] memory variablePartAB,
// variablePartAB[0] = challengeVariablePart
// variablePartAB[1] = refutationVariablePart
Signature memory refutationStateSig
) public {
// requirements
bytes32 channelId = _getChannelId(fixedPart);
(uint48 turnNumRecord, uint48 finalizesAt, ) = _getData(channelId);
_requireIncreasedTurnNumber(channelId, refutationStateTurnNum);
bytes32 challengeOutcomeHash = keccak256(abi.encode(variablePartAB[0].outcome));
bytes32 refutationOutcomeHash = keccak256(abi.encode(variablePartAB[1].outcome));
bytes32 challengeStateHash = _hashState(
turnNumRecord,
isFinalAB[0],
channelId,
fixedPart,
variablePartAB[0].appData,
challengeOutcomeHash
);
bytes32 refutationStateHash = _hashState(
refutationStateTurnNum,
isFinalAB[1],
channelId,
fixedPart,
variablePartAB[1].appData,
refutationOutcomeHash
);
_requireSpecificChallenge(
ChannelStorage(
turnNumRecord,
finalizesAt,
challengeStateHash,
challenger, // this is a check that the asserted challenger is in fact the challenger
challengeOutcomeHash
),
channelId
);
require(
_recoverSigner(refutationStateHash, refutationStateSig) == challenger,
'Refutation state not signed by challenger'
);
// effects
_clearChallenge(channelId, turnNumRecord);
}
function checkpoint(
FixedPart memory fixedPart,
uint48 largestTurnNum,
ForceMoveApp.VariablePart[] memory variableParts,
uint8 isFinalCount, // how many of the states are final
Signature[] memory sigs,
uint8[] memory whoSignedWhat
) public {
bytes32 channelId = _getChannelId(fixedPart);
// ------------
// REQUIREMENTS
// ------------
_requireChannelNotFinalized(channelId);
_requireIncreasedTurnNumber(channelId, largestTurnNum);
_requireStateSupportedBy(
largestTurnNum,
variableParts,
isFinalCount,
channelId,
fixedPart,
sigs,
whoSignedWhat
);
// effects
_clearChallenge(channelId, largestTurnNum);
}
function conclude(
uint48 largestTurnNum,
FixedPart memory fixedPart,
bytes32 appPartHash,
bytes32 outcomeHash,
uint8 numStates,
uint8[] memory whoSignedWhat,
Signature[] memory sigs
) public {
bytes32 channelId = _getChannelId(fixedPart);
_requireChannelNotFinalized(channelId);
// By construction, the following states form a valid transition
bytes32[] memory stateHashes = new bytes32[](numStates);
for (uint256 i = 0; i < numStates; i++) {
stateHashes[i] = keccak256(
abi.encode(
State(
largestTurnNum + (i + 1) - numStates, // turnNum
true, // isFinal
channelId,
appPartHash,
outcomeHash
)
)
);
}
// check the supplied states are supported by n signatures
require(
_validSignatures(
largestTurnNum,
fixedPart.participants,
stateHashes,
sigs,
whoSignedWhat
),
'Invalid signatures'
);
// effects
// set channel storage
channelStorageHashes[channelId] = _hashChannelStorage(
ChannelStorage(0, now, bytes32(0), address(0), outcomeHash)
);
// emit event
emit Concluded(channelId);
}
// Internal methods:
function _requireThatChallengerIsParticipant(
bytes32 supportedStateHash,
address[] memory participants,
Signature memory challengerSignature
) internal pure returns (address challenger) {
challenger = _recoverSigner(
keccak256(abi.encode(supportedStateHash, 'forceMove')),
challengerSignature
);
require(_isAddressInArray(challenger, participants), 'Challenger is not a participant');
}
function _isAddressInArray(address suspect, address[] memory addresses)
internal
pure
returns (bool)
{
for (uint256 i = 0; i < addresses.length; i++) {
if (suspect == addresses[i]) {
return true;
}
}
return false;
}
function _validSignatures(
uint256 largestTurnNum,
address[] memory participants,
bytes32[] memory stateHashes,
Signature[] memory sigs,
uint8[] memory whoSignedWhat // whoSignedWhat[i] is the index of the state in stateHashes that was signed by participants[i]
) internal pure returns (bool) {
uint256 nParticipants = participants.length;
uint256 nStates = stateHashes.length;
require(
_acceptableWhoSignedWhat(whoSignedWhat, largestTurnNum, nParticipants, nStates),
'Unacceptable whoSignedWhat array'
);
for (uint256 i = 0; i < nParticipants; i++) {
address signer = _recoverSigner(stateHashes[whoSignedWhat[i]], sigs[i]);
if (signer != participants[i]) {
return false;
}
}
return true;
}
function _acceptableWhoSignedWhat(
uint8[] memory whoSignedWhat,
uint256 largestTurnNum,
uint256 nParticipants,
uint256 nStates
) internal pure returns (bool) {
require(
whoSignedWhat.length == nParticipants,
'_validSignatures: whoSignedWhat must be the same length as participants'
);
for (uint256 i = 0; i < nParticipants; i++) {
uint256 offset = (nParticipants + largestTurnNum - i) % nParticipants;
// offset is the difference between the index of participant[i] and the index of the participant who owns the largesTurnNum state
// the additional nParticipants in the dividend ensures offset always positive
if (whoSignedWhat[i] + offset < nStates - 1) {
return false;
}
}
return true;
}
bytes constant prefix = '\x19Ethereum Signed Message:\n32';
function _recoverSigner(bytes32 _d, Signature memory sig) internal pure returns (address) {
bytes32 prefixedHash = keccak256(abi.encodePacked(prefix, _d));
address a = ecrecover(prefixedHash, sig.v, sig.r, sig.s);
return (a);
}
function _requireStateSupportedBy(
// returns hash of latest state, if supported
// else, reverts
uint256 largestTurnNum,
ForceMoveApp.VariablePart[] memory variableParts,
uint8 isFinalCount,
bytes32 channelId,
FixedPart memory fixedPart,
Signature[] memory sigs,
uint8[] memory whoSignedWhat // whoSignedWhat[i] is the index of the state in stateHashes that was signed by participants[i]
) internal pure returns (bytes32) {
bytes32[] memory stateHashes = _requireValidTransitionChain(
largestTurnNum,
variableParts,
isFinalCount,
channelId,
fixedPart
);
require(
_validSignatures(
largestTurnNum,
fixedPart.participants,
stateHashes,
sigs,
whoSignedWhat
),
'Invalid signatures'
);
return stateHashes[stateHashes.length - 1];
}
function _requireValidTransitionChain(
// returns stateHashes array if valid
// else, reverts
uint256 largestTurnNum,
ForceMoveApp.VariablePart[] memory variableParts,
uint8 isFinalCount,
bytes32 channelId,
FixedPart memory fixedPart
) internal pure returns (bytes32[] memory) {
bytes32[] memory stateHashes = new bytes32[](variableParts.length);
uint256 firstFinalTurnNum = largestTurnNum - isFinalCount + 1;
uint256 turnNum;
for (uint256 i = 0; i < variableParts.length; i++) {
turnNum = largestTurnNum - variableParts.length + 1 + i;
stateHashes[i] = _hashState(
turnNum,
turnNum >= firstFinalTurnNum,
channelId,
fixedPart,
variableParts[i].appData,
_hashOutcome(variableParts[i].outcome)
);
if (turnNum < largestTurnNum) {
_requireValidTransition(
fixedPart.participants.length,
[turnNum >= firstFinalTurnNum, turnNum + 1 >= firstFinalTurnNum],
[variableParts[i], variableParts[i + 1]],
turnNum + 1,
fixedPart.appDefinition
);
}
}
return stateHashes;
}
function _requireValidTransition(
uint256 nParticipants,
bool[2] memory isFinalAB, // [a.isFinal, b.isFinal]
ForceMoveApp.VariablePart[2] memory ab, // [a,b]
uint256 turnNumB,
address appDefinition
) internal pure returns (bool) {
// a prior check on the signatures for the submitted states implies that the following fields are equal for a and b:
// chainId, participants, channelNonce, appDefinition, challengeDuration
// and that the b.turnNum = a.turnNum + 1
if (isFinalAB[1]) {
require(
_bytesEqual(ab[1].outcome, ab[0].outcome),
'InvalidTransitionError: Cannot move to a final state with a different default outcome'
);
} else {
require(
!isFinalAB[0],
'InvalidTransitionError: Cannot move from a final state to a non final state'
);
if (turnNumB <= 2 * nParticipants) {
require(
_bytesEqual(ab[1].outcome, ab[0].outcome),
'InvalidTransitionError: Cannot change the default outcome during setup phase'
);
require(
keccak256(ab[1].appData) == keccak256(ab[0].appData),
'InvalidTransitionError: Cannot change the appData during setup phase'
);
} else {
require(
ForceMoveApp(appDefinition).validTransition(
ab[0],
ab[1],
turnNumB,
nParticipants
)
);
// reason string not necessary (called function will provide reason for reverting)
}
}
return true;
}
function _bytesEqual(bytes memory left, bytes memory right) internal pure returns (bool) {
return keccak256(left) == keccak256(right);
}
function _clearChallenge(bytes32 channelId, uint256 newTurnNumRecord) internal {
channelStorageHashes[channelId] = _hashChannelStorage(
ChannelStorage(newTurnNumRecord, 0, bytes32(0), address(0), bytes32(0))
);
emit ChallengeCleared(channelId, newTurnNumRecord);
}
function _requireIncreasedTurnNumber(bytes32 channelId, uint48 newTurnNumRecord) internal view {
(uint48 turnNumRecord, , ) = _getData(channelId);
require(newTurnNumRecord > turnNumRecord, 'turnNumRecord not increased.');
}
function _requireNonDecreasedTurnNumber(bytes32 channelId, uint48 newTurnNumRecord)
internal
view
{
(uint48 turnNumRecord, , ) = _getData(channelId);
require(newTurnNumRecord >= turnNumRecord, 'turnNumRecord decreased.');
}
function _requireSpecificChallenge(ChannelStorage memory cs, bytes32 channelId) internal view {
_requireMatchingStorage(cs, channelId);
_requireOngoingChallenge(channelId);
}
function _requireOngoingChallenge(bytes32 channelId) internal view {
require(_mode(channelId) == ChannelMode.Challenge, 'No ongoing challenge.');
}
function _requireChannelNotFinalized(bytes32 channelId) internal view {
require(_mode(channelId) != ChannelMode.Finalized, 'Channel finalized.');
}
function _requireChannelFinalized(bytes32 channelId) internal view {
require(_mode(channelId) == ChannelMode.Finalized, 'Channel not finalized.');
}
function _requireChannelOpen(bytes32 channelId) internal view {
require(_mode(channelId) == ChannelMode.Open, 'Channel not open.');
}
function _requireMatchingStorage(ChannelStorage memory cs, bytes32 channelId) internal view {
require(
_matchesHash(cs, channelStorageHashes[channelId]),
'Channel storage does not match stored version.'
);
}
function _mode(bytes32 channelId) internal view returns (ChannelMode) {
// Note that _getData(someRandomChannelId) returns (0,0,0), which is
// correct when nobody has written to storage yet.
(, uint48 finalizesAt, ) = _getData(channelId);
if (finalizesAt == 0) {
return ChannelMode.Open;
} else if (finalizesAt <= now) {
return ChannelMode.Finalized;
} else {
return ChannelMode.Challenge;
}
}
function _hashChannelStorage(ChannelStorage memory channelStorage)
internal
pure
returns (bytes32 newHash)
{
// The hash is constructed from left to right.
uint256 result;
uint16 cursor = 256;
// Shift turnNumRecord 208 bits left to fill the first 48 bits
result = uint256(channelStorage.turnNumRecord) << (cursor -= 48);
// logical or with finalizesAt padded with 160 zeros to get the next 48 bits
result |= (channelStorage.finalizesAt << (cursor -= 48));
// logical or with the last 160 bits of the hash of the encoded storage
result |= uint256(uint160(uint256(keccak256(abi.encode(channelStorage)))));
newHash = bytes32(result);
}
function _getData(bytes32 channelId)
internal
view
returns (uint48 turnNumRecord, uint48 finalizesAt, uint160 fingerprint)
{
bytes32 storageHash = channelStorageHashes[channelId];
uint16 cursor = 256;
turnNumRecord = uint48(uint256(storageHash) >> (cursor -= 48));
finalizesAt = uint48(uint256(storageHash) >> (cursor -= 48));
fingerprint = uint160(uint256(storageHash));
}
function _matchesHash(ChannelStorage memory cs, bytes32 h) internal pure returns (bool) {
return _hashChannelStorage(cs) == h;
}
function _hashState(
uint256 turnNumRecord,
bool isFinal,
bytes32 channelId,
FixedPart memory fixedPart,
bytes memory appData,
bytes32 outcomeHash
) internal pure returns (bytes32) {
return
keccak256(
abi.encode(
State(
turnNumRecord,
isFinal,
channelId,
keccak256(
abi.encode(
fixedPart.challengeDuration,
fixedPart.appDefinition,
appData
)
),
outcomeHash
)
)
);
}
function _hashOutcome(bytes memory outcome) internal pure returns (bytes32) {
return keccak256(abi.encode(outcome));
}
function _getChannelId(FixedPart memory fixedPart) internal pure returns (bytes32 channelId) {
channelId = keccak256(
abi.encode(fixedPart.chainId, fixedPart.participants, fixedPart.channelNonce)
);
}
// events
event ChallengeRegistered(
bytes32 indexed channelId,
// everything needed to respond or refute
uint256 turnNunmRecord,
uint256 finalizesAt,
address challenger,
bool isFinal,
FixedPart fixedPart,
ForceMoveApp.VariablePart[] variableParts
);
event ChallengeCleared(bytes32 indexed channelId, uint256 newTurnNumRecord);
event Concluded(bytes32 indexed channelId);
}
| ------------ REQUIREMENTS ------------ effects | function checkpoint(
FixedPart memory fixedPart,
uint48 largestTurnNum,
ForceMoveApp.VariablePart[] memory variableParts,
Signature[] memory sigs,
uint8[] memory whoSignedWhat
) public {
bytes32 channelId = _getChannelId(fixedPart);
_requireChannelNotFinalized(channelId);
_requireIncreasedTurnNumber(channelId, largestTurnNum);
_requireStateSupportedBy(
largestTurnNum,
variableParts,
isFinalCount,
channelId,
fixedPart,
sigs,
whoSignedWhat
);
_clearChallenge(channelId, largestTurnNum);
}
| 6,404,684 |
./partial_match/3/0x55Da7f9948940863B62d24869D13b74Cc9401A75/sources/Staking.sol | require(address(this).balance >= _amount);require(tether_token.allowance(msg.sender, this) >= _amount); | function invest_money_withdraw(address _address, uint _amount) public returns(bool result) {
require(_amount > 0);
require(invest_withdraw);
require(investors[_address].amount >= _amount);
require(investors[_address].time_update + time_suspend <= now);
require(tether_token.balanceOf(address(this)) >= _amount);
tether_token.transfer(_address, _amount);
invest_bank = invest_bank - _amount;
return true;
}
| 5,088,352 |
// File: contracts/AnonymiceLibrary.sol
pragma solidity ^0.8.0;
library AnonymiceLibrary {
string internal constant TABLE =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
function encode(bytes memory data) internal pure returns (string memory) {
if (data.length == 0) return "";
// load the table into memory
string memory table = TABLE;
// multiply by 4/3 rounded up
uint256 encodedLen = 4 * ((data.length + 2) / 3);
// add some extra buffer at the end required for the writing
string memory result = new string(encodedLen + 32);
assembly {
// set the actual output length
mstore(result, encodedLen)
// prepare the lookup table
let tablePtr := add(table, 1)
// input ptr
let dataPtr := data
let endPtr := add(dataPtr, mload(data))
// result ptr, jump over length
let resultPtr := add(result, 32)
// run over the input, 3 bytes at a time
for {
} lt(dataPtr, endPtr) {
} {
dataPtr := add(dataPtr, 3)
// read 3 bytes
let input := mload(dataPtr)
// write 4 characters
mstore(
resultPtr,
shl(248, mload(add(tablePtr, and(shr(18, input), 0x3F))))
)
resultPtr := add(resultPtr, 1)
mstore(
resultPtr,
shl(248, mload(add(tablePtr, and(shr(12, input), 0x3F))))
)
resultPtr := add(resultPtr, 1)
mstore(
resultPtr,
shl(248, mload(add(tablePtr, and(shr(6, input), 0x3F))))
)
resultPtr := add(resultPtr, 1)
mstore(
resultPtr,
shl(248, mload(add(tablePtr, and(input, 0x3F))))
)
resultPtr := add(resultPtr, 1)
}
// padding with '='
switch mod(mload(data), 3)
case 1 {
mstore(sub(resultPtr, 2), shl(240, 0x3d3d))
}
case 2 {
mstore(sub(resultPtr, 1), shl(248, 0x3d))
}
}
return result;
}
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
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 parseInt(string memory _a)
internal
pure
returns (uint8 _parsedInt)
{
bytes memory bresult = bytes(_a);
uint8 mint = 0;
for (uint8 i = 0; i < bresult.length; i++) {
if (
(uint8(uint8(bresult[i])) >= 48) &&
(uint8(uint8(bresult[i])) <= 57)
) {
mint *= 10;
mint += uint8(bresult[i]) - 48;
}
}
return mint;
}
function substring(
string memory str,
uint256 startIndex,
uint256 endIndex
) internal pure returns (string memory) {
bytes memory strBytes = bytes(str);
bytes memory result = new bytes(endIndex - startIndex);
for (uint256 i = startIndex; i < endIndex; i++) {
result[i - startIndex] = strBytes[i];
}
return string(result);
}
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;
}
}
// File: contracts/interfaces/IAxonsAuctionHouse.sol
/// @title Interface for Axons Auction Houses
pragma solidity ^0.8.6;
interface IAxonsAuctionHouse {
struct Auction {
// ID for the Axon (ERC721 token ID)
uint256 axonId;
// The current highest bid amount
uint256 amount;
// The time that the auction started
uint256 startTime;
// The time that the auction is scheduled to end
uint256 endTime;
// The address of the current highest bid
address payable bidder;
// Whether or not the auction has been settled
bool settled;
// The auction counter
uint256 counter;
}
event AuctionCreated(uint256 indexed axonId, uint256 startTime, uint256 endTime);
event AuctionBid(uint256 indexed axonId, address sender, uint256 value, bool extended);
event AuctionExtended(uint256 indexed axonId, uint256 endTime);
event AuctionSettled(uint256 indexed axonId, address winner, uint256 amount);
event AuctionTimeBufferUpdated(uint256 timeBuffer);
event AuctionReservePriceUpdated(uint256 reservePrice);
event AuctionMinBidIncrementPercentageUpdated(uint256 minBidIncrementPercentage);
function currentAuction() external view returns(IAxonsAuctionHouse.Auction memory);
function settleAuction() external;
function settleCurrentAndCreateNewAuction() external;
function createBid(uint256 axonId, uint256 amount) external;
function pause() external;
function unpause() external;
function setTimeBuffer(uint256 timeBuffer) external;
function setReservePrice(uint256 reservePrice) external;
function setMinBidIncrementPercentage(uint8 minBidIncrementPercentage) external;
}
// File: contracts/interfaces/IAxonsVoting.sol
/// @title Interface for Axons Auction Houses
pragma solidity ^0.8.6;
interface IAxonsVoting {
struct Auction {
// ID for the Axon (ERC721 token ID)
uint256 axonId;
// The current highest bid amount
uint256 amount;
// The time that the auction started
uint256 startTime;
// The time that the auction is scheduled to end
uint256 endTime;
// The address of the current highest bid
address payable bidder;
// Whether or not the auction has been settled
bool settled;
}
function currentWinnerForAuction(uint256 counter) external view returns (uint256);
function setupVoting(uint256 auctionCounter) external;
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: contracts/interfaces/IAxonsToken.sol
/// @title Interface for AxonsToken
pragma solidity ^0.8.6;
interface IAxonsToken is IERC20 {
event Claimed(address account, uint256 amount);
function generateReward(address recipient, uint256 amount) external;
function isGenesisAddress(address addressToCheck) external view returns(bool);
function burn(uint256 amount) external;
}
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// File: contracts/interfaces/IAxons.sol
/// @title Interface for Axons
pragma solidity ^0.8.6;
interface IAxons is IERC721Enumerable {
event AxonCreated(uint256 indexed tokenId);
event AxonBurned(uint256 indexed tokenId);
event MinterUpdated(address minter);
event MinterLocked();
function mint(uint256 axonId) external returns (uint256);
function burn(uint256 tokenId) external;
function dataURI(uint256 tokenId) external returns (string memory);
function setMinter(address minter) external;
function lockMinter() external;
}
// File: @openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol
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;
}
}
}
// File: @openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.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 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;
}
// File: @openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.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 OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
uint256[49] private __gap;
}
// File: @openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.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 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;
}
// File: @openzeppelin/contracts/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 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;
}
}
}
// File: contracts/AxonsVoting.sol
/// @title The Axons auction house
// LICENSE
// AxonsAuctionHouse.sol is a modified version of NounsAuctionHouse.sol:
// https://raw.githubusercontent.com/nounsDAO/nouns-monorepo/master/packages/nouns-contracts/contracts/NounsAuctionHouse.sol
//
// AuctionHouse.sol source code Copyright Zora licensed under the GPL-3.0 license.
// With modifications by Axons.
pragma solidity ^0.8.6;
contract AxonsVoting is IAxonsVoting, ReentrancyGuardUpgradeable, OwnableUpgradeable {
using SafeMath for uint256;
// The Axons ERC721 token contract
IAxons public axons;
IAxonsAuctionHouse public auctionHouse;
// The address of the AxonToken contract
address public axonsToken;
// The address of the Filaments contract
address public filaments = 0x0a57e26e480355510028b5310FD251df96e2274b;
// The amount of time that must pass to re-register to vote with a specific Axon or Filament
uint256 public registrationCooldown = 86400;
// Voting
mapping(uint256 => uint256[]) public currentAxonsNumbersForVotes;
mapping(uint256 => uint256[]) public currentVotesForAxonNumbers;
mapping(uint256 => uint256) public currentNumberOfVotes;
mapping(uint256 => mapping(address => bool)) public votersForAuctionNumber;
mapping(address => uint256) public votesToClaim;
mapping(uint256 => bool) internal axonNumberToGenerated;
// Voter registration
mapping(uint256 => address) public registeredAxonToAddress;
mapping(uint256 => address) public registeredFilamentToAddress;
mapping(address => uint256) public registeredVoters;
mapping(uint256 => uint256) public registeredAxonToTimestamp;
mapping(uint256 => uint256) public registeredFilamentToTimestamp;
/**
* @notice Require that the sender is the auction house.
*/
modifier onlyAuctionHouse() {
require(msg.sender == address(auctionHouse), 'Sender is not the auction house');
_;
}
/**
* @notice Initialize the voting contracts,
* @dev This function can only be called once.
*/
function initialize(
IAxons _axons,
address _axonsToken,
IAxonsAuctionHouse _auctionHouse
) external initializer {
__ReentrancyGuard_init();
__Ownable_init();
axons = _axons;
axonsToken = _axonsToken;
auctionHouse = _auctionHouse;
}
/**
* @dev Generates a random axon number
* @param _a The address to be used within the hash.
*/
function randomAxonNumber(
address _a,
uint256 _c
) internal returns (uint256) {
uint256 _rand = uint256(
uint256(
keccak256(
abi.encodePacked(
block.timestamp,
block.difficulty,
_a,
_c
)
)
) % 900719925474000
);
if (axonNumberToGenerated[_rand]) return randomAxonNumber(_a, _c + 1);
axonNumberToGenerated[_rand] = true;
return _rand;
}
function registerVoterWithFilament(uint256 tokenId) public {
require(!AnonymiceLibrary.isContract(msg.sender)); // Prevent contracts because I don't know enough Solidity to comfortably allow them
require(IERC721Enumerable(filaments).ownerOf(tokenId) == msg.sender, "Can't register for a Filament you don't own");
address registeredAddress = registeredFilamentToAddress[tokenId]; // Get address that filament is currently registered to
require(registeredAddress != msg.sender, "Already registered to you! Don't waste your gas");
require(registeredFilamentToTimestamp[tokenId] == 0 || (block.timestamp > (registeredFilamentToTimestamp[tokenId] + registrationCooldown)), "Must wait a total of 24 hours to register to vote with this Filament");
registeredFilamentToTimestamp[tokenId] = block.timestamp;
registeredFilamentToAddress[tokenId] = msg.sender; // Register Filament to sender
registeredVoters[msg.sender]++; // Register to vote
if (registeredAddress == address(0)) {
// Never been registered, return
return;
}
// Remove registration from prior owner
if (registeredVoters[registeredAddress] > 0) {
registeredVoters[registeredAddress]--;
}
}
function registerVoterWithAxon(uint256 tokenId) public {
require(!AnonymiceLibrary.isContract(msg.sender)); // Prevent contracts because I don't know enough Solidity to comfortably allow them
require(IAxons(axons).ownerOf(tokenId) == msg.sender, "Can't register for an Axon you don't own");
address registeredAddress = registeredAxonToAddress[tokenId]; // Get address that axon is currently registered to
require(registeredAddress != msg.sender, "Already registered to you! Don't waste your gas");
require(registeredAxonToTimestamp[tokenId] == 0 || (block.timestamp > (registeredAxonToTimestamp[tokenId] + registrationCooldown)), "Must wait a total of 24 hours to register to vote with this Axon");
registeredAxonToTimestamp[tokenId] = block.timestamp;
registeredAxonToAddress[tokenId] = msg.sender; // Register Axon to sender
registeredVoters[msg.sender]++; // Register to vote
if (registeredAddress == address(0)) {
// Never been registered, return
return;
}
// Remove registration from prior owner
if (registeredVoters[registeredAddress] > 0) {
registeredVoters[registeredAddress]--;
}
}
function vote(bool[10] memory votes, uint256 auctionCounter) public {
require(votersForAuctionNumber[auctionCounter][msg.sender] == false, 'Can only vote once per day');
IAxonsAuctionHouse.Auction memory _auction = auctionHouse.currentAuction();
require(block.timestamp < _auction.endTime, 'Auction expired');
require(auctionCounter == _auction.counter, 'Can only vote for current auction');
require(!AnonymiceLibrary.isContract(msg.sender));
require(registeredVoters[msg.sender] > 0 || IAxonsToken(axonsToken).isGenesisAddress(msg.sender), 'Must own a Filament or Axon (and register it to vote) or be a genesis $AXON holder to vote');
// Record voting for today
votersForAuctionNumber[auctionCounter][msg.sender] = true;
// Add upvotes
for (uint i=0; i<10; i++) {
if (votes[i] == true) {
currentVotesForAxonNumbers[auctionCounter][i]++;
}
}
// Track total votes
currentNumberOfVotes[auctionCounter]++;
votesToClaim[msg.sender]++;
}
function claimAxonToken() public {
uint256 amount = votesToClaim[msg.sender];
require(amount > 0,'No votes to claim');
require(!AnonymiceLibrary.isContract(msg.sender));
votesToClaim[msg.sender] = 0;
// Distribute $AXON
IAxonsToken(axonsToken).generateReward(msg.sender, amount);
}
/**
* @dev Generates random axon numbers at the start of a day
*/
function newAxonNumbersForVotes() internal returns (uint256[10] memory) {
uint256[10] memory axonNumbers = [
randomAxonNumber(address(this),3),
randomAxonNumber(address(this),103),
randomAxonNumber(address(this),203),
randomAxonNumber(address(this),303),
randomAxonNumber(address(this),403),
randomAxonNumber(address(this),503),
randomAxonNumber(address(this),603),
randomAxonNumber(address(this),703),
randomAxonNumber(address(this),803),
randomAxonNumber(address(this),903)
];
return axonNumbers;
}
function currentWinnerForAuction(uint256 counter) external view override returns (uint256) {
return _determineWinner(counter);
}
/**
* @notice Determine winner by tallying votes
*/
function _determineWinner(uint256 counter) internal view returns (uint256) {
uint256 winner = currentAxonsNumbersForVotes[counter][0];
uint256 highestVoteCount = 0;
for (uint i=0; i<10; i++) {
uint256 currentAxonNumber = currentAxonsNumbersForVotes[counter][i];
uint256 currentVotesCount = currentVotesForAxonNumbers[counter][i];
if (currentVotesCount > highestVoteCount) {
winner = currentAxonNumber;
highestVoteCount = currentVotesCount;
}
}
return winner;
}
/**
* @notice Set up voting for next auction period
*/
function setupVoting(uint256 auctionCounter) external override onlyAuctionHouse {
currentVotesForAxonNumbers[auctionCounter] = [0,0,0,0,0,0,0,0,0,0];
currentAxonsNumbersForVotes[auctionCounter] = newAxonNumbersForVotes();
currentNumberOfVotes[auctionCounter] = 0;
}
} | Initialize the voting contracts, This function can only be called once./ | function initialize(
IAxons _axons,
address _axonsToken,
IAxonsAuctionHouse _auctionHouse
) external initializer {
__ReentrancyGuard_init();
__Ownable_init();
axons = _axons;
axonsToken = _axonsToken;
auctionHouse = _auctionHouse;
}
| 1,432,948 |
pragma solidity ^0.5.2;
// File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol
interface ierc2023 { //inject NONSTANDARD NAMING
function TRANSFER24(address TO66, uint256 VALUE98) external returns (bool); //inject NONSTANDARD NAMING
function APPROVE68(address SPENDER23, uint256 VALUE98) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM78(address FROM2, address TO66, uint256 VALUE98) external returns (bool); //inject NONSTANDARD NAMING
function TOTALSUPPLY24() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF89(address WHO64) external view returns (uint256); //inject NONSTANDARD NAMING
function ALLOWANCE52(address OWNER65, address SPENDER23) external view returns (uint256); //inject NONSTANDARD NAMING
event TRANSFER5(address indexed FROM2, address indexed TO66, uint256 VALUE98); //inject NONSTANDARD NAMING
event APPROVAL89(address indexed OWNER65, address indexed SPENDER23, uint256 VALUE98); //inject NONSTANDARD NAMING
}
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
pragma solidity ^0.5.2;
library safemath69 { //inject NONSTANDARD NAMING
function MUL40(uint256 A83, uint256 B59) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (A83 == 0) {
return 0;
}
uint256 C4 = A83 * B59; //inject NONSTANDARD NAMING
require(C4 / A83 == B59);
return C4;
}
function DIV25(uint256 A83, uint256 B59) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Solidity only automatically asserts when dividing by 0
require(B59 > 0);
uint256 C4 = A83 / B59; //inject NONSTANDARD NAMING
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return C4;
}
function SUB60(uint256 A83, uint256 B59) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(B59 <= A83);
uint256 C4 = A83 - B59; //inject NONSTANDARD NAMING
return C4;
}
function ADD47(uint256 A83, uint256 B59) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 C4 = A83 + B59; //inject NONSTANDARD NAMING
require(C4 >= A83);
return C4;
}
function MOD87(uint256 A83, uint256 B59) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(B59 != 0);
return A83 % B59;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol
pragma solidity ^0.5.2;
contract erc2052 is ierc2023 { //inject NONSTANDARD NAMING
using safemath69 for uint256;
mapping (address => uint256) private _BALANCES88; //inject NONSTANDARD NAMING
mapping (address => mapping (address => uint256)) private _ALLOWED42; //inject NONSTANDARD NAMING
uint256 private _TOTALSUPPLY11; //inject NONSTANDARD NAMING
function TOTALSUPPLY24() public view returns (uint256) { //inject NONSTANDARD NAMING
return _TOTALSUPPLY11;
}
function BALANCEOF89(address OWNER65) public view returns (uint256) { //inject NONSTANDARD NAMING
return _BALANCES88[OWNER65];
}
function ALLOWANCE52(address OWNER65, address SPENDER23) public view returns (uint256) { //inject NONSTANDARD NAMING
return _ALLOWED42[OWNER65][SPENDER23];
}
function TRANSFER24(address TO66, uint256 VALUE98) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER56(msg.sender, TO66, VALUE98);
return true;
}
function APPROVE68(address SPENDER23, uint256 VALUE98) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE80(msg.sender, SPENDER23, VALUE98);
return true;
}
function TRANSFERFROM78(address FROM2, address TO66, uint256 VALUE98) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER56(FROM2, TO66, VALUE98);
_APPROVE80(FROM2, msg.sender, _ALLOWED42[FROM2][msg.sender].SUB60(VALUE98));
return true;
}
function INCREASEALLOWANCE93(address SPENDER23, uint256 ADDEDVALUE55) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE80(msg.sender, SPENDER23, _ALLOWED42[msg.sender][SPENDER23].ADD47(ADDEDVALUE55));
return true;
}
function DECREASEALLOWANCE55(address SPENDER23, uint256 SUBTRACTEDVALUE25) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE80(msg.sender, SPENDER23, _ALLOWED42[msg.sender][SPENDER23].SUB60(SUBTRACTEDVALUE25));
return true;
}
function _TRANSFER56(address FROM2, address TO66, uint256 VALUE98) internal { //inject NONSTANDARD NAMING
require(TO66 != address(0));
_BALANCES88[FROM2] = _BALANCES88[FROM2].SUB60(VALUE98);
_BALANCES88[TO66] = _BALANCES88[TO66].ADD47(VALUE98);
emit TRANSFER5(FROM2, TO66, VALUE98);
}
function _MINT69(address ACCOUNT65, uint256 VALUE98) internal { //inject NONSTANDARD NAMING
require(ACCOUNT65 != address(0));
_TOTALSUPPLY11 = _TOTALSUPPLY11.ADD47(VALUE98);
_BALANCES88[ACCOUNT65] = _BALANCES88[ACCOUNT65].ADD47(VALUE98);
emit TRANSFER5(address(0), ACCOUNT65, VALUE98);
}
function _BURN95(address ACCOUNT65, uint256 VALUE98) internal { //inject NONSTANDARD NAMING
require(ACCOUNT65 != address(0));
_TOTALSUPPLY11 = _TOTALSUPPLY11.SUB60(VALUE98);
_BALANCES88[ACCOUNT65] = _BALANCES88[ACCOUNT65].SUB60(VALUE98);
emit TRANSFER5(ACCOUNT65, address(0), VALUE98);
}
function _APPROVE80(address OWNER65, address SPENDER23, uint256 VALUE98) internal { //inject NONSTANDARD NAMING
require(SPENDER23 != address(0));
require(OWNER65 != address(0));
_ALLOWED42[OWNER65][SPENDER23] = VALUE98;
emit APPROVAL89(OWNER65, SPENDER23, VALUE98);
}
function _BURNFROM68(address ACCOUNT65, uint256 VALUE98) internal { //inject NONSTANDARD NAMING
_BURN95(ACCOUNT65, VALUE98);
_APPROVE80(ACCOUNT65, msg.sender, _ALLOWED42[ACCOUNT65][msg.sender].SUB60(VALUE98));
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Detailed.sol
pragma solidity ^0.5.2;
contract erc20detailed12 is ierc2023 { //inject NONSTANDARD NAMING
string private _NAME95; //inject NONSTANDARD NAMING
string private _SYMBOL37; //inject NONSTANDARD NAMING
uint8 private _DECIMALS2; //inject NONSTANDARD NAMING
constructor (string memory NAME93, string memory SYMBOL43, uint8 DECIMALS83) public { //inject NONSTANDARD NAMING
_NAME95 = NAME93;
_SYMBOL37 = SYMBOL43;
_DECIMALS2 = DECIMALS83;
}
function NAME100() public view returns (string memory) { //inject NONSTANDARD NAMING
return _NAME95;
}
function SYMBOL95() public view returns (string memory) { //inject NONSTANDARD NAMING
return _SYMBOL37;
}
function DECIMALS41() public view returns (uint8) { //inject NONSTANDARD NAMING
return _DECIMALS2;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Burnable.sol
pragma solidity ^0.5.2;
contract erc20burnable39 is erc2052 { //inject NONSTANDARD NAMING
function BURN93(uint256 VALUE98) public { //inject NONSTANDARD NAMING
_BURN95(msg.sender, VALUE98);
}
function BURNFROM19(address FROM2, uint256 VALUE98) public { //inject NONSTANDARD NAMING
_BURNFROM68(FROM2, VALUE98);
}
}
// File: contracts/AVEC.sol
pragma solidity ^0.5.0;
contract avec56 is erc2052, erc20detailed12, erc20burnable39 { //inject NONSTANDARD NAMING
constructor() erc20detailed12('Alternate Virtual Equity Credit', 'AVEC', 18) public {
_MINT69(msg.sender, 1440000000 * 10 ** 18);
}
} | inject NONSTANDARD NAMING | function _MINT69(address ACCOUNT65, uint256 VALUE98) internal { | 13,007,997 |
// File: @onchain-id/solidity/contracts/IERC734.sol
pragma solidity ^0.6.2;
interface IERC734 {
struct Key {
uint256[] purposes;
uint256 keyType;
bytes32 key;
}
event APPROVED490(uint256 indexed executionId, bool approved); //inject NONSTANDARD NAMING
event EXECUTED607(uint256 indexed executionId, address indexed to, uint256 indexed value, bytes data); //inject NONSTANDARD NAMING
event EXECUTIONREQUESTED852(uint256 indexed executionId, address indexed to, uint256 indexed value, bytes data); //inject NONSTANDARD NAMING
event KEYADDED145(bytes32 indexed key, uint256 indexed purpose, uint256 indexed keyType); //inject NONSTANDARD NAMING
event KEYREMOVED913(bytes32 indexed key, uint256 indexed purpose, uint256 indexed keyType); //inject NONSTANDARD NAMING
event KEYSREQUIREDCHANGED871(uint256 purpose, uint256 number); //inject NONSTANDARD NAMING
function ADDKEY780(bytes32 _key, uint256 _purpose, uint256 _keyType) external returns (bool success); //inject NONSTANDARD NAMING
function APPROVE542(uint256 _id, bool _approve) external returns (bool success); //inject NONSTANDARD NAMING
function EXECUTE357(address _to, uint256 _value, bytes calldata _data) external payable returns (uint256 executionId); //inject NONSTANDARD NAMING
function GETKEY752(bytes32 _key) external view returns (uint256[] memory purposes, uint256 keyType, bytes32 key); //inject NONSTANDARD NAMING
function GETKEYPURPOSES287(bytes32 _key) external view returns(uint256[] memory _purposes); //inject NONSTANDARD NAMING
function GETKEYSBYPURPOSE882(uint256 _purpose) external view returns (bytes32[] memory keys); //inject NONSTANDARD NAMING
function KEYHASPURPOSE281(bytes32 _key, uint256 _purpose) external view returns (bool exists); //inject NONSTANDARD NAMING
function REMOVEKEY520(bytes32 _key, uint256 _purpose) external returns (bool success); //inject NONSTANDARD NAMING
}
// File: @onchain-id/solidity/contracts/IERC735.sol
pragma solidity ^0.6.2;
interface IERC735 {
event CLAIMREQUESTED636(uint256 indexed claimRequestId, uint256 indexed topic, uint256 scheme, address indexed issuer, bytes signature, bytes data, string uri); //inject NONSTANDARD NAMING
event CLAIMADDED434(bytes32 indexed claimId, uint256 indexed topic, uint256 scheme, address indexed issuer, bytes signature, bytes data, string uri); //inject NONSTANDARD NAMING
event CLAIMREMOVED422(bytes32 indexed claimId, uint256 indexed topic, uint256 scheme, address indexed issuer, bytes signature, bytes data, string uri); //inject NONSTANDARD NAMING
event CLAIMCHANGED857(bytes32 indexed claimId, uint256 indexed topic, uint256 scheme, address indexed issuer, bytes signature, bytes data, string uri); //inject NONSTANDARD NAMING
struct Claim {
uint256 topic;
uint256 scheme;
address issuer;
bytes signature;
bytes data;
string uri;
}
function GETCLAIM300(bytes32 _claimId) external view returns(uint256 topic, uint256 scheme, address issuer, bytes memory signature, bytes memory data, string memory uri); //inject NONSTANDARD NAMING
function GETCLAIMIDSBYTOPIC680(uint256 _topic) external view returns(bytes32[] memory claimIds); //inject NONSTANDARD NAMING
function ADDCLAIM459(uint256 _topic, uint256 _scheme, address issuer, bytes calldata _signature, bytes calldata _data, string calldata _uri) external returns (bytes32 claimRequestId); //inject NONSTANDARD NAMING
function REMOVECLAIM793(bytes32 _claimId) external returns (bool success); //inject NONSTANDARD NAMING
}
// File: @onchain-id/solidity/contracts/IIdentity.sol
pragma solidity ^0.6.2;
interface IIdentity is IERC734, IERC735 {}
// File: @tokenysolutions/t-rex/contracts/registry/IIdentityRegistryStorage.sol
pragma solidity 0.6.2;
interface IIdentityRegistryStorage {
event IDENTITYSTORED128(address indexed investorAddress, IIdentity indexed identity); //inject NONSTANDARD NAMING
event IDENTITYUNSTORED820(address indexed investorAddress, IIdentity indexed identity); //inject NONSTANDARD NAMING
event IDENTITYMODIFIED265(IIdentity indexed oldIdentity, IIdentity indexed newIdentity); //inject NONSTANDARD NAMING
event COUNTRYMODIFIED940(address indexed investorAddress, uint16 indexed country); //inject NONSTANDARD NAMING
event IDENTITYREGISTRYBOUND952(address indexed identityRegistry); //inject NONSTANDARD NAMING
event IDENTITYREGISTRYUNBOUND414(address indexed identityRegistry); //inject NONSTANDARD NAMING
function LINKEDIDENTITYREGISTRIES299() external view returns (address[] memory); //inject NONSTANDARD NAMING
function STOREDIDENTITY367(address _userAddress) external view returns (IIdentity); //inject NONSTANDARD NAMING
function STOREDINVESTORCOUNTRY957(address _userAddress) external view returns (uint16); //inject NONSTANDARD NAMING
function ADDIDENTITYTOSTORAGE973(address _userAddress, IIdentity _identity, uint16 _country) external; //inject NONSTANDARD NAMING
function REMOVEIDENTITYFROMSTORAGE801(address _userAddress) external; //inject NONSTANDARD NAMING
function MODIFYSTOREDINVESTORCOUNTRY139(address _userAddress, uint16 _country) external; //inject NONSTANDARD NAMING
function MODIFYSTOREDIDENTITY804(address _userAddress, IIdentity _identity) external; //inject NONSTANDARD NAMING
function TRANSFEROWNERSHIPONIDENTITYREGISTRYSTORAGE181(address _newOwner) external; //inject NONSTANDARD NAMING
function BINDIDENTITYREGISTRY966(address _identityRegistry) external; //inject NONSTANDARD NAMING
function UNBINDIDENTITYREGISTRY94(address _identityRegistry) external; //inject NONSTANDARD NAMING
}
// File: openzeppelin-solidity/contracts/GSN/Context.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
function _MSGSENDER968() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING
return msg.sender;
}
function _MSGDATA951() internal view virtual returns (bytes memory) { //inject NONSTANDARD NAMING
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @tokenysolutions/t-rex/contracts/roles/Ownable.sol
pragma solidity 0.6.2;
contract Ownable is Context {
address private _owner;
event OWNERSHIPTRANSFERRED988(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING
constructor () internal {
address msgSender = _MSGSENDER968();
_owner = msgSender;
emit OWNERSHIPTRANSFERRED988(address(0), msgSender);
}
function OWNER857() external view returns (address) { //inject NONSTANDARD NAMING
return _owner;
}
modifier ONLYOWNER188() { //inject NONSTANDARD NAMING
require(ISOWNER766(), "Ownable: caller is not the owner");
_;
}
function ISOWNER766() public view returns (bool) { //inject NONSTANDARD NAMING
return _MSGSENDER968() == _owner;
}
function RENOUNCEOWNERSHIP147() external virtual ONLYOWNER188 { //inject NONSTANDARD NAMING
emit OWNERSHIPTRANSFERRED988(_owner, address(0));
_owner = address(0);
}
function TRANSFEROWNERSHIP614(address newOwner) public virtual ONLYOWNER188 { //inject NONSTANDARD NAMING
_TRANSFEROWNERSHIP40(newOwner);
}
function _TRANSFEROWNERSHIP40(address newOwner) internal virtual { //inject NONSTANDARD NAMING
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OWNERSHIPTRANSFERRED988(_owner, newOwner);
_owner = newOwner;
}
}
// File: @tokenysolutions/t-rex/contracts/compliance/ICompliance.sol
pragma solidity 0.6.2;
interface ICompliance {
event TOKENAGENTADDED270(address _agentAddress); //inject NONSTANDARD NAMING
event TOKENAGENTREMOVED312(address _agentAddress); //inject NONSTANDARD NAMING
event TOKENBOUND274(address _token); //inject NONSTANDARD NAMING
event TOKENUNBOUND919(address _token); //inject NONSTANDARD NAMING
function ISTOKENAGENT216(address _agentAddress) external view returns (bool); //inject NONSTANDARD NAMING
function ISTOKENBOUND101(address _token) external view returns (bool); //inject NONSTANDARD NAMING
function ADDTOKENAGENT168(address _agentAddress) external; //inject NONSTANDARD NAMING
function REMOVETOKENAGENT600(address _agentAddress) external; //inject NONSTANDARD NAMING
function BINDTOKEN336(address _token) external; //inject NONSTANDARD NAMING
function UNBINDTOKEN130(address _token) external; //inject NONSTANDARD NAMING
function CANTRANSFER762(address _from, address _to, uint256 _amount) external view returns (bool); //inject NONSTANDARD NAMING
function TRANSFERRED661(address _from, address _to, uint256 _amount) external; //inject NONSTANDARD NAMING
function CREATED745(address _to, uint256 _amount) external; //inject NONSTANDARD NAMING
function DESTROYED848(address _from, uint256 _amount) external; //inject NONSTANDARD NAMING
function TRANSFEROWNERSHIPONCOMPLIANCECONTRACT644(address newOwner) external; //inject NONSTANDARD NAMING
}
// File: contracts/compliance/CountryRestrictions.sol
pragma solidity 0.6.2;
contract CountryRestrictions is ICompliance, Ownable {
event IDENTITYSTORAGEADDED931(address indexed _identityStorage); //inject NONSTANDARD NAMING
event ADDEDRESTRICTEDCOUNTRY249(uint16 _country); //inject NONSTANDARD NAMING
event REMOVEDRESTRICTEDCOUNTRY571(uint16 _country); //inject NONSTANDARD NAMING
IIdentityRegistryStorage public identityStorage;
mapping(uint16 => bool) private _restrictedCountries;
mapping(address => bool) private _tokenAgentsList;
mapping(address => bool) private _tokensBound;
constructor (address _identityStorage) public {
identityStorage = IIdentityRegistryStorage(_identityStorage);
emit IDENTITYSTORAGEADDED931(_identityStorage);
}
function ISTOKENAGENT216(address _agentAddress) public override view returns (bool) { //inject NONSTANDARD NAMING
return (_tokenAgentsList[_agentAddress]);
}
function ISTOKENBOUND101(address _token) public override view returns (bool) { //inject NONSTANDARD NAMING
return (_tokensBound[_token]);
}
function ISCOUNTRYRESTRICTED644(uint16 _country) public view returns (bool) { //inject NONSTANDARD NAMING
return (_restrictedCountries[_country]);
}
function ADDTOKENAGENT168(address _agentAddress) external override ONLYOWNER188 { //inject NONSTANDARD NAMING
require(!_tokenAgentsList[_agentAddress], "This Agent is already registered");
_tokenAgentsList[_agentAddress] = true;
emit TOKENAGENTADDED270(_agentAddress);
}
function REMOVETOKENAGENT600(address _agentAddress) external override ONLYOWNER188 { //inject NONSTANDARD NAMING
require(_tokenAgentsList[_agentAddress], "This Agent is not registered yet");
_tokenAgentsList[_agentAddress] = false;
emit TOKENAGENTREMOVED312(_agentAddress);
}
function BINDTOKEN336(address _token) external override ONLYOWNER188 { //inject NONSTANDARD NAMING
require(!_tokensBound[_token], "This token is already bound");
_tokensBound[_token] = true;
emit TOKENBOUND274(_token);
}
function UNBINDTOKEN130(address _token) external override ONLYOWNER188 { //inject NONSTANDARD NAMING
require(_tokensBound[_token], "This token is not bound yet");
_tokensBound[_token] = false;
emit TOKENUNBOUND919(_token);
}
function TRANSFERRED661(address _from, address _to, uint256 _value) external override { //inject NONSTANDARD NAMING
}
function CREATED745(address _to, uint256 _value) external override { //inject NONSTANDARD NAMING
}
function DESTROYED848(address _from, uint256 _value) external override { //inject NONSTANDARD NAMING
}
function SETIDENTITYSTORAGE662(address _identityStorage) external ONLYOWNER188 { //inject NONSTANDARD NAMING
identityStorage = IIdentityRegistryStorage(_identityStorage);
emit IDENTITYSTORAGEADDED931(_identityStorage);
}
function ADDCOUNTRYRESTRICTION776(uint16 _country) external ONLYOWNER188 { //inject NONSTANDARD NAMING
_restrictedCountries[_country] = true;
emit ADDEDRESTRICTEDCOUNTRY249(_country);
}
function REMOVECOUNTRYRESTRICTION163(uint16 _country) external ONLYOWNER188 { //inject NONSTANDARD NAMING
_restrictedCountries[_country] = false;
emit REMOVEDRESTRICTEDCOUNTRY571(_country);
}
function BATCHRESTRICTCOUNTRIES404(uint16[] calldata _countries) external ONLYOWNER188 { //inject NONSTANDARD NAMING
for (uint i = 0; i < _countries.length; i++) {
_restrictedCountries[_countries[i]] = true;
emit ADDEDRESTRICTEDCOUNTRY249(_countries[i]);
}
}
function BATCHUNRESTRICTCOUNTRIES285(uint16[] calldata _countries) external ONLYOWNER188 { //inject NONSTANDARD NAMING
for (uint i = 0; i < _countries.length; i++) {
_restrictedCountries[_countries[i]] = false;
emit REMOVEDRESTRICTEDCOUNTRY571(_countries[i]);
}
}
function CANTRANSFER762(address _from, address _to, uint256 _value) external view override returns (bool) { //inject NONSTANDARD NAMING
uint16 receiverCountry = identityStorage.STOREDINVESTORCOUNTRY957(_to);
return (!(_restrictedCountries[receiverCountry]));
}
function TRANSFEROWNERSHIPONCOMPLIANCECONTRACT644(address newOwner) external override ONLYOWNER188 { //inject NONSTANDARD NAMING
TRANSFEROWNERSHIP614(newOwner);
}
} | inject NONSTANDARD NAMING | function CREATED745(address _to, uint256 _amount) external; | 5,524,160 |
./full_match/137/0xC505362eF38aA0DeCa5b14ebeE84A898950DB0Da/sources/contracts/BONQ-staking.sol | updates baseRate _increase value to add to baseRate _increase | function increaseBaseRate(uint256 _increase) external override returns (uint256) {
require(msg.sender == address(factory), "10bcb only factory increases baseRate");
lastFeeOperationTime = block.timestamp;
baseRate += _increase;
return baseRate;
}
| 4,745,172 |
./full_match/7001/0x3D9892247AEa8BEcc9f487Fb3709DfbCFF3c83c1/sources/contracts/Withdraw.sol | External function that is called by the zContract. zrc20 The address of the ZRC20 token to be withdrawn. amount The amount of tokens to be withdrawn. message The encoded recipient address for the withdrawn tokens./ | function onCrossChainCall(
address zrc20,
uint256 amount,
bytes calldata message
) external virtual override {
if (zrc20 == address(0)) revert InvalidZRC20Address();
if (amount == 0) revert ZeroAmount();
bytes32 recipient = abi.decode(message, (bytes32));
doWithdrawal(zrc20, amount, recipient);
}
| 13,228,959 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "../base/AbstractStrategy.sol";
import "../curve/interfaces/ICurveFi.sol";
import "../uniswap-v2/interfaces/IUniswapV2Router02.sol";
import "./interfaces/IConvex.sol";
import "./interfaces/IConvexRewards.sol";
// add_liquidity to curve 3pool 0xbebc44782c7db0a1a60cb6fe97d0b483032ff1c7,
// receive lpToken 3CRV 0x6c3F90f043a72FA612cbac8115EE7e52BDe6E490
// deposit 3crv to convex booster 0xF403C135812408BFbE8713b5A23a04b3D48AAE31, pool id is 9
// harvest will get reward from rewards contract 0x689440f2ff927e1f24c72f1087e1faf471ece1c8
contract StrategyConvex3Pool is AbstractStrategy {
using SafeERC20 for IERC20;
using Address for address;
uint256 public slippage = 500;
uint256 public constant SLIPPAGE_DENOMINATOR = 10000;
address public constant crv = address(0xD533a949740bb3306d119CC777fa900bA034cd52);
address public constant weth = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
address public constant uniswap = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
address public constant cvx = address(0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B); // convex CVX erc20 token
address public immutable pool; // curve 3pool
address public immutable lpToken; // 3crv
address public immutable convex;
address public immutable convexRewards;
uint256 public immutable convexPoolId; // poolId in convex booster
uint8 public immutable supplyTokenIndexInPool;
uint256 public immutable decimalDiff;
constructor(
address _controller,
address _supplyToken,
uint8 _supplyTokenDecimal,
uint8 _supplyTokenIndexIn3Pool,
address _3pool,
address _3crv,
address _convex,
address _convexRewards,
uint256 _convexPoolId
) AbstractStrategy(_controller, _supplyToken) {
pool = _3pool;
lpToken = _3crv;
convex = _convex;
convexRewards = _convexRewards;
convexPoolId = _convexPoolId;
supplyTokenIndexInPool = _supplyTokenIndexIn3Pool;
decimalDiff = PRICE_DECIMALS / 10**_supplyTokenDecimal; // curve treats supply tokens as they have 18 decimals but tokens like USDC and USDT actually have 6 decimals
}
/**
* @dev Require that the caller must be an EOA account to avoid flash loans.
*/
modifier onlyEOA() {
require(msg.sender == tx.origin, "Not EOA");
_;
}
function getAssetAmount() public view override returns (uint256) {
uint256 lpTokenBalance = IConvexRewards(convexRewards).balanceOf(address(this));
return ((lpTokenBalance * ICurveFi(pool).get_virtual_price()) / decimalDiff) / PRICE_DECIMALS;
}
function buy(uint256 _buyAmount) internal override returns (uint256) {
// pull fund from controller
IERC20(supplyToken).safeTransferFrom(msg.sender, address(this), _buyAmount);
uint256 obtainedLpTokens = _addLiquidity(_buyAmount);
// deposit LP tokens to convex booster
IERC20(lpToken).safeIncreaseAllowance(convex, obtainedLpTokens);
IConvex(convex).deposit(convexPoolId, obtainedLpTokens, true);
uint256 obtainedUnderlyingAsset = ((obtainedLpTokens * ICurveFi(pool).get_virtual_price()) / decimalDiff) /
PRICE_DECIMALS;
return obtainedUnderlyingAsset;
}
function sell(uint256 _sellAmount) internal override returns (uint256) {
uint256 sellLpTokens = (_sellAmount * PRICE_DECIMALS * decimalDiff) / ICurveFi(pool).get_virtual_price();
// get lpToken back, leave claim to harvest
IConvexRewards(convexRewards).withdrawAndUnwrap(sellLpTokens, false);
// remove liquidity from pool to get supplyToken back
uint256 minAmountFromSell = (_sellAmount * (SLIPPAGE_DENOMINATOR - slippage)) / SLIPPAGE_DENOMINATOR;
uint256 balanceBeforeSell = IERC20(supplyToken).balanceOf(address(this));
ICurveFi(pool).remove_liquidity_one_coin(sellLpTokens, int8(supplyTokenIndexInPool), minAmountFromSell);
uint256 obtainedSupplyToken = IERC20(supplyToken).balanceOf(address(this)) - balanceBeforeSell;
IERC20(supplyToken).safeTransfer(msg.sender, obtainedSupplyToken);
return obtainedSupplyToken;
}
function _addLiquidity(uint256 _buyAmount) private returns (uint256) {
uint256 originalLpTokenBalance = IERC20(lpToken).balanceOf(address(this));
uint256 minMintAmount = (((_buyAmount * PRICE_DECIMALS * decimalDiff) / ICurveFi(pool).get_virtual_price()) *
(SLIPPAGE_DENOMINATOR - slippage)) / SLIPPAGE_DENOMINATOR;
uint256[3] memory amounts;
amounts[supplyTokenIndexInPool] = _buyAmount;
IERC20(supplyToken).safeIncreaseAllowance(pool, _buyAmount);
ICurveFi(pool).add_liquidity(amounts, minMintAmount);
uint256 obtainedLpToken = IERC20(lpToken).balanceOf(address(this)) - originalLpTokenBalance;
return obtainedLpToken;
}
function harvest() external override onlyEOA {
IConvexRewards(convexRewards).getReward(); // receive both crv and cvx
uint256 originalBalance = IERC20(supplyToken).balanceOf(address(this));
uint256 crvBalance = IERC20(crv).balanceOf(address(this));
uint256 cvxBalance = IERC20(cvx).balanceOf(address(this));
if (crvBalance > 0) {
// Sell CRV for more supply token
IERC20(crv).safeIncreaseAllowance(uniswap, crvBalance);
address[] memory path = new address[](3);
path[0] = crv;
path[1] = weth;
path[2] = supplyToken;
// TODO: Check price
IUniswapV2Router02(uniswap).swapExactTokensForTokens(
crvBalance,
uint256(0),
path,
address(this),
block.timestamp + 1800
);
}
if (cvxBalance > 0) {
IERC20(cvx).safeIncreaseAllowance(uniswap, cvxBalance);
address[] memory path = new address[](3);
path[0] = cvx;
path[1] = weth;
path[2] = supplyToken;
IUniswapV2Router02(uniswap).swapExactTokensForTokens(
cvxBalance,
uint256(0),
path,
address(this),
block.timestamp + 1800
);
}
// Re-invest supply token to obtain more lpToken
uint256 obtainedAssetAmount = IERC20(supplyToken).balanceOf(address(this)) - originalBalance;
if (obtainedAssetAmount > 0) {
uint256 obtainedLpToken = _addLiquidity(obtainedAssetAmount);
// deposit LP tokens to convex booster
IERC20(lpToken).safeIncreaseAllowance(convex, obtainedLpToken);
IConvex(convex).deposit(convexPoolId, obtainedLpToken, true);
}
}
function setSlippage(uint256 _slippage) external onlyOwner {
slippage = _slippage;
}
function protectedTokens() internal view override returns (address[] memory) {
address[] memory protected = new address[](3);
protected[0] = lpToken;
protected[1] = crv;
protected[2] = cvx;
return protected;
}
}
| pull fund from controller deposit LP tokens to convex booster | function buy(uint256 _buyAmount) internal override returns (uint256) {
IERC20(supplyToken).safeTransferFrom(msg.sender, address(this), _buyAmount);
uint256 obtainedLpTokens = _addLiquidity(_buyAmount);
IERC20(lpToken).safeIncreaseAllowance(convex, obtainedLpTokens);
IConvex(convex).deposit(convexPoolId, obtainedLpTokens, true);
uint256 obtainedUnderlyingAsset = ((obtainedLpTokens * ICurveFi(pool).get_virtual_price()) / decimalDiff) /
PRICE_DECIMALS;
return obtainedUnderlyingAsset;
}
| 12,805,699 |
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "../interfaces/IOracle.sol";
import "../interfaces/IUniswapV3Pool.sol";
import "../libraries/Sqrt.sol";
contract UniswapV3Oracle is IOracle {
using Address for address;
using SafeMath for uint256;
using Sqrt for uint256;
bytes32 public constant POOL_INIT_CODE_HASH = 0xe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54;
address public constant FACTORY = 0x1F98431c8aD98523631AE4a59f267346ea31F984;
IERC20 private constant _NONE = IERC20(0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF);
function getRate(IERC20 srcToken, IERC20 dstToken, IERC20 connector) external override view returns (uint256 rate, uint256 weight) {
uint24[3] memory fees = [uint24(500), 3000, 10000];
for (uint256 i = 0; i < 3; i++) {
(uint256 rateForFee, uint256 weightForFee) = getRateForFee(srcToken, dstToken, connector, fees[i]);
rate = rate.add(rateForFee.mul(weightForFee));
weight = weight.add(weightForFee);
}
if (weight > 0) {
rate = rate.div(weight);
weight = weight.sqrt();
}
}
// @dev fee in ppm (e.g. 3000 for 0.3% fee)
function getRateForFee(IERC20 srcToken, IERC20 dstToken, IERC20 connector, uint24 fee) public view returns (uint256 rate, uint256 weight) {
uint256 balance0;
uint256 balance1;
if (connector == _NONE) {
(rate, balance0, balance1) = _getRate(srcToken, dstToken, fee);
} else {
uint256 balanceConnector0;
uint256 balanceConnector1;
uint256 rate0;
uint256 rate1;
(rate0, balance0, balanceConnector0) = _getRate(srcToken, connector, fee);
if (balance0 == 0 || balanceConnector0 == 0) {
return (0, 0);
}
(rate1, balanceConnector1, balance1) = _getRate(connector, dstToken, fee);
if (balanceConnector1 == 0 || balance1 == 0) {
return (0, 0);
}
if (balanceConnector0 > balanceConnector1) {
balance0 = balance0.mul(balanceConnector1).div(balanceConnector0);
} else {
balance1 = balance1.mul(balanceConnector0).div(balanceConnector1);
}
rate = rate0.mul(rate1).div(1e18);
}
weight = balance0.mul(balance1);
}
function _getRate(IERC20 srcToken, IERC20 dstToken, uint24 fee) internal view returns (uint256 rate, uint256 srcBalance, uint256 dstBalance) {
(IERC20 token0, IERC20 token1) = srcToken < dstToken ? (srcToken, dstToken) : (dstToken, srcToken);
address pool = _getPool(address(token0), address(token1), fee);
if (!pool.isContract()) {
return (0, 0, 0);
}
(uint256 sqrtPriceX96,,,,,,) = IUniswapV3Pool(pool).slot0();
if (srcToken == token0) {
rate = (uint256(1e18).mul(sqrtPriceX96) >> 96).mul(sqrtPriceX96) >> 96;
} else {
rate = uint256(1e18 << 192).div(sqrtPriceX96).div(sqrtPriceX96);
}
srcBalance = srcToken.balanceOf(address(pool));
dstBalance = dstToken.balanceOf(address(pool));
}
function _getPool(address token0, address token1, uint24 fee) private pure returns (address) {
return address(
uint256(
keccak256(
abi.encodePacked(
hex'ff',
FACTORY,
keccak256(abi.encode(token0, token1, fee)),
POOL_INIT_CODE_HASH
)
)
)
);
}
}
// 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, 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.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) {
// 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.7.6;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IOracle {
function getRate(IERC20 srcToken, IERC20 dstToken, IERC20 connector) external view returns (uint256 rate, uint256 weight);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IUniswapV3Pool {
function slot0() external view returns (uint160 sqrtPriceX96, int24, uint16, uint16, uint16, uint8, bool);
function token0() external view returns (IERC20 token);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
library Sqrt {
function sqrt(uint y) internal pure returns (uint z) {
if (y > 3) {
z = y;
uint x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
}
}
| fee in ppm (e.g. 3000 for 0.3% fee) | function getRateForFee(IERC20 srcToken, IERC20 dstToken, IERC20 connector, uint24 fee) public view returns (uint256 rate, uint256 weight) {
uint256 balance0;
uint256 balance1;
if (connector == _NONE) {
(rate, balance0, balance1) = _getRate(srcToken, dstToken, fee);
uint256 balanceConnector0;
uint256 balanceConnector1;
uint256 rate0;
uint256 rate1;
(rate0, balance0, balanceConnector0) = _getRate(srcToken, connector, fee);
if (balance0 == 0 || balanceConnector0 == 0) {
return (0, 0);
}
(rate1, balanceConnector1, balance1) = _getRate(connector, dstToken, fee);
if (balanceConnector1 == 0 || balance1 == 0) {
return (0, 0);
}
if (balanceConnector0 > balanceConnector1) {
balance0 = balance0.mul(balanceConnector1).div(balanceConnector0);
balance1 = balance1.mul(balanceConnector0).div(balanceConnector1);
}
rate = rate0.mul(rate1).div(1e18);
}
weight = balance0.mul(balance1);
}
| 1,129,235 |
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.8.9;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "../interfaces/IPool.sol";
import "../interfaces/IWithdrawInbox.sol";
import "../safeguard/Pauser.sol";
/**
* @title Example contract to provide liquidity to {Bridge}. Supports withdrawing liquidity via {WithdrawInbox}.
*/
contract ContractAsLP is ReentrancyGuard, Pauser {
using SafeERC20 for IERC20;
address public bridge;
address public inbox;
event Deposited(address depositor, address token, uint256 amount);
constructor(address _bridge, address _inbox) {
bridge = _bridge;
inbox = _inbox;
}
/**
* @notice Deposit tokens.
* @param _token The deposited token address.
* @param _amount The amount to deposit.
*/
function deposit(address _token, uint256 _amount) external nonReentrant whenNotPaused onlyOwner {
IERC20(_token).safeTransferFrom(msg.sender, address(this), _amount);
emit Deposited(msg.sender, _token, _amount);
}
/**
* @notice Add liquidity to the pool-based bridge.
* NOTE: This function DOES NOT SUPPORT fee-on-transfer / rebasing tokens.
* @param _token The address of the token.
* @param _amount The amount to add.
*/
function addLiquidity(address _token, uint256 _amount) external whenNotPaused onlyOwner {
require(IERC20(_token).balanceOf(address(this)) >= _amount, "insufficient balance");
IERC20(_token).safeIncreaseAllowance(bridge, _amount);
IPool(bridge).addLiquidity(_token, _amount);
}
/**
* @notice Withdraw liquidity from the pool-based bridge.
* NOTE: Each of your withdrawal request should have different _wdSeq.
* NOTE: Tokens to withdraw within one withdrawal request should have the same symbol.
* @param _wdSeq The unique sequence number to identify this withdrawal request.
* @param _receiver The receiver address on _toChain.
* @param _toChain The chain Id to receive the withdrawn tokens.
* @param _fromChains The chain Ids to withdraw tokens.
* @param _tokens The token to withdraw on each fromChain.
* @param _ratios The withdrawal ratios of each token.
* @param _slippages The max slippages of each token for cross-chain withdraw.
*/
function withdraw(
uint64 _wdSeq,
address _receiver,
uint64 _toChain,
uint64[] calldata _fromChains,
address[] calldata _tokens,
uint32[] calldata _ratios,
uint32[] calldata _slippages
) external whenNotPaused onlyOwner {
IWithdrawInbox(inbox).withdraw(_wdSeq, _receiver, _toChain, _fromChains, _tokens, _ratios, _slippages);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity >=0.8.0;
interface IPool {
function addLiquidity(address _token, uint256 _amount) external;
function withdraws(bytes32 withdrawId) external view returns (bool);
function withdraw(
bytes calldata _wdmsg,
bytes[] calldata _sigs,
address[] calldata _signers,
uint256[] calldata _powers
) external;
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity >=0.8.0;
interface IWithdrawInbox {
function withdraw(
uint64 _wdSeq,
address _receiver,
uint64 _toChain,
uint64[] calldata _fromChains,
address[] calldata _tokens,
uint32[] calldata _ratios,
uint32[] calldata _slippages
) external;
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.8.9;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
abstract contract Pauser is Ownable, Pausable {
mapping(address => bool) public pausers;
event PauserAdded(address account);
event PauserRemoved(address account);
constructor() {
_addPauser(msg.sender);
}
modifier onlyPauser() {
require(isPauser(msg.sender), "Caller is not pauser");
_;
}
function pause() public onlyPauser {
_pause();
}
function unpause() public onlyPauser {
_unpause();
}
function isPauser(address account) public view returns (bool) {
return pausers[account];
}
function addPauser(address account) public onlyOwner {
_addPauser(account);
}
function removePauser(address account) public onlyOwner {
_removePauser(account);
}
function renouncePauser() public {
_removePauser(msg.sender);
}
function _addPauser(address account) private {
require(!isPauser(account), "Account is already pauser");
pausers[account] = true;
emit PauserAdded(account);
}
function _removePauser(address account) private {
require(isPauser(account), "Account is not pauser");
pausers[account] = false;
emit PauserRemoved(account);
}
}
// 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 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/Pausable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.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: GPL-3.0-only
pragma solidity 0.8.9;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {DataTypes as dt} from "./DataTypes.sol";
import "../safeguard/Pauser.sol";
import "./Staking.sol";
/**
* @title A contract to hold and distribute CELR staking rewards.
*/
contract StakingReward is Pauser {
using SafeERC20 for IERC20;
Staking public immutable staking;
// recipient => CELR reward amount
mapping(address => uint256) public claimedRewardAmounts;
event StakingRewardClaimed(address indexed recipient, uint256 reward);
event StakingRewardContributed(address indexed contributor, uint256 contribution);
constructor(Staking _staking) {
staking = _staking;
}
/**
* @notice Claim reward
* @dev Here we use cumulative reward to make claim process idempotent
* @param _rewardRequest reward request bytes coded in protobuf
* @param _sigs list of validator signatures
*/
function claimReward(bytes calldata _rewardRequest, bytes[] calldata _sigs) external whenNotPaused {
bytes32 domain = keccak256(abi.encodePacked(block.chainid, address(this), "StakingReward"));
staking.verifySignatures(abi.encodePacked(domain, _rewardRequest), _sigs);
PbStaking.StakingReward memory reward = PbStaking.decStakingReward(_rewardRequest);
uint256 cumulativeRewardAmount = reward.cumulativeRewardAmount;
uint256 newReward = cumulativeRewardAmount - claimedRewardAmounts[reward.recipient];
require(newReward > 0, "No new reward");
claimedRewardAmounts[reward.recipient] = cumulativeRewardAmount;
staking.CELER_TOKEN().safeTransfer(reward.recipient, newReward);
emit StakingRewardClaimed(reward.recipient, newReward);
}
/**
* @notice Contribute CELR tokens to the reward pool
* @param _amount the amount of CELR token to contribute
*/
function contributeToRewardPool(uint256 _amount) external whenNotPaused {
address contributor = msg.sender;
IERC20(staking.CELER_TOKEN()).safeTransferFrom(contributor, address(this), _amount);
emit StakingRewardContributed(contributor, _amount);
}
/**
* @notice Owner drains CELR tokens when the contract is paused
* @dev emergency use only
* @param _amount drained CELR token amount
*/
function drainToken(uint256 _amount) external whenPaused onlyOwner {
IERC20(staking.CELER_TOKEN()).safeTransfer(msg.sender, _amount);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.8.9;
library DataTypes {
uint256 constant CELR_DECIMAL = 1e18;
uint256 constant MAX_INT = 2**256 - 1;
uint256 constant COMMISSION_RATE_BASE = 10000; // 1 commissionRate means 0.01%
uint256 constant MAX_UNDELEGATION_ENTRIES = 10;
uint256 constant SLASH_FACTOR_DECIMAL = 1e6;
enum ValidatorStatus {
Null,
Unbonded,
Unbonding,
Bonded
}
enum ParamName {
ProposalDeposit,
VotingPeriod,
UnbondingPeriod,
MaxBondedValidators,
MinValidatorTokens,
MinSelfDelegation,
AdvanceNoticePeriod,
ValidatorBondInterval,
MaxSlashFactor
}
struct Undelegation {
uint256 shares;
uint256 creationBlock;
}
struct Undelegations {
mapping(uint256 => Undelegation) queue;
uint32 head;
uint32 tail;
}
struct Delegator {
uint256 shares;
Undelegations undelegations;
}
struct Validator {
ValidatorStatus status;
address signer;
uint256 tokens; // sum of all tokens delegated to this validator
uint256 shares; // sum of all delegation shares
uint256 undelegationTokens; // tokens being undelegated
uint256 undelegationShares; // shares of tokens being undelegated
mapping(address => Delegator) delegators;
uint256 minSelfDelegation;
uint64 bondBlock; // cannot become bonded before this block
uint64 unbondBlock; // cannot become unbonded before this block
uint64 commissionRate; // equal to real commission rate * COMMISSION_RATE_BASE
}
// used for external view output
struct ValidatorTokens {
address valAddr;
uint256 tokens;
}
// used for external view output
struct ValidatorInfo {
address valAddr;
ValidatorStatus status;
address signer;
uint256 tokens;
uint256 shares;
uint256 minSelfDelegation;
uint64 commissionRate;
}
// used for external view output
struct DelegatorInfo {
address valAddr;
uint256 tokens;
uint256 shares;
Undelegation[] undelegations;
uint256 undelegationTokens;
uint256 withdrawableUndelegationTokens;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.8.9;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import {DataTypes as dt} from "./DataTypes.sol";
import "../interfaces/ISigsVerifier.sol";
import "../libraries/PbStaking.sol";
import "../safeguard/Pauser.sol";
import "../safeguard/Whitelist.sol";
/**
* @title A Staking contract shared by all external sidechains and apps
*/
contract Staking is ISigsVerifier, Pauser, Whitelist {
using SafeERC20 for IERC20;
using ECDSA for bytes32;
IERC20 public immutable CELER_TOKEN;
uint256 public bondedTokens;
uint256 public nextBondBlock;
address[] public valAddrs;
address[] public bondedValAddrs;
mapping(address => dt.Validator) public validators; // key is valAddr
mapping(address => address) public signerVals; // signerAddr -> valAddr
mapping(uint256 => bool) public slashNonces;
mapping(dt.ParamName => uint256) public params;
address public govContract;
address public rewardContract;
uint256 public forfeiture;
/* Events */
event ValidatorNotice(address indexed valAddr, string key, bytes data, address from);
event ValidatorStatusUpdate(address indexed valAddr, dt.ValidatorStatus indexed status);
event DelegationUpdate(
address indexed valAddr,
address indexed delAddr,
uint256 valTokens,
uint256 delShares,
int256 tokenDiff
);
event Undelegated(address indexed valAddr, address indexed delAddr, uint256 amount);
event Slash(address indexed valAddr, uint64 nonce, uint256 slashAmt);
event SlashAmtCollected(address indexed recipient, uint256 amount);
/**
* @notice Staking constructor
* @param _celerTokenAddress address of Celer Token Contract
* @param _proposalDeposit required deposit amount for a governance proposal
* @param _votingPeriod voting timeout for a governance proposal
* @param _unbondingPeriod the locking time for funds locked before withdrawn
* @param _maxBondedValidators the maximum number of bonded validators
* @param _minValidatorTokens the global minimum token amount requirement for bonded validator
* @param _minSelfDelegation minimal amount of self-delegated tokens
* @param _advanceNoticePeriod the wait time after the announcement and prior to the effective date of an update
* @param _validatorBondInterval min interval between bondValidator
* @param _maxSlashFactor maximal slashing factor (1e6 = 100%)
*/
constructor(
address _celerTokenAddress,
uint256 _proposalDeposit,
uint256 _votingPeriod,
uint256 _unbondingPeriod,
uint256 _maxBondedValidators,
uint256 _minValidatorTokens,
uint256 _minSelfDelegation,
uint256 _advanceNoticePeriod,
uint256 _validatorBondInterval,
uint256 _maxSlashFactor
) {
CELER_TOKEN = IERC20(_celerTokenAddress);
params[dt.ParamName.ProposalDeposit] = _proposalDeposit;
params[dt.ParamName.VotingPeriod] = _votingPeriod;
params[dt.ParamName.UnbondingPeriod] = _unbondingPeriod;
params[dt.ParamName.MaxBondedValidators] = _maxBondedValidators;
params[dt.ParamName.MinValidatorTokens] = _minValidatorTokens;
params[dt.ParamName.MinSelfDelegation] = _minSelfDelegation;
params[dt.ParamName.AdvanceNoticePeriod] = _advanceNoticePeriod;
params[dt.ParamName.ValidatorBondInterval] = _validatorBondInterval;
params[dt.ParamName.MaxSlashFactor] = _maxSlashFactor;
}
receive() external payable {}
/*********************************
* External and Public Functions *
*********************************/
/**
* @notice Initialize a validator candidate
* @param _signer signer address
* @param _minSelfDelegation minimal amount of tokens staked by the validator itself
* @param _commissionRate the self-declaimed commission rate
*/
function initializeValidator(
address _signer,
uint256 _minSelfDelegation,
uint64 _commissionRate
) external whenNotPaused onlyWhitelisted {
address valAddr = msg.sender;
dt.Validator storage validator = validators[valAddr];
require(validator.status == dt.ValidatorStatus.Null, "Validator is initialized");
require(validators[_signer].status == dt.ValidatorStatus.Null, "Signer is other validator");
require(signerVals[valAddr] == address(0), "Validator is other signer");
require(signerVals[_signer] == address(0), "Signer already used");
require(_commissionRate <= dt.COMMISSION_RATE_BASE, "Invalid commission rate");
require(_minSelfDelegation >= params[dt.ParamName.MinSelfDelegation], "Insufficient min self delegation");
validator.signer = _signer;
validator.status = dt.ValidatorStatus.Unbonded;
validator.minSelfDelegation = _minSelfDelegation;
validator.commissionRate = _commissionRate;
valAddrs.push(valAddr);
signerVals[_signer] = valAddr;
delegate(valAddr, _minSelfDelegation);
emit ValidatorNotice(valAddr, "init", abi.encode(_signer, _minSelfDelegation, _commissionRate), address(0));
}
/**
* @notice Update validator signer address
* @param _signer signer address
*/
function updateValidatorSigner(address _signer) external {
address valAddr = msg.sender;
dt.Validator storage validator = validators[valAddr];
require(validator.status != dt.ValidatorStatus.Null, "Validator not initialized");
require(signerVals[_signer] == address(0), "Signer already used");
if (_signer != valAddr) {
require(validators[_signer].status == dt.ValidatorStatus.Null, "Signer is other validator");
}
delete signerVals[validator.signer];
validator.signer = _signer;
signerVals[_signer] = valAddr;
emit ValidatorNotice(valAddr, "signer", abi.encode(_signer), address(0));
}
/**
* @notice Candidate claims to become a bonded validator
* @dev caller can be either validator owner or signer
*/
function bondValidator() external {
address valAddr = msg.sender;
if (signerVals[msg.sender] != address(0)) {
valAddr = signerVals[msg.sender];
}
dt.Validator storage validator = validators[valAddr];
require(
validator.status == dt.ValidatorStatus.Unbonded || validator.status == dt.ValidatorStatus.Unbonding,
"Invalid validator status"
);
require(block.number >= validator.bondBlock, "Bond block not reached");
require(block.number >= nextBondBlock, "Too frequent validator bond");
nextBondBlock = block.number + params[dt.ParamName.ValidatorBondInterval];
require(hasMinRequiredTokens(valAddr, true), "Not have min tokens");
uint256 maxBondedValidators = params[dt.ParamName.MaxBondedValidators];
// if the number of validators has not reached the max_validator_num,
// add validator directly
if (bondedValAddrs.length < maxBondedValidators) {
_bondValidator(valAddr);
_decentralizationCheck(validator.tokens);
return;
}
// if the number of validators has already reached the max_validator_num,
// add validator only if its tokens is more than the current least bonded validator tokens
uint256 minTokens = dt.MAX_INT;
uint256 minTokensIndex;
for (uint256 i = 0; i < maxBondedValidators; i++) {
if (validators[bondedValAddrs[i]].tokens < minTokens) {
minTokensIndex = i;
minTokens = validators[bondedValAddrs[i]].tokens;
if (minTokens == 0) {
break;
}
}
}
require(validator.tokens > minTokens, "Insufficient tokens");
_replaceBondedValidator(valAddr, minTokensIndex);
_decentralizationCheck(validator.tokens);
}
/**
* @notice Confirm validator status from Unbonding to Unbonded
* @param _valAddr the address of the validator
*/
function confirmUnbondedValidator(address _valAddr) external {
dt.Validator storage validator = validators[_valAddr];
require(validator.status == dt.ValidatorStatus.Unbonding, "Validator not unbonding");
require(block.number >= validator.unbondBlock, "Unbond block not reached");
validator.status = dt.ValidatorStatus.Unbonded;
delete validator.unbondBlock;
emit ValidatorStatusUpdate(_valAddr, dt.ValidatorStatus.Unbonded);
}
/**
* @notice Delegate CELR tokens to a validator
* @dev Minimal amount per delegate operation is 1 CELR
* @param _valAddr validator to delegate
* @param _tokens the amount of delegated CELR tokens
*/
function delegate(address _valAddr, uint256 _tokens) public whenNotPaused {
address delAddr = msg.sender;
require(_tokens >= dt.CELR_DECIMAL, "Minimal amount is 1 CELR");
dt.Validator storage validator = validators[_valAddr];
require(validator.status != dt.ValidatorStatus.Null, "Validator is not initialized");
uint256 shares = _tokenToShare(_tokens, validator.tokens, validator.shares);
dt.Delegator storage delegator = validator.delegators[delAddr];
delegator.shares += shares;
validator.shares += shares;
validator.tokens += _tokens;
if (validator.status == dt.ValidatorStatus.Bonded) {
bondedTokens += _tokens;
_decentralizationCheck(validator.tokens);
}
CELER_TOKEN.safeTransferFrom(delAddr, address(this), _tokens);
emit DelegationUpdate(_valAddr, delAddr, validator.tokens, delegator.shares, int256(_tokens));
}
/**
* @notice Undelegate shares from a validator
* @dev Tokens are delegated by the msgSender to the validator
* @param _valAddr the address of the validator
* @param _shares undelegate shares
*/
function undelegateShares(address _valAddr, uint256 _shares) external {
require(_shares >= dt.CELR_DECIMAL, "Minimal amount is 1 share");
dt.Validator storage validator = validators[_valAddr];
require(validator.status != dt.ValidatorStatus.Null, "Validator is not initialized");
uint256 tokens = _shareToToken(_shares, validator.tokens, validator.shares);
_undelegate(validator, _valAddr, tokens, _shares);
}
/**
* @notice Undelegate shares from a validator
* @dev Tokens are delegated by the msgSender to the validator
* @param _valAddr the address of the validator
* @param _tokens undelegate tokens
*/
function undelegateTokens(address _valAddr, uint256 _tokens) external {
require(_tokens >= dt.CELR_DECIMAL, "Minimal amount is 1 CELR");
dt.Validator storage validator = validators[_valAddr];
require(validator.status != dt.ValidatorStatus.Null, "Validator is not initialized");
uint256 shares = _tokenToShare(_tokens, validator.tokens, validator.shares);
_undelegate(validator, _valAddr, _tokens, shares);
}
/**
* @notice Complete pending undelegations from a validator
* @param _valAddr the address of the validator
*/
function completeUndelegate(address _valAddr) external {
address delAddr = msg.sender;
dt.Validator storage validator = validators[_valAddr];
require(validator.status != dt.ValidatorStatus.Null, "Validator is not initialized");
dt.Delegator storage delegator = validator.delegators[delAddr];
uint256 unbondingPeriod = params[dt.ParamName.UnbondingPeriod];
bool isUnbonded = validator.status == dt.ValidatorStatus.Unbonded;
// for all pending undelegations
uint32 i;
uint256 undelegationShares;
for (i = delegator.undelegations.head; i < delegator.undelegations.tail; i++) {
if (isUnbonded || delegator.undelegations.queue[i].creationBlock + unbondingPeriod <= block.number) {
// complete undelegation when the validator becomes unbonded or
// the unbondingPeriod for the pending undelegation is up.
undelegationShares += delegator.undelegations.queue[i].shares;
delete delegator.undelegations.queue[i];
continue;
}
break;
}
delegator.undelegations.head = i;
require(undelegationShares > 0, "No undelegation ready to be completed");
uint256 tokens = _shareToToken(undelegationShares, validator.undelegationTokens, validator.undelegationShares);
validator.undelegationShares -= undelegationShares;
validator.undelegationTokens -= tokens;
CELER_TOKEN.safeTransfer(delAddr, tokens);
emit Undelegated(_valAddr, delAddr, tokens);
}
/**
* @notice Update commission rate
* @param _newRate new commission rate
*/
function updateCommissionRate(uint64 _newRate) external {
address valAddr = msg.sender;
dt.Validator storage validator = validators[valAddr];
require(validator.status != dt.ValidatorStatus.Null, "Validator is not initialized");
require(_newRate <= dt.COMMISSION_RATE_BASE, "Invalid new rate");
validator.commissionRate = _newRate;
emit ValidatorNotice(valAddr, "commission", abi.encode(_newRate), address(0));
}
/**
* @notice Update minimal self delegation value
* @param _minSelfDelegation minimal amount of tokens staked by the validator itself
*/
function updateMinSelfDelegation(uint256 _minSelfDelegation) external {
address valAddr = msg.sender;
dt.Validator storage validator = validators[valAddr];
require(validator.status != dt.ValidatorStatus.Null, "Validator is not initialized");
require(_minSelfDelegation >= params[dt.ParamName.MinSelfDelegation], "Insufficient min self delegation");
if (_minSelfDelegation < validator.minSelfDelegation) {
require(validator.status != dt.ValidatorStatus.Bonded, "Validator is bonded");
validator.bondBlock = uint64(block.number + params[dt.ParamName.AdvanceNoticePeriod]);
}
validator.minSelfDelegation = _minSelfDelegation;
emit ValidatorNotice(valAddr, "min-self-delegation", abi.encode(_minSelfDelegation), address(0));
}
/**
* @notice Slash a validator and its delegators
* @param _slashRequest slash request bytes coded in protobuf
* @param _sigs list of validator signatures
*/
function slash(bytes calldata _slashRequest, bytes[] calldata _sigs) external whenNotPaused {
bytes32 domain = keccak256(abi.encodePacked(block.chainid, address(this), "Slash"));
verifySignatures(abi.encodePacked(domain, _slashRequest), _sigs);
PbStaking.Slash memory request = PbStaking.decSlash(_slashRequest);
require(block.timestamp < request.expireTime, "Slash expired");
require(request.slashFactor <= dt.SLASH_FACTOR_DECIMAL, "Invalid slash factor");
require(request.slashFactor <= params[dt.ParamName.MaxSlashFactor], "Exceed max slash factor");
require(!slashNonces[request.nonce], "Used slash nonce");
slashNonces[request.nonce] = true;
address valAddr = request.validator;
dt.Validator storage validator = validators[valAddr];
require(
validator.status == dt.ValidatorStatus.Bonded || validator.status == dt.ValidatorStatus.Unbonding,
"Invalid validator status"
);
// slash delegated tokens
uint256 slashAmt = (validator.tokens * request.slashFactor) / dt.SLASH_FACTOR_DECIMAL;
validator.tokens -= slashAmt;
if (validator.status == dt.ValidatorStatus.Bonded) {
bondedTokens -= slashAmt;
if (request.jailPeriod > 0 || !hasMinRequiredTokens(valAddr, true)) {
_unbondValidator(valAddr);
}
}
if (validator.status == dt.ValidatorStatus.Unbonding && request.jailPeriod > 0) {
validator.bondBlock = uint64(block.number + request.jailPeriod);
}
emit DelegationUpdate(valAddr, address(0), validator.tokens, 0, -int256(slashAmt));
// slash pending undelegations
uint256 slashUndelegation = (validator.undelegationTokens * request.slashFactor) / dt.SLASH_FACTOR_DECIMAL;
validator.undelegationTokens -= slashUndelegation;
slashAmt += slashUndelegation;
uint256 collectAmt;
for (uint256 i = 0; i < request.collectors.length; i++) {
PbStaking.AcctAmtPair memory collector = request.collectors[i];
if (collectAmt + collector.amount > slashAmt) {
collector.amount = slashAmt - collectAmt;
}
if (collector.amount > 0) {
collectAmt += collector.amount;
if (collector.account == address(0)) {
CELER_TOKEN.safeTransfer(msg.sender, collector.amount);
emit SlashAmtCollected(msg.sender, collector.amount);
} else {
CELER_TOKEN.safeTransfer(collector.account, collector.amount);
emit SlashAmtCollected(collector.account, collector.amount);
}
}
}
forfeiture += slashAmt - collectAmt;
emit Slash(valAddr, request.nonce, slashAmt);
}
function collectForfeiture() external {
require(forfeiture > 0, "Nothing to collect");
CELER_TOKEN.safeTransfer(rewardContract, forfeiture);
forfeiture = 0;
}
/**
* @notice Validator notice event, could be triggered by anyone
*/
function validatorNotice(
address _valAddr,
string calldata _key,
bytes calldata _data
) external {
dt.Validator storage validator = validators[_valAddr];
require(validator.status != dt.ValidatorStatus.Null, "Validator is not initialized");
emit ValidatorNotice(_valAddr, _key, _data, msg.sender);
}
function setParamValue(dt.ParamName _name, uint256 _value) external {
require(msg.sender == govContract, "Caller is not gov contract");
if (_name == dt.ParamName.MaxBondedValidators) {
require(bondedValAddrs.length <= _value, "invalid value");
}
params[_name] = _value;
}
function setGovContract(address _addr) external onlyOwner {
govContract = _addr;
}
function setRewardContract(address _addr) external onlyOwner {
rewardContract = _addr;
}
/**
* @notice Set max slash factor
*/
function setMaxSlashFactor(uint256 _maxSlashFactor) external onlyOwner {
params[dt.ParamName.MaxSlashFactor] = _maxSlashFactor;
}
/**
* @notice Owner drains tokens when the contract is paused
* @dev emergency use only
* @param _amount drained token amount
*/
function drainToken(uint256 _amount) external whenPaused onlyOwner {
CELER_TOKEN.safeTransfer(msg.sender, _amount);
}
/**************************
* Public View Functions *
**************************/
/**
* @notice Validate if a message is signed by quorum tokens
* @param _msg signed message
* @param _sigs list of validator signatures
*/
function verifySignatures(bytes memory _msg, bytes[] memory _sigs) public view returns (bool) {
bytes32 hash = keccak256(_msg).toEthSignedMessageHash();
uint256 signedTokens;
address prev = address(0);
uint256 quorum = getQuorumTokens();
for (uint256 i = 0; i < _sigs.length; i++) {
address signer = hash.recover(_sigs[i]);
require(signer > prev, "Signers not in ascending order");
prev = signer;
dt.Validator storage validator = validators[signerVals[signer]];
if (validator.status != dt.ValidatorStatus.Bonded) {
continue;
}
signedTokens += validator.tokens;
if (signedTokens >= quorum) {
return true;
}
}
revert("Quorum not reached");
}
/**
* @notice Verifies that a message is signed by a quorum among the validators.
* @param _msg signed message
* @param _sigs the list of signatures
*/
function verifySigs(
bytes memory _msg,
bytes[] calldata _sigs,
address[] calldata,
uint256[] calldata
) public view override {
require(verifySignatures(_msg, _sigs), "Failed to verify sigs");
}
/**
* @notice Get quorum amount of tokens
* @return the quorum amount
*/
function getQuorumTokens() public view returns (uint256) {
return (bondedTokens * 2) / 3 + 1;
}
/**
* @notice Get validator info
* @param _valAddr the address of the validator
* @return Validator token amount
*/
function getValidatorTokens(address _valAddr) public view returns (uint256) {
return validators[_valAddr].tokens;
}
/**
* @notice Get validator info
* @param _valAddr the address of the validator
* @return Validator status
*/
function getValidatorStatus(address _valAddr) public view returns (dt.ValidatorStatus) {
return validators[_valAddr].status;
}
/**
* @notice Check the given address is a validator or not
* @param _addr the address to check
* @return the given address is a validator or not
*/
function isBondedValidator(address _addr) public view returns (bool) {
return validators[_addr].status == dt.ValidatorStatus.Bonded;
}
/**
* @notice Get the number of validators
* @return the number of validators
*/
function getValidatorNum() public view returns (uint256) {
return valAddrs.length;
}
/**
* @notice Get the number of bonded validators
* @return the number of bonded validators
*/
function getBondedValidatorNum() public view returns (uint256) {
return bondedValAddrs.length;
}
/**
* @return addresses and token amounts of bonded validators
*/
function getBondedValidatorsTokens() public view returns (dt.ValidatorTokens[] memory) {
dt.ValidatorTokens[] memory infos = new dt.ValidatorTokens[](bondedValAddrs.length);
for (uint256 i = 0; i < bondedValAddrs.length; i++) {
address valAddr = bondedValAddrs[i];
infos[i] = dt.ValidatorTokens(valAddr, validators[valAddr].tokens);
}
return infos;
}
/**
* @notice Check if min token requirements are met
* @param _valAddr the address of the validator
* @param _checkSelfDelegation check self delegation
*/
function hasMinRequiredTokens(address _valAddr, bool _checkSelfDelegation) public view returns (bool) {
dt.Validator storage v = validators[_valAddr];
uint256 valTokens = v.tokens;
if (valTokens < params[dt.ParamName.MinValidatorTokens]) {
return false;
}
if (_checkSelfDelegation) {
uint256 selfDelegation = _shareToToken(v.delegators[_valAddr].shares, valTokens, v.shares);
if (selfDelegation < v.minSelfDelegation) {
return false;
}
}
return true;
}
/**
* @notice Get the delegator info of a specific validator
* @param _valAddr the address of the validator
* @param _delAddr the address of the delegator
* @return DelegatorInfo from the given validator
*/
function getDelegatorInfo(address _valAddr, address _delAddr) public view returns (dt.DelegatorInfo memory) {
dt.Validator storage validator = validators[_valAddr];
dt.Delegator storage d = validator.delegators[_delAddr];
uint256 tokens = _shareToToken(d.shares, validator.tokens, validator.shares);
uint256 undelegationShares;
uint256 withdrawableUndelegationShares;
uint256 unbondingPeriod = params[dt.ParamName.UnbondingPeriod];
bool isUnbonded = validator.status == dt.ValidatorStatus.Unbonded;
uint256 len = d.undelegations.tail - d.undelegations.head;
dt.Undelegation[] memory undelegations = new dt.Undelegation[](len);
for (uint256 i = 0; i < len; i++) {
undelegations[i] = d.undelegations.queue[i + d.undelegations.head];
undelegationShares += undelegations[i].shares;
if (isUnbonded || undelegations[i].creationBlock + unbondingPeriod <= block.number) {
withdrawableUndelegationShares += undelegations[i].shares;
}
}
uint256 undelegationTokens = _shareToToken(
undelegationShares,
validator.undelegationTokens,
validator.undelegationShares
);
uint256 withdrawableUndelegationTokens = _shareToToken(
withdrawableUndelegationShares,
validator.undelegationTokens,
validator.undelegationShares
);
return
dt.DelegatorInfo(
_valAddr,
tokens,
d.shares,
undelegations,
undelegationTokens,
withdrawableUndelegationTokens
);
}
/**
* @notice Get the value of a specific uint parameter
* @param _name the key of this parameter
* @return the value of this parameter
*/
function getParamValue(dt.ParamName _name) public view returns (uint256) {
return params[_name];
}
/*********************
* Private Functions *
*********************/
function _undelegate(
dt.Validator storage validator,
address _valAddr,
uint256 _tokens,
uint256 _shares
) private {
address delAddr = msg.sender;
dt.Delegator storage delegator = validator.delegators[delAddr];
delegator.shares -= _shares;
validator.shares -= _shares;
validator.tokens -= _tokens;
if (validator.tokens != validator.shares && delegator.shares <= 2) {
// Remove residual share caused by rounding error when total shares and tokens are not equal
validator.shares -= delegator.shares;
delegator.shares = 0;
}
require(delegator.shares == 0 || delegator.shares >= dt.CELR_DECIMAL, "not enough remaining shares");
if (validator.status == dt.ValidatorStatus.Unbonded) {
CELER_TOKEN.safeTransfer(delAddr, _tokens);
emit Undelegated(_valAddr, delAddr, _tokens);
return;
} else if (validator.status == dt.ValidatorStatus.Bonded) {
bondedTokens -= _tokens;
if (!hasMinRequiredTokens(_valAddr, delAddr == _valAddr)) {
_unbondValidator(_valAddr);
}
}
require(
delegator.undelegations.tail - delegator.undelegations.head < dt.MAX_UNDELEGATION_ENTRIES,
"Exceed max undelegation entries"
);
uint256 undelegationShares = _tokenToShare(_tokens, validator.undelegationTokens, validator.undelegationShares);
validator.undelegationShares += undelegationShares;
validator.undelegationTokens += _tokens;
dt.Undelegation storage undelegation = delegator.undelegations.queue[delegator.undelegations.tail];
undelegation.shares = undelegationShares;
undelegation.creationBlock = block.number;
delegator.undelegations.tail++;
emit DelegationUpdate(_valAddr, delAddr, validator.tokens, delegator.shares, -int256(_tokens));
}
/**
* @notice Set validator to bonded
* @param _valAddr the address of the validator
*/
function _setBondedValidator(address _valAddr) private {
dt.Validator storage validator = validators[_valAddr];
validator.status = dt.ValidatorStatus.Bonded;
delete validator.unbondBlock;
bondedTokens += validator.tokens;
emit ValidatorStatusUpdate(_valAddr, dt.ValidatorStatus.Bonded);
}
/**
* @notice Set validator to unbonding
* @param _valAddr the address of the validator
*/
function _setUnbondingValidator(address _valAddr) private {
dt.Validator storage validator = validators[_valAddr];
validator.status = dt.ValidatorStatus.Unbonding;
validator.unbondBlock = uint64(block.number + params[dt.ParamName.UnbondingPeriod]);
bondedTokens -= validator.tokens;
emit ValidatorStatusUpdate(_valAddr, dt.ValidatorStatus.Unbonding);
}
/**
* @notice Bond a validator
* @param _valAddr the address of the validator
*/
function _bondValidator(address _valAddr) private {
bondedValAddrs.push(_valAddr);
_setBondedValidator(_valAddr);
}
/**
* @notice Replace a bonded validator
* @param _valAddr the address of the new validator
* @param _index the index of the validator to be replaced
*/
function _replaceBondedValidator(address _valAddr, uint256 _index) private {
_setUnbondingValidator(bondedValAddrs[_index]);
bondedValAddrs[_index] = _valAddr;
_setBondedValidator(_valAddr);
}
/**
* @notice Unbond a validator
* @param _valAddr validator to be removed
*/
function _unbondValidator(address _valAddr) private {
uint256 lastIndex = bondedValAddrs.length - 1;
for (uint256 i = 0; i < bondedValAddrs.length; i++) {
if (bondedValAddrs[i] == _valAddr) {
if (i < lastIndex) {
bondedValAddrs[i] = bondedValAddrs[lastIndex];
}
bondedValAddrs.pop();
_setUnbondingValidator(_valAddr);
return;
}
}
revert("Not bonded validator");
}
/**
* @notice Check if one validator has too much power
* @param _valTokens token amounts of the validator
*/
function _decentralizationCheck(uint256 _valTokens) private view {
uint256 bondedValNum = bondedValAddrs.length;
if (bondedValNum == 2 || bondedValNum == 3) {
require(_valTokens < getQuorumTokens(), "Single validator should not have quorum tokens");
} else if (bondedValNum > 3) {
require(_valTokens < bondedTokens / 3, "Single validator should not have 1/3 tokens");
}
}
/**
* @notice Convert token to share
*/
function _tokenToShare(
uint256 tokens,
uint256 totalTokens,
uint256 totalShares
) private pure returns (uint256) {
if (totalTokens == 0) {
return tokens;
}
return (tokens * totalShares) / totalTokens;
}
/**
* @notice Convert share to token
*/
function _shareToToken(
uint256 shares,
uint256 totalTokens,
uint256 totalShares
) private pure returns (uint256) {
if (totalShares == 0) {
return shares;
}
return (shares * totalTokens) / totalShares;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.0;
import "../Strings.sol";
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
uint8 v = uint8((uint256(vs) >> 255) + 27);
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity >=0.8.0;
interface ISigsVerifier {
/**
* @notice Verifies that a message is signed by a quorum among the signers.
* @param _msg signed message
* @param _sigs list of signatures sorted by signer addresses in ascending order
* @param _signers sorted list of current signers
* @param _powers powers of current signers
*/
function verifySigs(
bytes memory _msg,
bytes[] calldata _sigs,
address[] calldata _signers,
uint256[] calldata _powers
) external view;
}
// SPDX-License-Identifier: GPL-3.0-only
// Code generated by protoc-gen-sol. DO NOT EDIT.
// source: contracts/libraries/proto/staking.proto
pragma solidity 0.8.9;
import "./Pb.sol";
library PbStaking {
using Pb for Pb.Buffer; // so we can call Pb funcs on Buffer obj
struct StakingReward {
address recipient; // tag: 1
uint256 cumulativeRewardAmount; // tag: 2
} // end struct StakingReward
function decStakingReward(bytes memory raw) internal pure returns (StakingReward memory m) {
Pb.Buffer memory buf = Pb.fromBytes(raw);
uint256 tag;
Pb.WireType wire;
while (buf.hasMore()) {
(tag, wire) = buf.decKey();
if (false) {}
// solidity has no switch/case
else if (tag == 1) {
m.recipient = Pb._address(buf.decBytes());
} else if (tag == 2) {
m.cumulativeRewardAmount = Pb._uint256(buf.decBytes());
} else {
buf.skipValue(wire);
} // skip value of unknown tag
}
} // end decoder StakingReward
struct Slash {
address validator; // tag: 1
uint64 nonce; // tag: 2
uint64 slashFactor; // tag: 3
uint64 expireTime; // tag: 4
uint64 jailPeriod; // tag: 5
AcctAmtPair[] collectors; // tag: 6
} // end struct Slash
function decSlash(bytes memory raw) internal pure returns (Slash memory m) {
Pb.Buffer memory buf = Pb.fromBytes(raw);
uint256[] memory cnts = buf.cntTags(6);
m.collectors = new AcctAmtPair[](cnts[6]);
cnts[6] = 0; // reset counter for later use
uint256 tag;
Pb.WireType wire;
while (buf.hasMore()) {
(tag, wire) = buf.decKey();
if (false) {}
// solidity has no switch/case
else if (tag == 1) {
m.validator = Pb._address(buf.decBytes());
} else if (tag == 2) {
m.nonce = uint64(buf.decVarint());
} else if (tag == 3) {
m.slashFactor = uint64(buf.decVarint());
} else if (tag == 4) {
m.expireTime = uint64(buf.decVarint());
} else if (tag == 5) {
m.jailPeriod = uint64(buf.decVarint());
} else if (tag == 6) {
m.collectors[cnts[6]] = decAcctAmtPair(buf.decBytes());
cnts[6]++;
} else {
buf.skipValue(wire);
} // skip value of unknown tag
}
} // end decoder Slash
struct AcctAmtPair {
address account; // tag: 1
uint256 amount; // tag: 2
} // end struct AcctAmtPair
function decAcctAmtPair(bytes memory raw) internal pure returns (AcctAmtPair memory m) {
Pb.Buffer memory buf = Pb.fromBytes(raw);
uint256 tag;
Pb.WireType wire;
while (buf.hasMore()) {
(tag, wire) = buf.decKey();
if (false) {}
// solidity has no switch/case
else if (tag == 1) {
m.account = Pb._address(buf.decBytes());
} else if (tag == 2) {
m.amount = Pb._uint256(buf.decBytes());
} else {
buf.skipValue(wire);
} // skip value of unknown tag
}
} // end decoder AcctAmtPair
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.8.9;
import "@openzeppelin/contracts/access/Ownable.sol";
abstract contract Whitelist is Ownable {
mapping(address => bool) public whitelist;
bool public whitelistEnabled;
event WhitelistedAdded(address account);
event WhitelistedRemoved(address account);
modifier onlyWhitelisted() {
if (whitelistEnabled) {
require(isWhitelisted(msg.sender), "Caller is not whitelisted");
}
_;
}
/**
* @notice Set whitelistEnabled
*/
function setWhitelistEnabled(bool _whitelistEnabled) external onlyOwner {
whitelistEnabled = _whitelistEnabled;
}
/**
* @notice Add an account to whitelist
*/
function addWhitelisted(address account) external onlyOwner {
require(!isWhitelisted(account), "Already whitelisted");
whitelist[account] = true;
emit WhitelistedAdded(account);
}
/**
* @notice Remove an account from whitelist
*/
function removeWhitelisted(address account) external onlyOwner {
require(isWhitelisted(account), "Not whitelisted");
whitelist[account] = false;
emit WhitelistedRemoved(account);
}
/**
* @return is account whitelisted
*/
function isWhitelisted(address account) public view returns (bool) {
return whitelist[account];
}
}
// 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: GPL-3.0-only
pragma solidity 0.8.9;
// runtime proto sol library
library Pb {
enum WireType {
Varint,
Fixed64,
LengthDelim,
StartGroup,
EndGroup,
Fixed32
}
struct Buffer {
uint256 idx; // the start index of next read. when idx=b.length, we're done
bytes b; // hold serialized proto msg, readonly
}
// create a new in-memory Buffer object from raw msg bytes
function fromBytes(bytes memory raw) internal pure returns (Buffer memory buf) {
buf.b = raw;
buf.idx = 0;
}
// whether there are unread bytes
function hasMore(Buffer memory buf) internal pure returns (bool) {
return buf.idx < buf.b.length;
}
// decode current field number and wiretype
function decKey(Buffer memory buf) internal pure returns (uint256 tag, WireType wiretype) {
uint256 v = decVarint(buf);
tag = v / 8;
wiretype = WireType(v & 7);
}
// count tag occurrences, return an array due to no memory map support
// have to create array for (maxtag+1) size. cnts[tag] = occurrences
// should keep buf.idx unchanged because this is only a count function
function cntTags(Buffer memory buf, uint256 maxtag) internal pure returns (uint256[] memory cnts) {
uint256 originalIdx = buf.idx;
cnts = new uint256[](maxtag + 1); // protobuf's tags are from 1 rather than 0
uint256 tag;
WireType wire;
while (hasMore(buf)) {
(tag, wire) = decKey(buf);
cnts[tag] += 1;
skipValue(buf, wire);
}
buf.idx = originalIdx;
}
// read varint from current buf idx, move buf.idx to next read, return the int value
function decVarint(Buffer memory buf) internal pure returns (uint256 v) {
bytes10 tmp; // proto int is at most 10 bytes (7 bits can be used per byte)
bytes memory bb = buf.b; // get buf.b mem addr to use in assembly
v = buf.idx; // use v to save one additional uint variable
assembly {
tmp := mload(add(add(bb, 32), v)) // load 10 bytes from buf.b[buf.idx] to tmp
}
uint256 b; // store current byte content
v = 0; // reset to 0 for return value
for (uint256 i = 0; i < 10; i++) {
assembly {
b := byte(i, tmp) // don't use tmp[i] because it does bound check and costs extra
}
v |= (b & 0x7F) << (i * 7);
if (b & 0x80 == 0) {
buf.idx += i + 1;
return v;
}
}
revert(); // i=10, invalid varint stream
}
// read length delimited field and return bytes
function decBytes(Buffer memory buf) internal pure returns (bytes memory b) {
uint256 len = decVarint(buf);
uint256 end = buf.idx + len;
require(end <= buf.b.length); // avoid overflow
b = new bytes(len);
bytes memory bufB = buf.b; // get buf.b mem addr to use in assembly
uint256 bStart;
uint256 bufBStart = buf.idx;
assembly {
bStart := add(b, 32)
bufBStart := add(add(bufB, 32), bufBStart)
}
for (uint256 i = 0; i < len; i += 32) {
assembly {
mstore(add(bStart, i), mload(add(bufBStart, i)))
}
}
buf.idx = end;
}
// return packed ints
function decPacked(Buffer memory buf) internal pure returns (uint256[] memory t) {
uint256 len = decVarint(buf);
uint256 end = buf.idx + len;
require(end <= buf.b.length); // avoid overflow
// array in memory must be init w/ known length
// so we have to create a tmp array w/ max possible len first
uint256[] memory tmp = new uint256[](len);
uint256 i = 0; // count how many ints are there
while (buf.idx < end) {
tmp[i] = decVarint(buf);
i++;
}
t = new uint256[](i); // init t with correct length
for (uint256 j = 0; j < i; j++) {
t[j] = tmp[j];
}
return t;
}
// move idx pass current value field, to beginning of next tag or msg end
function skipValue(Buffer memory buf, WireType wire) internal pure {
if (wire == WireType.Varint) {
decVarint(buf);
} else if (wire == WireType.LengthDelim) {
uint256 len = decVarint(buf);
buf.idx += len; // skip len bytes value data
require(buf.idx <= buf.b.length); // avoid overflow
} else {
revert();
} // unsupported wiretype
}
// type conversion help utils
function _bool(uint256 x) internal pure returns (bool v) {
return x != 0;
}
function _uint256(bytes memory b) internal pure returns (uint256 v) {
require(b.length <= 32); // b's length must be smaller than or equal to 32
assembly {
v := mload(add(b, 32))
} // load all 32bytes to v
v = v >> (8 * (32 - b.length)); // only first b.length is valid
}
function _address(bytes memory b) internal pure returns (address v) {
v = _addressPayable(b);
}
function _addressPayable(bytes memory b) internal pure returns (address payable v) {
require(b.length == 20);
//load 32bytes then shift right 12 bytes
assembly {
v := div(mload(add(b, 32)), 0x1000000000000000000000000)
}
}
function _bytes32(bytes memory b) internal pure returns (bytes32 v) {
require(b.length == 32);
assembly {
v := mload(add(b, 32))
}
}
// uint[] to uint8[]
function uint8s(uint256[] memory arr) internal pure returns (uint8[] memory t) {
t = new uint8[](arr.length);
for (uint256 i = 0; i < t.length; i++) {
t[i] = uint8(arr[i]);
}
}
function uint32s(uint256[] memory arr) internal pure returns (uint32[] memory t) {
t = new uint32[](arr.length);
for (uint256 i = 0; i < t.length; i++) {
t[i] = uint32(arr[i]);
}
}
function uint64s(uint256[] memory arr) internal pure returns (uint64[] memory t) {
t = new uint64[](arr.length);
for (uint256 i = 0; i < t.length; i++) {
t[i] = uint64(arr[i]);
}
}
function bools(uint256[] memory arr) internal pure returns (bool[] memory t) {
t = new bool[](arr.length);
for (uint256 i = 0; i < t.length; i++) {
t[i] = arr[i] != 0;
}
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.8.9;
import {DataTypes as dt} from "./DataTypes.sol";
import "./Staking.sol";
/**
* @title Viewer of the staking contract
* @notice Using a separate viewer contract to reduce staking contract size
*/
contract Viewer {
Staking public immutable staking;
constructor(Staking _staking) {
staking = _staking;
}
function getValidatorInfos() public view returns (dt.ValidatorInfo[] memory) {
uint256 valNum = staking.getValidatorNum();
dt.ValidatorInfo[] memory infos = new dt.ValidatorInfo[](valNum);
for (uint32 i = 0; i < valNum; i++) {
infos[i] = getValidatorInfo(staking.valAddrs(i));
}
return infos;
}
function getBondedValidatorInfos() public view returns (dt.ValidatorInfo[] memory) {
uint256 bondedValNum = staking.getBondedValidatorNum();
dt.ValidatorInfo[] memory infos = new dt.ValidatorInfo[](bondedValNum);
for (uint32 i = 0; i < bondedValNum; i++) {
infos[i] = getValidatorInfo(staking.bondedValAddrs(i));
}
return infos;
}
function getValidatorInfo(address _valAddr) public view returns (dt.ValidatorInfo memory) {
(
dt.ValidatorStatus status,
address signer,
uint256 tokens,
uint256 shares,
,
,
uint256 minSelfDelegation,
,
,
uint64 commissionRate
) = staking.validators(_valAddr);
return
dt.ValidatorInfo({
valAddr: _valAddr,
status: status,
signer: signer,
tokens: tokens,
shares: shares,
minSelfDelegation: minSelfDelegation,
commissionRate: commissionRate
});
}
function getDelegatorInfos(address _delAddr) public view returns (dt.DelegatorInfo[] memory) {
uint256 valNum = staking.getValidatorNum();
dt.DelegatorInfo[] memory infos = new dt.DelegatorInfo[](valNum);
uint32 num = 0;
for (uint32 i = 0; i < valNum; i++) {
address valAddr = staking.valAddrs(i);
infos[i] = staking.getDelegatorInfo(valAddr, _delAddr);
if (infos[i].shares != 0 || infos[i].undelegationTokens != 0) {
num++;
}
}
dt.DelegatorInfo[] memory res = new dt.DelegatorInfo[](num);
uint32 j = 0;
for (uint32 i = 0; i < valNum; i++) {
if (infos[i].shares != 0 || infos[i].undelegationTokens != 0) {
res[j] = infos[i];
j++;
}
}
return res;
}
function getDelegatorTokens(address _delAddr) public view returns (uint256, uint256) {
dt.DelegatorInfo[] memory infos = getDelegatorInfos(_delAddr);
uint256 tokens;
uint256 undelegationTokens;
for (uint32 i = 0; i < infos.length; i++) {
tokens += infos[i].tokens;
undelegationTokens += infos[i].undelegationTokens;
}
return (tokens, undelegationTokens);
}
/**
* @notice Get the minimum staking pool of all bonded validators
* @return the minimum staking pool of all bonded validators
*/
function getMinValidatorTokens() public view returns (uint256) {
uint256 bondedValNum = staking.getBondedValidatorNum();
if (bondedValNum < staking.params(dt.ParamName.MaxBondedValidators)) {
return 0;
}
uint256 minTokens = dt.MAX_INT;
for (uint256 i = 0; i < bondedValNum; i++) {
uint256 tokens = staking.getValidatorTokens(staking.bondedValAddrs(i));
if (tokens < minTokens) {
minTokens = tokens;
if (minTokens == 0) {
return 0;
}
}
}
return minTokens;
}
function shouldBondValidator(address _valAddr) public view returns (bool) {
(dt.ValidatorStatus status, , uint256 tokens, , , , , uint64 bondBlock, , ) = staking.validators(_valAddr);
if (status == dt.ValidatorStatus.Null || status == dt.ValidatorStatus.Bonded) {
return false;
}
if (block.number < bondBlock) {
return false;
}
if (!staking.hasMinRequiredTokens(_valAddr, true)) {
return false;
}
if (tokens <= getMinValidatorTokens()) {
return false;
}
uint256 nextBondBlock = staking.nextBondBlock();
if (block.number < nextBondBlock) {
return false;
}
return true;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.8.9;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {DataTypes as dt} from "./DataTypes.sol";
import "../libraries/PbSgn.sol";
import "../safeguard/Pauser.sol";
import "./Staking.sol";
/**
* @title contract of SGN chain
*/
contract SGN is Pauser {
using SafeERC20 for IERC20;
Staking public immutable staking;
bytes32[] public deposits;
// account -> (token -> amount)
mapping(address => mapping(address => uint256)) public withdrawnAmts;
mapping(address => bytes) public sgnAddrs;
/* Events */
event SgnAddrUpdate(address indexed valAddr, bytes oldAddr, bytes newAddr);
event Deposit(uint256 depositId, address account, address token, uint256 amount);
event Withdraw(address account, address token, uint256 amount);
/**
* @notice SGN constructor
* @dev Need to deploy Staking contract first before deploying SGN contract
* @param _staking address of Staking Contract
*/
constructor(Staking _staking) {
staking = _staking;
}
/**
* @notice Update sgn address
* @param _sgnAddr the new address in the layer 2 SGN
*/
function updateSgnAddr(bytes calldata _sgnAddr) external {
address valAddr = msg.sender;
if (staking.signerVals(msg.sender) != address(0)) {
valAddr = staking.signerVals(msg.sender);
}
dt.ValidatorStatus status = staking.getValidatorStatus(valAddr);
require(status == dt.ValidatorStatus.Unbonded, "Not unbonded validator");
bytes memory oldAddr = sgnAddrs[valAddr];
sgnAddrs[valAddr] = _sgnAddr;
staking.validatorNotice(valAddr, "sgn-addr", _sgnAddr);
emit SgnAddrUpdate(valAddr, oldAddr, _sgnAddr);
}
/**a
* @notice Deposit to SGN
* @param _amount subscription fee paid along this function call in CELR tokens
*/
function deposit(address _token, uint256 _amount) external whenNotPaused {
address msgSender = msg.sender;
deposits.push(keccak256(abi.encodePacked(msgSender, _token, _amount)));
IERC20(_token).safeTransferFrom(msgSender, address(this), _amount);
uint64 depositId = uint64(deposits.length - 1);
emit Deposit(depositId, msgSender, _token, _amount);
}
/**
* @notice Withdraw token
* @dev Here we use cumulative amount to make withdrawal process idempotent
* @param _withdrawalRequest withdrawal request bytes coded in protobuf
* @param _sigs list of validator signatures
*/
function withdraw(bytes calldata _withdrawalRequest, bytes[] calldata _sigs) external whenNotPaused {
bytes32 domain = keccak256(abi.encodePacked(block.chainid, address(this), "Withdrawal"));
staking.verifySignatures(abi.encodePacked(domain, _withdrawalRequest), _sigs);
PbSgn.Withdrawal memory withdrawal = PbSgn.decWithdrawal(_withdrawalRequest);
uint256 amount = withdrawal.cumulativeAmount - withdrawnAmts[withdrawal.account][withdrawal.token];
require(amount > 0, "No new amount to withdraw");
withdrawnAmts[withdrawal.account][withdrawal.token] = withdrawal.cumulativeAmount;
IERC20(withdrawal.token).safeTransfer(withdrawal.account, amount);
emit Withdraw(withdrawal.account, withdrawal.token, amount);
}
/**
* @notice Owner drains one type of tokens when the contract is paused
* @dev emergency use only
* @param _amount drained token amount
*/
function drainToken(address _token, uint256 _amount) external whenPaused onlyOwner {
IERC20(_token).safeTransfer(msg.sender, _amount);
}
}
// SPDX-License-Identifier: GPL-3.0-only
// Code generated by protoc-gen-sol. DO NOT EDIT.
// source: contracts/libraries/proto/sgn.proto
pragma solidity 0.8.9;
import "./Pb.sol";
library PbSgn {
using Pb for Pb.Buffer; // so we can call Pb funcs on Buffer obj
struct Withdrawal {
address account; // tag: 1
address token; // tag: 2
uint256 cumulativeAmount; // tag: 3
} // end struct Withdrawal
function decWithdrawal(bytes memory raw) internal pure returns (Withdrawal memory m) {
Pb.Buffer memory buf = Pb.fromBytes(raw);
uint256 tag;
Pb.WireType wire;
while (buf.hasMore()) {
(tag, wire) = buf.decKey();
if (false) {}
// solidity has no switch/case
else if (tag == 1) {
m.account = Pb._address(buf.decBytes());
} else if (tag == 2) {
m.token = Pb._address(buf.decBytes());
} else if (tag == 3) {
m.cumulativeAmount = Pb._uint256(buf.decBytes());
} else {
buf.skipValue(wire);
} // skip value of unknown tag
}
} // end decoder Withdrawal
}
// SPDX-License-Identifier: GPL-3.0-only
// Code generated by protoc-gen-sol. DO NOT EDIT.
// source: contracts/libraries/proto/farming.proto
pragma solidity 0.8.9;
import "./Pb.sol";
library PbFarming {
using Pb for Pb.Buffer; // so we can call Pb funcs on Buffer obj
struct FarmingRewards {
address recipient; // tag: 1
address[] tokenAddresses; // tag: 2
uint256[] cumulativeRewardAmounts; // tag: 3
} // end struct FarmingRewards
function decFarmingRewards(bytes memory raw) internal pure returns (FarmingRewards memory m) {
Pb.Buffer memory buf = Pb.fromBytes(raw);
uint256[] memory cnts = buf.cntTags(3);
m.tokenAddresses = new address[](cnts[2]);
cnts[2] = 0; // reset counter for later use
m.cumulativeRewardAmounts = new uint256[](cnts[3]);
cnts[3] = 0; // reset counter for later use
uint256 tag;
Pb.WireType wire;
while (buf.hasMore()) {
(tag, wire) = buf.decKey();
if (false) {}
// solidity has no switch/case
else if (tag == 1) {
m.recipient = Pb._address(buf.decBytes());
} else if (tag == 2) {
m.tokenAddresses[cnts[2]] = Pb._address(buf.decBytes());
cnts[2]++;
} else if (tag == 3) {
m.cumulativeRewardAmounts[cnts[3]] = Pb._uint256(buf.decBytes());
cnts[3]++;
} else {
buf.skipValue(wire);
} // skip value of unknown tag
}
} // end decoder FarmingRewards
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.8.9;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "../interfaces/ISigsVerifier.sol";
import "../libraries/PbFarming.sol";
import "../safeguard/Pauser.sol";
/**
* @title A contract to hold and distribute farming rewards.
*/
contract FarmingRewards is Pauser {
using SafeERC20 for IERC20;
ISigsVerifier public immutable sigsVerifier;
// recipient => tokenAddress => amount
mapping(address => mapping(address => uint256)) public claimedRewardAmounts;
event FarmingRewardClaimed(address indexed recipient, address indexed token, uint256 reward);
event FarmingRewardContributed(address indexed contributor, address indexed token, uint256 contribution);
constructor(ISigsVerifier _sigsVerifier) {
sigsVerifier = _sigsVerifier;
}
/**
* @notice Claim rewards
* @dev Here we use cumulative reward to make claim process idempotent
* @param _rewardsRequest rewards request bytes coded in protobuf
* @param _sigs list of signatures sorted by signer addresses in ascending order
* @param _signers sorted list of current signers
* @param _powers powers of current signers
*/
function claimRewards(
bytes calldata _rewardsRequest,
bytes[] calldata _sigs,
address[] calldata _signers,
uint256[] calldata _powers
) external whenNotPaused {
bytes32 domain = keccak256(abi.encodePacked(block.chainid, address(this), "FarmingRewards"));
sigsVerifier.verifySigs(abi.encodePacked(domain, _rewardsRequest), _sigs, _signers, _powers);
PbFarming.FarmingRewards memory rewards = PbFarming.decFarmingRewards(_rewardsRequest);
bool hasNewReward;
for (uint256 i = 0; i < rewards.tokenAddresses.length; i++) {
address token = rewards.tokenAddresses[i];
uint256 cumulativeRewardAmount = rewards.cumulativeRewardAmounts[i];
uint256 newReward = cumulativeRewardAmount - claimedRewardAmounts[rewards.recipient][token];
if (newReward > 0) {
hasNewReward = true;
claimedRewardAmounts[rewards.recipient][token] = cumulativeRewardAmount;
IERC20(token).safeTransfer(rewards.recipient, newReward);
emit FarmingRewardClaimed(rewards.recipient, token, newReward);
}
}
require(hasNewReward, "No new reward");
}
/**
* @notice Contribute reward tokens to the reward pool
* @param _token the address of the token to contribute
* @param _amount the amount of the token to contribute
*/
function contributeToRewardPool(address _token, uint256 _amount) external whenNotPaused {
address contributor = msg.sender;
IERC20(_token).safeTransferFrom(contributor, address(this), _amount);
emit FarmingRewardContributed(contributor, _token, _amount);
}
/**
* @notice Owner drains tokens when the contract is paused
* @dev emergency use only
* @param _token the address of the token to drain
* @param _amount drained token amount
*/
function drainToken(address _token, uint256 _amount) external whenPaused onlyOwner {
IERC20(_token).safeTransfer(msg.sender, _amount);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.8.9;
import "../interfaces/ISigsVerifier.sol";
import "../interfaces/IPeggedToken.sol";
import "../interfaces/IPeggedTokenBurnFrom.sol";
import "../libraries/PbPegged.sol";
import "../safeguard/Pauser.sol";
import "../safeguard/VolumeControl.sol";
import "../safeguard/DelayedTransfer.sol";
/**
* @title The bridge contract to mint and burn pegged tokens
* @dev Work together with OriginalTokenVault deployed at remote chains.
*/
contract PeggedTokenBridgeV2 is Pauser, VolumeControl, DelayedTransfer {
ISigsVerifier public immutable sigsVerifier;
mapping(bytes32 => bool) public records;
mapping(address => uint256) public minBurn;
mapping(address => uint256) public maxBurn;
event Mint(
bytes32 mintId,
address token,
address account,
uint256 amount,
// ref_chain_id defines the reference chain ID, taking values of:
// 1. The common case: the chain ID on which the remote corresponding deposit or burn happened;
// 2. Refund for wrong burn: this chain ID on which the burn happened
uint64 refChainId,
// ref_id defines a unique reference ID, taking values of:
// 1. The common case of deposit/burn-mint: the deposit or burn ID on the remote chain;
// 2. Refund for wrong burn: the burn ID on this chain
bytes32 refId,
address depositor
);
event Burn(
bytes32 burnId,
address token,
address account,
uint256 amount,
uint64 toChainId,
address toAccount,
uint64 nonce
);
event MinBurnUpdated(address token, uint256 amount);
event MaxBurnUpdated(address token, uint256 amount);
constructor(ISigsVerifier _sigsVerifier) {
sigsVerifier = _sigsVerifier;
}
/**
* @notice Mint tokens triggered by deposit at a remote chain's OriginalTokenVault.
* @param _request The serialized Mint protobuf.
* @param _sigs The list of signatures sorted by signing addresses in ascending order. A relay must be signed-off by
* +2/3 of the sigsVerifier's current signing power to be delivered.
* @param _signers The sorted list of signers.
* @param _powers The signing powers of the signers.
*/
function mint(
bytes calldata _request,
bytes[] calldata _sigs,
address[] calldata _signers,
uint256[] calldata _powers
) external whenNotPaused returns (bytes32) {
bytes32 domain = keccak256(abi.encodePacked(block.chainid, address(this), "Mint"));
sigsVerifier.verifySigs(abi.encodePacked(domain, _request), _sigs, _signers, _powers);
PbPegged.Mint memory request = PbPegged.decMint(_request);
bytes32 mintId = keccak256(
// len = 20 + 20 + 32 + 20 + 8 + 32 + 20 = 152
abi.encodePacked(
request.account,
request.token,
request.amount,
request.depositor,
request.refChainId,
request.refId,
address(this)
)
);
require(records[mintId] == false, "record exists");
records[mintId] = true;
_updateVolume(request.token, request.amount);
uint256 delayThreshold = delayThresholds[request.token];
if (delayThreshold > 0 && request.amount > delayThreshold) {
_addDelayedTransfer(mintId, request.account, request.token, request.amount);
} else {
IPeggedToken(request.token).mint(request.account, request.amount);
}
emit Mint(
mintId,
request.token,
request.account,
request.amount,
request.refChainId,
request.refId,
request.depositor
);
return mintId;
}
/**
* @notice Burn pegged tokens to trigger a cross-chain withdrawal of the original tokens at a remote chain's
* OriginalTokenVault, or mint at another remote chain
* NOTE: This function DOES NOT SUPPORT fee-on-transfer / rebasing tokens.
* @param _token The pegged token address.
* @param _amount The amount to burn.
* @param _toChainId If zero, withdraw from original vault; otherwise, the remote chain to mint tokens.
* @param _toAccount The account to receive tokens on the remote chain
* @param _nonce A number to guarantee unique depositId. Can be timestamp in practice.
*/
function burn(
address _token,
uint256 _amount,
uint64 _toChainId,
address _toAccount,
uint64 _nonce
) external whenNotPaused returns (bytes32) {
bytes32 burnId = _burn(_token, _amount, _toChainId, _toAccount, _nonce);
IPeggedToken(_token).burn(msg.sender, _amount);
return burnId;
}
// same with `burn` above, use openzeppelin ERC20Burnable interface
function burnFrom(
address _token,
uint256 _amount,
uint64 _toChainId,
address _toAccount,
uint64 _nonce
) external whenNotPaused returns (bytes32) {
bytes32 burnId = _burn(_token, _amount, _toChainId, _toAccount, _nonce);
IPeggedTokenBurnFrom(_token).burnFrom(msg.sender, _amount);
return burnId;
}
function _burn(
address _token,
uint256 _amount,
uint64 _toChainId,
address _toAccount,
uint64 _nonce
) private returns (bytes32) {
require(_amount > minBurn[_token], "amount too small");
require(maxBurn[_token] == 0 || _amount <= maxBurn[_token], "amount too large");
bytes32 burnId = keccak256(
// len = 20 + 20 + 32 + 8 + 20 + 8 + 8 + 20 = 136
abi.encodePacked(
msg.sender,
_token,
_amount,
_toChainId,
_toAccount,
_nonce,
uint64(block.chainid),
address(this)
)
);
require(records[burnId] == false, "record exists");
records[burnId] = true;
emit Burn(burnId, _token, msg.sender, _amount, _toChainId, _toAccount, _nonce);
return burnId;
}
function executeDelayedTransfer(bytes32 id) external whenNotPaused {
delayedTransfer memory transfer = _executeDelayedTransfer(id);
IPeggedToken(transfer.token).mint(transfer.receiver, transfer.amount);
}
function setMinBurn(address[] calldata _tokens, uint256[] calldata _amounts) external onlyGovernor {
require(_tokens.length == _amounts.length, "length mismatch");
for (uint256 i = 0; i < _tokens.length; i++) {
minBurn[_tokens[i]] = _amounts[i];
emit MinBurnUpdated(_tokens[i], _amounts[i]);
}
}
function setMaxBurn(address[] calldata _tokens, uint256[] calldata _amounts) external onlyGovernor {
require(_tokens.length == _amounts.length, "length mismatch");
for (uint256 i = 0; i < _tokens.length; i++) {
maxBurn[_tokens[i]] = _amounts[i];
emit MaxBurnUpdated(_tokens[i], _amounts[i]);
}
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity >=0.8.0;
interface IPeggedToken {
function mint(address _to, uint256 _amount) external;
function burn(address _from, uint256 _amount) external;
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity >=0.8.0;
// used for pegged token with openzeppelin ERC20Burnable interface
// only compatible with PeggedTokenBridgeV2
interface IPeggedTokenBurnFrom {
function mint(address _to, uint256 _amount) external;
function burnFrom(address _from, uint256 _amount) external;
}
// SPDX-License-Identifier: GPL-3.0-only
// Code generated by protoc-gen-sol. DO NOT EDIT.
// source: contracts/libraries/proto/pegged.proto
pragma solidity 0.8.9;
import "./Pb.sol";
library PbPegged {
using Pb for Pb.Buffer; // so we can call Pb funcs on Buffer obj
struct Mint {
address token; // tag: 1
address account; // tag: 2
uint256 amount; // tag: 3
address depositor; // tag: 4
uint64 refChainId; // tag: 5
bytes32 refId; // tag: 6
} // end struct Mint
function decMint(bytes memory raw) internal pure returns (Mint memory m) {
Pb.Buffer memory buf = Pb.fromBytes(raw);
uint256 tag;
Pb.WireType wire;
while (buf.hasMore()) {
(tag, wire) = buf.decKey();
if (false) {}
// solidity has no switch/case
else if (tag == 1) {
m.token = Pb._address(buf.decBytes());
} else if (tag == 2) {
m.account = Pb._address(buf.decBytes());
} else if (tag == 3) {
m.amount = Pb._uint256(buf.decBytes());
} else if (tag == 4) {
m.depositor = Pb._address(buf.decBytes());
} else if (tag == 5) {
m.refChainId = uint64(buf.decVarint());
} else if (tag == 6) {
m.refId = Pb._bytes32(buf.decBytes());
} else {
buf.skipValue(wire);
} // skip value of unknown tag
}
} // end decoder Mint
struct Withdraw {
address token; // tag: 1
address receiver; // tag: 2
uint256 amount; // tag: 3
address burnAccount; // tag: 4
uint64 refChainId; // tag: 5
bytes32 refId; // tag: 6
} // end struct Withdraw
function decWithdraw(bytes memory raw) internal pure returns (Withdraw memory m) {
Pb.Buffer memory buf = Pb.fromBytes(raw);
uint256 tag;
Pb.WireType wire;
while (buf.hasMore()) {
(tag, wire) = buf.decKey();
if (false) {}
// solidity has no switch/case
else if (tag == 1) {
m.token = Pb._address(buf.decBytes());
} else if (tag == 2) {
m.receiver = Pb._address(buf.decBytes());
} else if (tag == 3) {
m.amount = Pb._uint256(buf.decBytes());
} else if (tag == 4) {
m.burnAccount = Pb._address(buf.decBytes());
} else if (tag == 5) {
m.refChainId = uint64(buf.decVarint());
} else if (tag == 6) {
m.refId = Pb._bytes32(buf.decBytes());
} else {
buf.skipValue(wire);
} // skip value of unknown tag
}
} // end decoder Withdraw
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.8.9;
import "./Governor.sol";
abstract contract VolumeControl is Governor {
uint256 public epochLength; // seconds
mapping(address => uint256) public epochVolumes; // key is token
mapping(address => uint256) public epochVolumeCaps; // key is token
mapping(address => uint256) public lastOpTimestamps; // key is token
event EpochLengthUpdated(uint256 length);
event EpochVolumeUpdated(address token, uint256 cap);
function setEpochLength(uint256 _length) external onlyGovernor {
epochLength = _length;
emit EpochLengthUpdated(_length);
}
function setEpochVolumeCaps(address[] calldata _tokens, uint256[] calldata _caps) external onlyGovernor {
require(_tokens.length == _caps.length, "length mismatch");
for (uint256 i = 0; i < _tokens.length; i++) {
epochVolumeCaps[_tokens[i]] = _caps[i];
emit EpochVolumeUpdated(_tokens[i], _caps[i]);
}
}
function _updateVolume(address _token, uint256 _amount) internal {
if (epochLength == 0) {
return;
}
uint256 cap = epochVolumeCaps[_token];
if (cap == 0) {
return;
}
uint256 volume = epochVolumes[_token];
uint256 timestamp = block.timestamp;
uint256 epochStartTime = (timestamp / epochLength) * epochLength;
if (lastOpTimestamps[_token] < epochStartTime) {
volume = _amount;
} else {
volume += _amount;
}
require(volume <= cap, "volume exceeds cap");
epochVolumes[_token] = volume;
lastOpTimestamps[_token] = timestamp;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.8.9;
import "./Governor.sol";
abstract contract DelayedTransfer is Governor {
struct delayedTransfer {
address receiver;
address token;
uint256 amount;
uint256 timestamp;
}
mapping(bytes32 => delayedTransfer) public delayedTransfers;
mapping(address => uint256) public delayThresholds;
uint256 public delayPeriod; // in seconds
event DelayedTransferAdded(bytes32 id);
event DelayedTransferExecuted(bytes32 id, address receiver, address token, uint256 amount);
event DelayPeriodUpdated(uint256 period);
event DelayThresholdUpdated(address token, uint256 threshold);
function setDelayThresholds(address[] calldata _tokens, uint256[] calldata _thresholds) external onlyGovernor {
require(_tokens.length == _thresholds.length, "length mismatch");
for (uint256 i = 0; i < _tokens.length; i++) {
delayThresholds[_tokens[i]] = _thresholds[i];
emit DelayThresholdUpdated(_tokens[i], _thresholds[i]);
}
}
function setDelayPeriod(uint256 _period) external onlyGovernor {
delayPeriod = _period;
emit DelayPeriodUpdated(_period);
}
function _addDelayedTransfer(
bytes32 id,
address receiver,
address token,
uint256 amount
) internal {
require(delayedTransfers[id].timestamp == 0, "delayed transfer already exists");
delayedTransfers[id] = delayedTransfer({
receiver: receiver,
token: token,
amount: amount,
timestamp: block.timestamp
});
emit DelayedTransferAdded(id);
}
// caller needs to do the actual token transfer
function _executeDelayedTransfer(bytes32 id) internal returns (delayedTransfer memory) {
delayedTransfer memory transfer = delayedTransfers[id];
require(transfer.timestamp > 0, "delayed transfer not exist");
require(block.timestamp > transfer.timestamp + delayPeriod, "delayed transfer still locked");
delete delayedTransfers[id];
emit DelayedTransferExecuted(id, transfer.receiver, transfer.token, transfer.amount);
return transfer;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.8.9;
import "@openzeppelin/contracts/access/Ownable.sol";
abstract contract Governor is Ownable {
mapping(address => bool) public governors;
event GovernorAdded(address account);
event GovernorRemoved(address account);
modifier onlyGovernor() {
require(isGovernor(msg.sender), "Caller is not governor");
_;
}
constructor() {
_addGovernor(msg.sender);
}
function isGovernor(address _account) public view returns (bool) {
return governors[_account];
}
function addGovernor(address _account) public onlyOwner {
_addGovernor(_account);
}
function removeGovernor(address _account) public onlyOwner {
_removeGovernor(_account);
}
function renounceGovernor() public {
_removeGovernor(msg.sender);
}
function _addGovernor(address _account) private {
require(!isGovernor(_account), "Account is already governor");
governors[_account] = true;
emit GovernorAdded(_account);
}
function _removeGovernor(address _account) private {
require(isGovernor(_account), "Account is not governor");
governors[_account] = false;
emit GovernorRemoved(_account);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.8.9;
import "../interfaces/ISigsVerifier.sol";
import "../interfaces/IPeggedToken.sol";
import "../libraries/PbPegged.sol";
import "../safeguard/Pauser.sol";
import "../safeguard/VolumeControl.sol";
import "../safeguard/DelayedTransfer.sol";
/**
* @title The bridge contract to mint and burn pegged tokens
* @dev Work together with OriginalTokenVault deployed at remote chains.
*/
contract PeggedTokenBridge is Pauser, VolumeControl, DelayedTransfer {
ISigsVerifier public immutable sigsVerifier;
mapping(bytes32 => bool) public records;
mapping(address => uint256) public minBurn;
mapping(address => uint256) public maxBurn;
event Mint(
bytes32 mintId,
address token,
address account,
uint256 amount,
// ref_chain_id defines the reference chain ID, taking values of:
// 1. The common case: the chain ID on which the remote corresponding deposit or burn happened;
// 2. Refund for wrong burn: this chain ID on which the burn happened
uint64 refChainId,
// ref_id defines a unique reference ID, taking values of:
// 1. The common case of deposit/burn-mint: the deposit or burn ID on the remote chain;
// 2. Refund for wrong burn: the burn ID on this chain
bytes32 refId,
address depositor
);
event Burn(bytes32 burnId, address token, address account, uint256 amount, address withdrawAccount);
event MinBurnUpdated(address token, uint256 amount);
event MaxBurnUpdated(address token, uint256 amount);
constructor(ISigsVerifier _sigsVerifier) {
sigsVerifier = _sigsVerifier;
}
/**
* @notice Mint tokens triggered by deposit at a remote chain's OriginalTokenVault.
* @param _request The serialized Mint protobuf.
* @param _sigs The list of signatures sorted by signing addresses in ascending order. A relay must be signed-off by
* +2/3 of the sigsVerifier's current signing power to be delivered.
* @param _signers The sorted list of signers.
* @param _powers The signing powers of the signers.
*/
function mint(
bytes calldata _request,
bytes[] calldata _sigs,
address[] calldata _signers,
uint256[] calldata _powers
) external whenNotPaused {
bytes32 domain = keccak256(abi.encodePacked(block.chainid, address(this), "Mint"));
sigsVerifier.verifySigs(abi.encodePacked(domain, _request), _sigs, _signers, _powers);
PbPegged.Mint memory request = PbPegged.decMint(_request);
bytes32 mintId = keccak256(
// len = 20 + 20 + 32 + 20 + 8 + 32 = 132
abi.encodePacked(
request.account,
request.token,
request.amount,
request.depositor,
request.refChainId,
request.refId
)
);
require(records[mintId] == false, "record exists");
records[mintId] = true;
_updateVolume(request.token, request.amount);
uint256 delayThreshold = delayThresholds[request.token];
if (delayThreshold > 0 && request.amount > delayThreshold) {
_addDelayedTransfer(mintId, request.account, request.token, request.amount);
} else {
IPeggedToken(request.token).mint(request.account, request.amount);
}
emit Mint(
mintId,
request.token,
request.account,
request.amount,
request.refChainId,
request.refId,
request.depositor
);
}
/**
* @notice Burn pegged tokens to trigger a cross-chain withdrawal of the original tokens at a remote chain's
* OriginalTokenVault.
* NOTE: This function DOES NOT SUPPORT fee-on-transfer / rebasing tokens.
* @param _token The pegged token address.
* @param _amount The amount to burn.
* @param _withdrawAccount The account to receive the original tokens withdrawn on the remote chain.
* @param _nonce A number to guarantee unique depositId. Can be timestamp in practice.
*/
function burn(
address _token,
uint256 _amount,
address _withdrawAccount,
uint64 _nonce
) external whenNotPaused {
require(_amount > minBurn[_token], "amount too small");
require(maxBurn[_token] == 0 || _amount <= maxBurn[_token], "amount too large");
bytes32 burnId = keccak256(
// len = 20 + 20 + 32 + 20 + 8 + 8 = 108
abi.encodePacked(msg.sender, _token, _amount, _withdrawAccount, _nonce, uint64(block.chainid))
);
require(records[burnId] == false, "record exists");
records[burnId] = true;
IPeggedToken(_token).burn(msg.sender, _amount);
emit Burn(burnId, _token, msg.sender, _amount, _withdrawAccount);
}
function executeDelayedTransfer(bytes32 id) external whenNotPaused {
delayedTransfer memory transfer = _executeDelayedTransfer(id);
IPeggedToken(transfer.token).mint(transfer.receiver, transfer.amount);
}
function setMinBurn(address[] calldata _tokens, uint256[] calldata _amounts) external onlyGovernor {
require(_tokens.length == _amounts.length, "length mismatch");
for (uint256 i = 0; i < _tokens.length; i++) {
minBurn[_tokens[i]] = _amounts[i];
emit MinBurnUpdated(_tokens[i], _amounts[i]);
}
}
function setMaxBurn(address[] calldata _tokens, uint256[] calldata _amounts) external onlyGovernor {
require(_tokens.length == _amounts.length, "length mismatch");
for (uint256 i = 0; i < _tokens.length; i++) {
maxBurn[_tokens[i]] = _amounts[i];
emit MaxBurnUpdated(_tokens[i], _amounts[i]);
}
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.8.9;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "../interfaces/ISigsVerifier.sol";
import "../interfaces/IWETH.sol";
import "../libraries/PbPegged.sol";
import "../safeguard/Pauser.sol";
import "../safeguard/VolumeControl.sol";
import "../safeguard/DelayedTransfer.sol";
/**
* @title the vault to deposit and withdraw original tokens
* @dev Work together with PeggedTokenBridge contracts deployed at remote chains
*/
contract OriginalTokenVaultV2 is ReentrancyGuard, Pauser, VolumeControl, DelayedTransfer {
using SafeERC20 for IERC20;
ISigsVerifier public immutable sigsVerifier;
mapping(bytes32 => bool) public records;
mapping(address => uint256) public minDeposit;
mapping(address => uint256) public maxDeposit;
address public nativeWrap;
event Deposited(
bytes32 depositId,
address depositor,
address token,
uint256 amount,
uint64 mintChainId,
address mintAccount,
uint64 nonce
);
event Withdrawn(
bytes32 withdrawId,
address receiver,
address token,
uint256 amount,
// ref_chain_id defines the reference chain ID, taking values of:
// 1. The common case of burn-withdraw: the chain ID on which the corresponding burn happened;
// 2. Pegbridge fee claim: zero / not applicable;
// 3. Refund for wrong deposit: this chain ID on which the deposit happened
uint64 refChainId,
// ref_id defines a unique reference ID, taking values of:
// 1. The common case of burn-withdraw: the burn ID on the remote chain;
// 2. Pegbridge fee claim: a per-account nonce;
// 3. Refund for wrong deposit: the deposit ID on this chain
bytes32 refId,
address burnAccount
);
event MinDepositUpdated(address token, uint256 amount);
event MaxDepositUpdated(address token, uint256 amount);
constructor(ISigsVerifier _sigsVerifier) {
sigsVerifier = _sigsVerifier;
}
/**
* @notice Lock original tokens to trigger cross-chain mint of pegged tokens at a remote chain's PeggedTokenBridge.
* NOTE: This function DOES NOT SUPPORT fee-on-transfer / rebasing tokens.
* @param _token The original token address.
* @param _amount The amount to deposit.
* @param _mintChainId The destination chain ID to mint tokens.
* @param _mintAccount The destination account to receive the minted pegged tokens.
* @param _nonce A number input to guarantee unique depositId. Can be timestamp in practice.
*/
function deposit(
address _token,
uint256 _amount,
uint64 _mintChainId,
address _mintAccount,
uint64 _nonce
) external nonReentrant whenNotPaused returns (bytes32) {
bytes32 depId = _deposit(_token, _amount, _mintChainId, _mintAccount, _nonce);
IERC20(_token).safeTransferFrom(msg.sender, address(this), _amount);
emit Deposited(depId, msg.sender, _token, _amount, _mintChainId, _mintAccount, _nonce);
return depId;
}
/**
* @notice Lock native token as original token to trigger cross-chain mint of pegged tokens at a remote chain's
* PeggedTokenBridge.
* @param _amount The amount to deposit.
* @param _mintChainId The destination chain ID to mint tokens.
* @param _mintAccount The destination account to receive the minted pegged tokens.
* @param _nonce A number input to guarantee unique depositId. Can be timestamp in practice.
*/
function depositNative(
uint256 _amount,
uint64 _mintChainId,
address _mintAccount,
uint64 _nonce
) external payable nonReentrant whenNotPaused returns (bytes32) {
require(msg.value == _amount, "Amount mismatch");
require(nativeWrap != address(0), "Native wrap not set");
bytes32 depId = _deposit(nativeWrap, _amount, _mintChainId, _mintAccount, _nonce);
IWETH(nativeWrap).deposit{value: _amount}();
emit Deposited(depId, msg.sender, nativeWrap, _amount, _mintChainId, _mintAccount, _nonce);
return depId;
}
function _deposit(
address _token,
uint256 _amount,
uint64 _mintChainId,
address _mintAccount,
uint64 _nonce
) private returns (bytes32) {
require(_amount > minDeposit[_token], "amount too small");
require(maxDeposit[_token] == 0 || _amount <= maxDeposit[_token], "amount too large");
bytes32 depId = keccak256(
// len = 20 + 20 + 32 + 8 + 20 + 8 + 8 + 20 = 136
abi.encodePacked(
msg.sender,
_token,
_amount,
_mintChainId,
_mintAccount,
_nonce,
uint64(block.chainid),
address(this)
)
);
require(records[depId] == false, "record exists");
records[depId] = true;
return depId;
}
/**
* @notice Withdraw locked original tokens triggered by a burn at a remote chain's PeggedTokenBridge.
* @param _request The serialized Withdraw protobuf.
* @param _sigs The list of signatures sorted by signing addresses in ascending order. A relay must be signed-off by
* +2/3 of the bridge's current signing power to be delivered.
* @param _signers The sorted list of signers.
* @param _powers The signing powers of the signers.
*/
function withdraw(
bytes calldata _request,
bytes[] calldata _sigs,
address[] calldata _signers,
uint256[] calldata _powers
) external whenNotPaused returns (bytes32) {
bytes32 domain = keccak256(abi.encodePacked(block.chainid, address(this), "Withdraw"));
sigsVerifier.verifySigs(abi.encodePacked(domain, _request), _sigs, _signers, _powers);
PbPegged.Withdraw memory request = PbPegged.decWithdraw(_request);
bytes32 wdId = keccak256(
// len = 20 + 20 + 32 + 20 + 8 + 32 + 20 = 152
abi.encodePacked(
request.receiver,
request.token,
request.amount,
request.burnAccount,
request.refChainId,
request.refId,
address(this)
)
);
require(records[wdId] == false, "record exists");
records[wdId] = true;
_updateVolume(request.token, request.amount);
uint256 delayThreshold = delayThresholds[request.token];
if (delayThreshold > 0 && request.amount > delayThreshold) {
_addDelayedTransfer(wdId, request.receiver, request.token, request.amount);
} else {
_sendToken(request.receiver, request.token, request.amount);
}
emit Withdrawn(
wdId,
request.receiver,
request.token,
request.amount,
request.refChainId,
request.refId,
request.burnAccount
);
return wdId;
}
function executeDelayedTransfer(bytes32 id) external whenNotPaused {
delayedTransfer memory transfer = _executeDelayedTransfer(id);
_sendToken(transfer.receiver, transfer.token, transfer.amount);
}
function setMinDeposit(address[] calldata _tokens, uint256[] calldata _amounts) external onlyGovernor {
require(_tokens.length == _amounts.length, "length mismatch");
for (uint256 i = 0; i < _tokens.length; i++) {
minDeposit[_tokens[i]] = _amounts[i];
emit MinDepositUpdated(_tokens[i], _amounts[i]);
}
}
function setMaxDeposit(address[] calldata _tokens, uint256[] calldata _amounts) external onlyGovernor {
require(_tokens.length == _amounts.length, "length mismatch");
for (uint256 i = 0; i < _tokens.length; i++) {
maxDeposit[_tokens[i]] = _amounts[i];
emit MaxDepositUpdated(_tokens[i], _amounts[i]);
}
}
function setWrap(address _weth) external onlyOwner {
nativeWrap = _weth;
}
function _sendToken(
address _receiver,
address _token,
uint256 _amount
) private {
if (_token == nativeWrap) {
// withdraw then transfer native to receiver
IWETH(nativeWrap).withdraw(_amount);
(bool sent, ) = _receiver.call{value: _amount, gas: 50000}("");
require(sent, "failed to send native token");
} else {
IERC20(_token).safeTransfer(_receiver, _amount);
}
}
receive() external payable {}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity >=0.8.0;
interface IWETH {
function deposit() external payable;
function withdraw(uint256) external;
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.8.9;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "../interfaces/ISigsVerifier.sol";
import "../interfaces/IWETH.sol";
import "../libraries/PbPegged.sol";
import "../safeguard/Pauser.sol";
import "../safeguard/VolumeControl.sol";
import "../safeguard/DelayedTransfer.sol";
/**
* @title the vault to deposit and withdraw original tokens
* @dev Work together with PeggedTokenBridge contracts deployed at remote chains
*/
contract OriginalTokenVault is ReentrancyGuard, Pauser, VolumeControl, DelayedTransfer {
using SafeERC20 for IERC20;
ISigsVerifier public immutable sigsVerifier;
mapping(bytes32 => bool) public records;
mapping(address => uint256) public minDeposit;
mapping(address => uint256) public maxDeposit;
address public nativeWrap;
event Deposited(
bytes32 depositId,
address depositor,
address token,
uint256 amount,
uint64 mintChainId,
address mintAccount
);
event Withdrawn(
bytes32 withdrawId,
address receiver,
address token,
uint256 amount,
// ref_chain_id defines the reference chain ID, taking values of:
// 1. The common case of burn-withdraw: the chain ID on which the corresponding burn happened;
// 2. Pegbridge fee claim: zero / not applicable;
// 3. Refund for wrong deposit: this chain ID on which the deposit happened
uint64 refChainId,
// ref_id defines a unique reference ID, taking values of:
// 1. The common case of burn-withdraw: the burn ID on the remote chain;
// 2. Pegbridge fee claim: a per-account nonce;
// 3. Refund for wrong deposit: the deposit ID on this chain
bytes32 refId,
address burnAccount
);
event MinDepositUpdated(address token, uint256 amount);
event MaxDepositUpdated(address token, uint256 amount);
constructor(ISigsVerifier _sigsVerifier) {
sigsVerifier = _sigsVerifier;
}
/**
* @notice Lock original tokens to trigger cross-chain mint of pegged tokens at a remote chain's PeggedTokenBridge.
* NOTE: This function DOES NOT SUPPORT fee-on-transfer / rebasing tokens.
* @param _token The original token address.
* @param _amount The amount to deposit.
* @param _mintChainId The destination chain ID to mint tokens.
* @param _mintAccount The destination account to receive the minted pegged tokens.
* @param _nonce A number input to guarantee unique depositId. Can be timestamp in practice.
*/
function deposit(
address _token,
uint256 _amount,
uint64 _mintChainId,
address _mintAccount,
uint64 _nonce
) external nonReentrant whenNotPaused {
bytes32 depId = _deposit(_token, _amount, _mintChainId, _mintAccount, _nonce);
IERC20(_token).safeTransferFrom(msg.sender, address(this), _amount);
emit Deposited(depId, msg.sender, _token, _amount, _mintChainId, _mintAccount);
}
/**
* @notice Lock native token as original token to trigger cross-chain mint of pegged tokens at a remote chain's
* PeggedTokenBridge.
* @param _amount The amount to deposit.
* @param _mintChainId The destination chain ID to mint tokens.
* @param _mintAccount The destination account to receive the minted pegged tokens.
* @param _nonce A number input to guarantee unique depositId. Can be timestamp in practice.
*/
function depositNative(
uint256 _amount,
uint64 _mintChainId,
address _mintAccount,
uint64 _nonce
) external payable nonReentrant whenNotPaused {
require(msg.value == _amount, "Amount mismatch");
require(nativeWrap != address(0), "Native wrap not set");
bytes32 depId = _deposit(nativeWrap, _amount, _mintChainId, _mintAccount, _nonce);
IWETH(nativeWrap).deposit{value: _amount}();
emit Deposited(depId, msg.sender, nativeWrap, _amount, _mintChainId, _mintAccount);
}
function _deposit(
address _token,
uint256 _amount,
uint64 _mintChainId,
address _mintAccount,
uint64 _nonce
) private returns (bytes32) {
require(_amount > minDeposit[_token], "amount too small");
require(maxDeposit[_token] == 0 || _amount <= maxDeposit[_token], "amount too large");
bytes32 depId = keccak256(
// len = 20 + 20 + 32 + 8 + 20 + 8 + 8 = 116
abi.encodePacked(msg.sender, _token, _amount, _mintChainId, _mintAccount, _nonce, uint64(block.chainid))
);
require(records[depId] == false, "record exists");
records[depId] = true;
return depId;
}
/**
* @notice Withdraw locked original tokens triggered by a burn at a remote chain's PeggedTokenBridge.
* @param _request The serialized Withdraw protobuf.
* @param _sigs The list of signatures sorted by signing addresses in ascending order. A relay must be signed-off by
* +2/3 of the bridge's current signing power to be delivered.
* @param _signers The sorted list of signers.
* @param _powers The signing powers of the signers.
*/
function withdraw(
bytes calldata _request,
bytes[] calldata _sigs,
address[] calldata _signers,
uint256[] calldata _powers
) external whenNotPaused {
bytes32 domain = keccak256(abi.encodePacked(block.chainid, address(this), "Withdraw"));
sigsVerifier.verifySigs(abi.encodePacked(domain, _request), _sigs, _signers, _powers);
PbPegged.Withdraw memory request = PbPegged.decWithdraw(_request);
bytes32 wdId = keccak256(
// len = 20 + 20 + 32 + 20 + 8 + 32 = 132
abi.encodePacked(
request.receiver,
request.token,
request.amount,
request.burnAccount,
request.refChainId,
request.refId
)
);
require(records[wdId] == false, "record exists");
records[wdId] = true;
_updateVolume(request.token, request.amount);
uint256 delayThreshold = delayThresholds[request.token];
if (delayThreshold > 0 && request.amount > delayThreshold) {
_addDelayedTransfer(wdId, request.receiver, request.token, request.amount);
} else {
_sendToken(request.receiver, request.token, request.amount);
}
emit Withdrawn(
wdId,
request.receiver,
request.token,
request.amount,
request.refChainId,
request.refId,
request.burnAccount
);
}
function executeDelayedTransfer(bytes32 id) external whenNotPaused {
delayedTransfer memory transfer = _executeDelayedTransfer(id);
_sendToken(transfer.receiver, transfer.token, transfer.amount);
}
function setMinDeposit(address[] calldata _tokens, uint256[] calldata _amounts) external onlyGovernor {
require(_tokens.length == _amounts.length, "length mismatch");
for (uint256 i = 0; i < _tokens.length; i++) {
minDeposit[_tokens[i]] = _amounts[i];
emit MinDepositUpdated(_tokens[i], _amounts[i]);
}
}
function setMaxDeposit(address[] calldata _tokens, uint256[] calldata _amounts) external onlyGovernor {
require(_tokens.length == _amounts.length, "length mismatch");
for (uint256 i = 0; i < _tokens.length; i++) {
maxDeposit[_tokens[i]] = _amounts[i];
emit MaxDepositUpdated(_tokens[i], _amounts[i]);
}
}
function setWrap(address _weth) external onlyOwner {
nativeWrap = _weth;
}
function _sendToken(
address _receiver,
address _token,
uint256 _amount
) private {
if (_token == nativeWrap) {
// withdraw then transfer native to receiver
IWETH(nativeWrap).withdraw(_amount);
(bool sent, ) = _receiver.call{value: _amount, gas: 50000}("");
require(sent, "failed to send native token");
} else {
IERC20(_token).safeTransfer(_receiver, _amount);
}
}
receive() external payable {}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity >=0.8.9;
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../framework/MessageBusAddress.sol";
import "../framework/MessageSenderApp.sol";
import "../framework/MessageReceiverApp.sol";
import "../../interfaces/IWETH.sol";
import "../../interfaces/IUniswapV2.sol";
/**
* @title Demo application contract that facilitates swapping on a chain, transferring to another chain,
* and swapping another time on the destination chain before sending the result tokens to a user
*/
contract TransferSwap is MessageSenderApp, MessageReceiverApp {
using SafeERC20 for IERC20;
modifier onlyEOA() {
require(msg.sender == tx.origin, "Not EOA");
_;
}
struct SwapInfo {
// if this array has only one element, it means no need to swap
address[] path;
// the following fields are only needed if path.length > 1
address dex; // the DEX to use for the swap
uint256 deadline; // deadline for the swap
uint256 minRecvAmt; // minimum receive amount for the swap
}
struct SwapRequest {
SwapInfo swap;
// the receiving party (the user) of the final output token
address receiver;
// this field is best to be per-user per-transaction unique so that
// a nonce that is specified by the calling party (the user),
uint64 nonce;
// indicates whether the output token coming out of the swap on destination
// chain should be unwrapped before sending to the user
bool nativeOut;
}
enum SwapStatus {
Null,
Succeeded,
Failed,
Fallback
}
// emitted when requested dstChainId == srcChainId, no bridging
event DirectSwap(
bytes32 id,
uint64 srcChainId,
uint256 amountIn,
address tokenIn,
uint256 amountOut,
address tokenOut
);
event SwapRequestSent(bytes32 id, uint64 dstChainId, uint256 srcAmount, address srcToken, address dstToken);
event SwapRequestDone(bytes32 id, uint256 dstAmount, SwapStatus status);
mapping(address => uint256) public minSwapAmounts;
mapping(address => bool) supportedDex;
// erc20 wrap of gas token of this chain, eg. WETH
address public nativeWrap;
constructor(
address _messageBus,
address _supportedDex,
address _nativeWrap
) {
messageBus = _messageBus;
supportedDex[_supportedDex] = true;
nativeWrap = _nativeWrap;
}
function transferWithSwapNative(
address _receiver,
uint256 _amountIn,
uint64 _dstChainId,
SwapInfo calldata _srcSwap,
SwapInfo calldata _dstSwap,
uint32 _maxBridgeSlippage,
uint64 _nonce,
bool _nativeOut
) external payable onlyEOA {
require(msg.value >= _amountIn, "Amount insufficient");
require(_srcSwap.path[0] == nativeWrap, "token mismatch");
IWETH(nativeWrap).deposit{value: _amountIn}();
_transferWithSwap(
_receiver,
_amountIn,
_dstChainId,
_srcSwap,
_dstSwap,
_maxBridgeSlippage,
_nonce,
_nativeOut,
msg.value - _amountIn
);
}
function transferWithSwap(
address _receiver,
uint256 _amountIn,
uint64 _dstChainId,
SwapInfo calldata _srcSwap,
SwapInfo calldata _dstSwap,
uint32 _maxBridgeSlippage,
uint64 _nonce
) external payable onlyEOA {
IERC20(_srcSwap.path[0]).safeTransferFrom(msg.sender, address(this), _amountIn);
_transferWithSwap(
_receiver,
_amountIn,
_dstChainId,
_srcSwap,
_dstSwap,
_maxBridgeSlippage,
_nonce,
false,
msg.value
);
}
/**
* @notice Sends a cross-chain transfer via the liquidity pool-based bridge and sends a message specifying a wanted swap action on the
destination chain via the message bus
* @param _receiver the app contract that implements the MessageReceiver abstract contract
* NOTE not to be confused with the receiver field in SwapInfo which is an EOA address of a user
* @param _amountIn the input amount that the user wants to swap and/or bridge
* @param _dstChainId destination chain ID
* @param _srcSwap a struct containing swap related requirements
* @param _dstSwap a struct containing swap related requirements
* @param _maxBridgeSlippage the max acceptable slippage at bridge, given as percentage in point (pip). Eg. 5000 means 0.5%.
* Must be greater than minimalMaxSlippage. Receiver is guaranteed to receive at least (100% - max slippage percentage) * amount or the
* transfer can be refunded.
* @param _fee the fee to pay to MessageBus.
*/
function _transferWithSwap(
address _receiver,
uint256 _amountIn,
uint64 _dstChainId,
SwapInfo memory _srcSwap,
SwapInfo memory _dstSwap,
uint32 _maxBridgeSlippage,
uint64 _nonce,
bool _nativeOut,
uint256 _fee
) private {
require(_srcSwap.path.length > 0, "empty src swap path");
address srcTokenOut = _srcSwap.path[_srcSwap.path.length - 1];
require(_amountIn > minSwapAmounts[_srcSwap.path[0]], "amount must be greater than min swap amount");
uint64 chainId = uint64(block.chainid);
require(_srcSwap.path.length > 1 || _dstChainId != chainId, "noop is not allowed"); // revert early to save gas
uint256 srcAmtOut = _amountIn;
// swap source token for intermediate token on the source DEX
if (_srcSwap.path.length > 1) {
bool ok = true;
(ok, srcAmtOut) = _trySwap(_srcSwap, _amountIn);
if (!ok) revert("src swap failed");
}
if (_dstChainId == chainId) {
_directSend(_receiver, _amountIn, chainId, _srcSwap, _nonce, srcTokenOut, srcAmtOut);
} else {
_crossChainTransferWithSwap(
_receiver,
_amountIn,
chainId,
_dstChainId,
_srcSwap,
_dstSwap,
_maxBridgeSlippage,
_nonce,
_nativeOut,
_fee,
srcTokenOut,
srcAmtOut
);
}
}
function _directSend(
address _receiver,
uint256 _amountIn,
uint64 _chainId,
SwapInfo memory _srcSwap,
uint64 _nonce,
address srcTokenOut,
uint256 srcAmtOut
) private {
// no need to bridge, directly send the tokens to user
IERC20(srcTokenOut).safeTransfer(_receiver, srcAmtOut);
// use uint64 for chainid to be consistent with other components in the system
bytes32 id = keccak256(abi.encode(msg.sender, _chainId, _receiver, _nonce, _srcSwap));
emit DirectSwap(id, _chainId, _amountIn, _srcSwap.path[0], srcAmtOut, srcTokenOut);
}
function _crossChainTransferWithSwap(
address _receiver,
uint256 _amountIn,
uint64 _chainId,
uint64 _dstChainId,
SwapInfo memory _srcSwap,
SwapInfo memory _dstSwap,
uint32 _maxBridgeSlippage,
uint64 _nonce,
bool _nativeOut,
uint256 _fee,
address srcTokenOut,
uint256 srcAmtOut
) private {
require(_dstSwap.path.length > 0, "empty dst swap path");
bytes memory message = abi.encode(
SwapRequest({swap: _dstSwap, receiver: msg.sender, nonce: _nonce, nativeOut: _nativeOut})
);
bytes32 id = _computeSwapRequestId(msg.sender, _chainId, _dstChainId, message);
// bridge the intermediate token to destination chain along with the message
// NOTE In production, it's better use a per-user per-transaction nonce so that it's less likely transferId collision
// would happen at Bridge contract. Currently this nonce is a timestamp supplied by frontend
sendMessageWithTransfer(
_receiver,
srcTokenOut,
srcAmtOut,
_dstChainId,
_nonce,
_maxBridgeSlippage,
message,
MsgDataTypes.BridgeSendType.Liquidity,
_fee
);
emit SwapRequestSent(id, _dstChainId, _amountIn, _srcSwap.path[0], _dstSwap.path[_dstSwap.path.length - 1]);
}
/**
* @notice called by MessageBus when the tokens are checked to be arrived at this contract's address.
sends the amount received to the receiver. swaps beforehand if swap behavior is defined in message
* NOTE: if the swap fails, it sends the tokens received directly to the receiver as fallback behavior
* @param _token the address of the token sent through the bridge
* @param _amount the amount of tokens received at this contract through the cross-chain bridge
* @param _srcChainId source chain ID
* @param _message SwapRequest message that defines the swap behavior on this destination chain
*/
function executeMessageWithTransfer(
address, // _sender
address _token,
uint256 _amount,
uint64 _srcChainId,
bytes memory _message,
address // executor
) external payable override onlyMessageBus returns (ExecutionStatus) {
SwapRequest memory m = abi.decode((_message), (SwapRequest));
require(_token == m.swap.path[0], "bridged token must be the same as the first token in destination swap path");
bytes32 id = _computeSwapRequestId(m.receiver, _srcChainId, uint64(block.chainid), _message);
uint256 dstAmount;
SwapStatus status = SwapStatus.Succeeded;
if (m.swap.path.length > 1) {
bool ok = true;
(ok, dstAmount) = _trySwap(m.swap, _amount);
if (ok) {
_sendToken(m.swap.path[m.swap.path.length - 1], dstAmount, m.receiver, m.nativeOut);
status = SwapStatus.Succeeded;
} else {
// handle swap failure, send the received token directly to receiver
_sendToken(_token, _amount, m.receiver, false);
dstAmount = _amount;
status = SwapStatus.Fallback;
}
} else {
// no need to swap, directly send the bridged token to user
_sendToken(m.swap.path[0], _amount, m.receiver, m.nativeOut);
dstAmount = _amount;
status = SwapStatus.Succeeded;
}
emit SwapRequestDone(id, dstAmount, status);
// always return success since swap failure is already handled in-place
return ExecutionStatus.Success;
}
/**
* @notice called by MessageBus when the executeMessageWithTransfer call fails. does nothing but emitting a "fail" event
* @param _srcChainId source chain ID
* @param _message SwapRequest message that defines the swap behavior on this destination chain
*/
function executeMessageWithTransferFallback(
address, // _sender
address, // _token
uint256, // _amount
uint64 _srcChainId,
bytes memory _message,
address // executor
) external payable override onlyMessageBus returns (ExecutionStatus) {
SwapRequest memory m = abi.decode((_message), (SwapRequest));
bytes32 id = _computeSwapRequestId(m.receiver, _srcChainId, uint64(block.chainid), _message);
emit SwapRequestDone(id, 0, SwapStatus.Failed);
// always return fail to mark this transfer as failed since if this function is called then there nothing more
// we can do in this app as the swap failures are already handled in executeMessageWithTransfer
return ExecutionStatus.Fail;
}
function _trySwap(SwapInfo memory _swap, uint256 _amount) private returns (bool ok, uint256 amountOut) {
uint256 zero;
if (!supportedDex[_swap.dex]) {
return (false, zero);
}
IERC20(_swap.path[0]).safeIncreaseAllowance(_swap.dex, _amount);
try
IUniswapV2(_swap.dex).swapExactTokensForTokens(
_amount,
_swap.minRecvAmt,
_swap.path,
address(this),
_swap.deadline
)
returns (uint256[] memory amounts) {
return (true, amounts[amounts.length - 1]);
} catch {
return (false, zero);
}
}
function _sendToken(
address _token,
uint256 _amount,
address _receiver,
bool _nativeOut
) private {
if (_nativeOut) {
require(_token == nativeWrap, "token mismatch");
IWETH(nativeWrap).withdraw(_amount);
(bool sent, ) = _receiver.call{value: _amount, gas: 50000}("");
require(sent, "failed to send native");
} else {
IERC20(_token).safeTransfer(_receiver, _amount);
}
}
function _computeSwapRequestId(
address _sender,
uint64 _srcChainId,
uint64 _dstChainId,
bytes memory _message
) private pure returns (bytes32) {
return keccak256(abi.encodePacked(_sender, _srcChainId, _dstChainId, _message));
}
function setMinSwapAmount(address _token, uint256 _minSwapAmount) external onlyOwner {
minSwapAmounts[_token] = _minSwapAmount;
}
function setSupportedDex(address _dex, bool _enabled) external onlyOwner {
supportedDex[_dex] = _enabled;
}
function setNativeWrap(address _nativeWrap) external onlyOwner {
nativeWrap = _nativeWrap;
}
// This is needed to receive ETH when calling `IWETH.withdraw`
receive() external payable {}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity >=0.8.0;
import "../../safeguard/Ownable.sol";
abstract contract MessageBusAddress is Ownable {
event MessageBusUpdated(address messageBus);
address public messageBus;
function setMessageBus(address _messageBus) public onlyOwner {
messageBus = _messageBus;
emit MessageBusUpdated(messageBus);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.8.9;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "../libraries/MsgDataTypes.sol";
import "../libraries/MessageSenderLib.sol";
import "../messagebus/MessageBus.sol";
import "./MessageBusAddress.sol";
abstract contract MessageSenderApp is MessageBusAddress {
using SafeERC20 for IERC20;
// ============== Utility functions called by apps ==============
/**
* @notice Sends a message to a contract on another chain.
* Sender needs to make sure the uniqueness of the message Id, which is computed as
* hash(type.MessageOnly, sender, receiver, srcChainId, srcTxHash, dstChainId, message).
* If messages with the same Id are sent, only one of them will succeed at dst chain.
* @param _receiver The address of the destination app contract.
* @param _dstChainId The destination chain ID.
* @param _message Arbitrary message bytes to be decoded by the destination app contract.
* @param _fee The fee amount to pay to MessageBus.
*/
function sendMessage(
address _receiver,
uint64 _dstChainId,
bytes memory _message,
uint256 _fee
) internal {
MessageSenderLib.sendMessage(_receiver, _dstChainId, _message, messageBus, _fee);
}
/**
* @notice Sends a message associated with a transfer to a contract on another chain.
* @param _receiver The address of the destination app contract.
* @param _token The address of the token to be sent.
* @param _amount The amount of tokens to be sent.
* @param _dstChainId The destination chain ID.
* @param _nonce A number input to guarantee uniqueness of transferId. Can be timestamp in practice.
* @param _maxSlippage The max slippage accepted, given as percentage in point (pip). Eg. 5000 means 0.5%.
* Must be greater than minimalMaxSlippage. Receiver is guaranteed to receive at least
* (100% - max slippage percentage) * amount or the transfer can be refunded.
* Only applicable to the {MsgDataTypes.BridgeSendType.Liquidity}.
* @param _message Arbitrary message bytes to be decoded by the destination app contract.
* If message is empty, only the token transfer will be sent
* @param _bridgeSendType One of the {BridgeSendType} enum.
* @param _fee The fee amount to pay to MessageBus.
* @return The transfer ID.
*/
function sendMessageWithTransfer(
address _receiver,
address _token,
uint256 _amount,
uint64 _dstChainId,
uint64 _nonce,
uint32 _maxSlippage,
bytes memory _message,
MsgDataTypes.BridgeSendType _bridgeSendType,
uint256 _fee
) internal returns (bytes32) {
return
MessageSenderLib.sendMessageWithTransfer(
_receiver,
_token,
_amount,
_dstChainId,
_nonce,
_maxSlippage,
_message,
_bridgeSendType,
messageBus,
_fee
);
}
/**
* @notice Sends a token transfer via a bridge.
* @dev sendMessageWithTransfer with empty message
* @param _receiver The address of the destination app contract.
* @param _token The address of the token to be sent.
* @param _amount The amount of tokens to be sent.
* @param _dstChainId The destination chain ID.
* @param _nonce A number input to guarantee uniqueness of transferId. Can be timestamp in practice.
* @param _maxSlippage The max slippage accepted, given as percentage in point (pip). Eg. 5000 means 0.5%.
* Must be greater than minimalMaxSlippage. Receiver is guaranteed to receive at least
* (100% - max slippage percentage) * amount or the transfer can be refunded.
* Only applicable to the {MsgDataTypes.BridgeSendType.Liquidity}.
* @param _bridgeSendType One of the {BridgeSendType} enum.
*/
function sendTokenTransfer(
address _receiver,
address _token,
uint256 _amount,
uint64 _dstChainId,
uint64 _nonce,
uint32 _maxSlippage,
MsgDataTypes.BridgeSendType _bridgeSendType
) internal returns (bytes32) {
return
MessageSenderLib.sendMessageWithTransfer(
_receiver,
_token,
_amount,
_dstChainId,
_nonce,
_maxSlippage,
"", // empty message, which will not trigger sendMessage
_bridgeSendType,
messageBus,
0
);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.8.9;
import "../interfaces/IMessageReceiverApp.sol";
import "./MessageBusAddress.sol";
abstract contract MessageReceiverApp is IMessageReceiverApp, MessageBusAddress {
modifier onlyMessageBus() {
require(msg.sender == messageBus, "caller is not message bus");
_;
}
/**
* @notice Called by MessageBus (MessageBusReceiver) if the process is originated from MessageBus (MessageBusSender)'s
* sendMessageWithTransfer it is only called when the tokens are checked to be arrived at this contract's address.
* @param _sender The address of the source app contract
* @param _token The address of the token that comes out of the bridge
* @param _amount The amount of tokens received at this contract through the cross-chain bridge.
* the contract that implements this contract can safely assume that the tokens will arrive before this
* function is called.
* @param _srcChainId The source chain ID where the transfer is originated from
* @param _message Arbitrary message bytes originated from and encoded by the source app contract
* @param _executor Address who called the MessageBus execution function
*/
function executeMessageWithTransfer(
address _sender,
address _token,
uint256 _amount,
uint64 _srcChainId,
bytes calldata _message,
address _executor
) external payable virtual override onlyMessageBus returns (ExecutionStatus) {}
/**
* @notice Only called by MessageBus (MessageBusReceiver) if
* 1. executeMessageWithTransfer reverts, or
* 2. executeMessageWithTransfer returns ExecutionStatus.Fail
* @param _sender The address of the source app contract
* @param _token The address of the token that comes out of the bridge
* @param _amount The amount of tokens received at this contract through the cross-chain bridge.
* the contract that implements this contract can safely assume that the tokens will arrive before this
* function is called.
* @param _srcChainId The source chain ID where the transfer is originated from
* @param _message Arbitrary message bytes originated from and encoded by the source app contract
* @param _executor Address who called the MessageBus execution function
*/
function executeMessageWithTransferFallback(
address _sender,
address _token,
uint256 _amount,
uint64 _srcChainId,
bytes calldata _message,
address _executor
) external payable virtual override onlyMessageBus returns (ExecutionStatus) {}
/**
* @notice Called by MessageBus (MessageBusReceiver) to process refund of the original transfer from this contract
* @param _token The token address of the original transfer
* @param _amount The amount of the original transfer
* @param _message The same message associated with the original transfer
* @param _executor Address who called the MessageBus execution function
*/
function executeMessageWithTransferRefund(
address _token,
uint256 _amount,
bytes calldata _message,
address _executor
) external payable virtual override onlyMessageBus returns (ExecutionStatus) {}
/**
* @notice Called by MessageBus (MessageBusReceiver)
* @param _sender The address of the source app contract
* @param _srcChainId The source chain ID where the transfer is originated from
* @param _message Arbitrary message bytes originated from and encoded by the source app contract
* @param _executor Address who called the MessageBus execution function
*/
function executeMessage(
address _sender,
uint64 _srcChainId,
bytes calldata _message,
address _executor
) external payable virtual override onlyMessageBus returns (ExecutionStatus) {}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity >=0.8.0;
interface IUniswapV2 {
function swapTokensForExactTokens(
uint256 amountOut,
uint256 amountInMax,
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: GPL-3.0-only
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.
*
* This adds a normal func that setOwner if _owner is address(0). So we can't allow
* renounceOwnership. So we can support Proxy based upgradable contract
*/
abstract contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(msg.sender);
}
/**
* @dev Only to be called by inherit contracts, in their init func called by Proxy
* we require _owner == address(0), which is only possible when it's a delegateCall
* because constructor sets _owner in contract state.
*/
function initOwner() internal {
require(_owner == address(0), "owner already set");
_setOwner(msg.sender);
}
/**
* @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() == msg.sender, "Ownable: caller is not the owner");
_;
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity >=0.8.0;
library MsgDataTypes {
// bridge operation type at the sender side (src chain)
enum BridgeSendType {
Null,
Liquidity,
PegDeposit,
PegBurn,
PegV2Deposit,
PegV2Burn,
PegV2BurnFrom
}
// bridge operation type at the receiver side (dst chain)
enum TransferType {
Null,
LqRelay, // relay through liquidity bridge
LqWithdraw, // withdraw from liquidity bridge
PegMint, // mint through pegged token bridge
PegWithdraw, // withdraw from original token vault
PegV2Mint, // mint through pegged token bridge v2
PegV2Withdraw // withdraw from original token vault v2
}
enum MsgType {
MessageWithTransfer,
MessageOnly
}
enum TxStatus {
Null,
Success,
Fail,
Fallback,
Pending // transient state within a transaction
}
struct TransferInfo {
TransferType t;
address sender;
address receiver;
address token;
uint256 amount;
uint64 wdseq; // only needed for LqWithdraw (refund)
uint64 srcChainId;
bytes32 refId;
bytes32 srcTxHash; // src chain msg tx hash
}
struct RouteInfo {
address sender;
address receiver;
uint64 srcChainId;
bytes32 srcTxHash; // src chain msg tx hash
}
struct MsgWithTransferExecutionParams {
bytes message;
TransferInfo transfer;
bytes[] sigs;
address[] signers;
uint256[] powers;
}
struct BridgeTransferParams {
bytes request;
bytes[] sigs;
address[] signers;
uint256[] powers;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity >=0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "../../interfaces/IBridge.sol";
import "../../interfaces/IOriginalTokenVault.sol";
import "../../interfaces/IOriginalTokenVaultV2.sol";
import "../../interfaces/IPeggedTokenBridge.sol";
import "../../interfaces/IPeggedTokenBridgeV2.sol";
import "../interfaces/IMessageBus.sol";
import "./MsgDataTypes.sol";
library MessageSenderLib {
using SafeERC20 for IERC20;
// ============== Internal library functions called by apps ==============
/**
* @notice Sends a message to a contract on another chain.
* Sender needs to make sure the uniqueness of the message Id, which is computed as
* hash(type.MessageOnly, sender, receiver, srcChainId, srcTxHash, dstChainId, message).
* If messages with the same Id are sent, only one of them will succeed at dst chain.
* @param _receiver The address of the destination app contract.
* @param _dstChainId The destination chain ID.
* @param _message Arbitrary message bytes to be decoded by the destination app contract.
* @param _messageBus The address of the MessageBus on this chain.
* @param _fee The fee amount to pay to MessageBus.
*/
function sendMessage(
address _receiver,
uint64 _dstChainId,
bytes memory _message,
address _messageBus,
uint256 _fee
) internal {
IMessageBus(_messageBus).sendMessage{value: _fee}(_receiver, _dstChainId, _message);
}
/**
* @notice Sends a message associated with a transfer to a contract on another chain.
* @param _receiver The address of the destination app contract.
* @param _token The address of the token to be sent.
* @param _amount The amount of tokens to be sent.
* @param _dstChainId The destination chain ID.
* @param _nonce A number input to guarantee uniqueness of transferId. Can be timestamp in practice.
* @param _maxSlippage The max slippage accepted, given as percentage in point (pip). Eg. 5000 means 0.5%.
* Must be greater than minimalMaxSlippage. Receiver is guaranteed to receive at least
* (100% - max slippage percentage) * amount or the transfer can be refunded.
* Only applicable to the {MsgDataTypes.BridgeSendType.Liquidity}.
* @param _message Arbitrary message bytes to be decoded by the destination app contract.
* If message is empty, only the token transfer will be sent
* @param _bridgeSendType One of the {MsgDataTypes.BridgeSendType} enum.
* @param _messageBus The address of the MessageBus on this chain.
* @param _fee The fee amount to pay to MessageBus.
* @return The transfer ID.
*/
function sendMessageWithTransfer(
address _receiver,
address _token,
uint256 _amount,
uint64 _dstChainId,
uint64 _nonce,
uint32 _maxSlippage,
bytes memory _message,
MsgDataTypes.BridgeSendType _bridgeSendType,
address _messageBus,
uint256 _fee
) internal returns (bytes32) {
if (_bridgeSendType == MsgDataTypes.BridgeSendType.Liquidity) {
return
sendMessageWithLiquidityBridgeTransfer(
_receiver,
_token,
_amount,
_dstChainId,
_nonce,
_maxSlippage,
_message,
_messageBus,
_fee
);
} else if (
_bridgeSendType == MsgDataTypes.BridgeSendType.PegDeposit ||
_bridgeSendType == MsgDataTypes.BridgeSendType.PegV2Deposit
) {
return
sendMessageWithPegVaultDeposit(
_bridgeSendType,
_receiver,
_token,
_amount,
_dstChainId,
_nonce,
_message,
_messageBus,
_fee
);
} else if (
_bridgeSendType == MsgDataTypes.BridgeSendType.PegBurn ||
_bridgeSendType == MsgDataTypes.BridgeSendType.PegV2Burn ||
_bridgeSendType == MsgDataTypes.BridgeSendType.PegV2BurnFrom
) {
return
sendMessageWithPegBridgeBurn(
_bridgeSendType,
_receiver,
_token,
_amount,
_dstChainId,
_nonce,
_message,
_messageBus,
_fee
);
} else {
revert("bridge type not supported");
}
}
/**
* @notice Sends a message to an app on another chain via MessageBus with an associated liquidity bridge transfer.
* @param _receiver The address of the destination app contract.
* @param _token The address of the token to be sent.
* @param _amount The amount of tokens to be sent.
* @param _dstChainId The destination chain ID.
* @param _nonce A number input to guarantee uniqueness of transferId. Can be timestamp in practice.
* @param _maxSlippage The max slippage accepted, given as percentage in point (pip). Eg. 5000 means 0.5%.
* Must be greater than minimalMaxSlippage. Receiver is guaranteed to receive at least
* (100% - max slippage percentage) * amount or the transfer can be refunded.
* @param _message Arbitrary message bytes to be decoded by the destination app contract.
* If message is empty, only the token transfer will be sent
* @param _messageBus The address of the MessageBus on this chain.
* @param _fee The fee amount to pay to MessageBus.
* @return The transfer ID.
*/
function sendMessageWithLiquidityBridgeTransfer(
address _receiver,
address _token,
uint256 _amount,
uint64 _dstChainId,
uint64 _nonce,
uint32 _maxSlippage,
bytes memory _message,
address _messageBus,
uint256 _fee
) internal returns (bytes32) {
address bridge = IMessageBus(_messageBus).liquidityBridge();
IERC20(_token).safeIncreaseAllowance(bridge, _amount);
IBridge(bridge).send(_receiver, _token, _amount, _dstChainId, _nonce, _maxSlippage);
bytes32 transferId = keccak256(
abi.encodePacked(address(this), _receiver, _token, _amount, _dstChainId, _nonce, uint64(block.chainid))
);
if (_message.length > 0) {
IMessageBus(_messageBus).sendMessageWithTransfer{value: _fee}(
_receiver,
_dstChainId,
bridge,
transferId,
_message
);
}
return transferId;
}
/**
* @notice Sends a message to an app on another chain via MessageBus with an associated OriginalTokenVault deposit.
* @param _receiver The address of the destination app contract.
* @param _token The address of the token to be sent.
* @param _amount The amount of tokens to be sent.
* @param _dstChainId The destination chain ID.
* @param _nonce A number input to guarantee uniqueness of transferId. Can be timestamp in practice.
* @param _message Arbitrary message bytes to be decoded by the destination app contract.
* If message is empty, only the token transfer will be sent
* @param _messageBus The address of the MessageBus on this chain.
* @param _fee The fee amount to pay to MessageBus.
* @return The transfer ID.
*/
function sendMessageWithPegVaultDeposit(
MsgDataTypes.BridgeSendType _bridgeSendType,
address _receiver,
address _token,
uint256 _amount,
uint64 _dstChainId,
uint64 _nonce,
bytes memory _message,
address _messageBus,
uint256 _fee
) internal returns (bytes32) {
address pegVault;
if (_bridgeSendType == MsgDataTypes.BridgeSendType.PegDeposit) {
pegVault = IMessageBus(_messageBus).pegVault();
} else {
pegVault = IMessageBus(_messageBus).pegVaultV2();
}
IERC20(_token).safeIncreaseAllowance(pegVault, _amount);
bytes32 transferId;
if (_bridgeSendType == MsgDataTypes.BridgeSendType.PegDeposit) {
IOriginalTokenVault(pegVault).deposit(_token, _amount, _dstChainId, _receiver, _nonce);
transferId = keccak256(
abi.encodePacked(address(this), _token, _amount, _dstChainId, _receiver, _nonce, uint64(block.chainid))
);
} else {
transferId = IOriginalTokenVaultV2(pegVault).deposit(_token, _amount, _dstChainId, _receiver, _nonce);
}
if (_message.length > 0) {
IMessageBus(_messageBus).sendMessageWithTransfer{value: _fee}(
_receiver,
_dstChainId,
pegVault,
transferId,
_message
);
}
return transferId;
}
/**
* @notice Sends a message to an app on another chain via MessageBus with an associated PeggedTokenBridge burn.
* @param _receiver The address of the destination app contract.
* @param _token The address of the token to be sent.
* @param _amount The amount of tokens to be sent.
* @param _dstChainId The destination chain ID.
* @param _nonce A number input to guarantee uniqueness of transferId. Can be timestamp in practice.
* @param _message Arbitrary message bytes to be decoded by the destination app contract.
* If message is empty, only the token transfer will be sent
* @param _messageBus The address of the MessageBus on this chain.
* @param _fee The fee amount to pay to MessageBus.
* @return The transfer ID.
*/
function sendMessageWithPegBridgeBurn(
MsgDataTypes.BridgeSendType _bridgeSendType,
address _receiver,
address _token,
uint256 _amount,
uint64 _dstChainId,
uint64 _nonce,
bytes memory _message,
address _messageBus,
uint256 _fee
) internal returns (bytes32) {
address pegBridge;
if (_bridgeSendType == MsgDataTypes.BridgeSendType.PegBurn) {
pegBridge = IMessageBus(_messageBus).pegBridge();
} else {
pegBridge = IMessageBus(_messageBus).pegBridgeV2();
}
IERC20(_token).safeIncreaseAllowance(pegBridge, _amount);
bytes32 transferId;
if (_bridgeSendType == MsgDataTypes.BridgeSendType.PegBurn) {
IPeggedTokenBridge(pegBridge).burn(_token, _amount, _receiver, _nonce);
transferId = keccak256(
abi.encodePacked(address(this), _token, _amount, _receiver, _nonce, uint64(block.chainid))
);
} else if (_bridgeSendType == MsgDataTypes.BridgeSendType.PegV2Burn) {
transferId = IPeggedTokenBridgeV2(pegBridge).burn(_token, _amount, _dstChainId, _receiver, _nonce);
} else {
// PegV2BurnFrom
transferId = IPeggedTokenBridgeV2(pegBridge).burnFrom(_token, _amount, _dstChainId, _receiver, _nonce);
}
// handle cases where certain tokens do not spend allowance for role-based burn
IERC20(_token).safeApprove(pegBridge, 0);
if (_message.length > 0) {
IMessageBus(_messageBus).sendMessageWithTransfer{value: _fee}(
_receiver,
_dstChainId,
pegBridge,
transferId,
_message
);
}
return transferId;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.8.9;
import "./MessageBusSender.sol";
import "./MessageBusReceiver.sol";
contract MessageBus is MessageBusSender, MessageBusReceiver {
constructor(
ISigsVerifier _sigsVerifier,
address _liquidityBridge,
address _pegBridge,
address _pegVault,
address _pegBridgeV2,
address _pegVaultV2
)
MessageBusSender(_sigsVerifier)
MessageBusReceiver(_liquidityBridge, _pegBridge, _pegVault, _pegBridgeV2, _pegVaultV2)
{}
// this is only to be called by Proxy via delegateCall as initOwner will require _owner is 0.
// so calling init on this contract directly will guarantee to fail
function init(
address _liquidityBridge,
address _pegBridge,
address _pegVault,
address _pegBridgeV2,
address _pegVaultV2
) external {
// MUST manually call ownable init and must only call once
initOwner();
// we don't need sender init as _sigsVerifier is immutable so already in the deployed code
initReceiver(_liquidityBridge, _pegBridge, _pegVault, _pegBridgeV2, _pegVaultV2);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity >=0.8.0;
interface IBridge {
function send(
address _receiver,
address _token,
uint256 _amount,
uint64 _dstChainId,
uint64 _nonce,
uint32 _maxSlippage
) external;
function relay(
bytes calldata _relayRequest,
bytes[] calldata _sigs,
address[] calldata _signers,
uint256[] calldata _powers
) external;
function transfers(bytes32 transferId) external view returns (bool);
function withdraws(bytes32 withdrawId) external view returns (bool);
function withdraw(
bytes calldata _wdmsg,
bytes[] calldata _sigs,
address[] calldata _signers,
uint256[] calldata _powers
) external;
/**
* @notice Verifies that a message is signed by a quorum among the signers.
* @param _msg signed message
* @param _sigs list of signatures sorted by signer addresses in ascending order
* @param _signers sorted list of current signers
* @param _powers powers of current signers
*/
function verifySigs(
bytes memory _msg,
bytes[] calldata _sigs,
address[] calldata _signers,
uint256[] calldata _powers
) external view;
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity >=0.8.0;
interface IOriginalTokenVault {
/**
* @notice Lock original tokens to trigger mint at a remote chain's PeggedTokenBridge
* @param _token local token address
* @param _amount locked token amount
* @param _mintChainId destination chainId to mint tokens
* @param _mintAccount destination account to receive minted tokens
* @param _nonce user input to guarantee unique depositId
*/
function deposit(
address _token,
uint256 _amount,
uint64 _mintChainId,
address _mintAccount,
uint64 _nonce
) external;
/**
* @notice Withdraw locked original tokens triggered by a burn at a remote chain's PeggedTokenBridge.
* @param _request The serialized Withdraw protobuf.
* @param _sigs The list of signatures sorted by signing addresses in ascending order. A relay must be signed-off by
* +2/3 of the bridge's current signing power to be delivered.
* @param _signers The sorted list of signers.
* @param _powers The signing powers of the signers.
*/
function withdraw(
bytes calldata _request,
bytes[] calldata _sigs,
address[] calldata _signers,
uint256[] calldata _powers
) external;
function records(bytes32 recordId) external view returns (bool);
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity >=0.8.0;
interface IOriginalTokenVaultV2 {
/**
* @notice Lock original tokens to trigger mint at a remote chain's PeggedTokenBridge
* @param _token local token address
* @param _amount locked token amount
* @param _mintChainId destination chainId to mint tokens
* @param _mintAccount destination account to receive minted tokens
* @param _nonce user input to guarantee unique depositId
*/
function deposit(
address _token,
uint256 _amount,
uint64 _mintChainId,
address _mintAccount,
uint64 _nonce
) external returns (bytes32);
/**
* @notice Withdraw locked original tokens triggered by a burn at a remote chain's PeggedTokenBridge.
* @param _request The serialized Withdraw protobuf.
* @param _sigs The list of signatures sorted by signing addresses in ascending order. A relay must be signed-off by
* +2/3 of the bridge's current signing power to be delivered.
* @param _signers The sorted list of signers.
* @param _powers The signing powers of the signers.
*/
function withdraw(
bytes calldata _request,
bytes[] calldata _sigs,
address[] calldata _signers,
uint256[] calldata _powers
) external returns (bytes32);
function records(bytes32 recordId) external view returns (bool);
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity >=0.8.0;
interface IPeggedTokenBridge {
/**
* @notice Burn tokens to trigger withdrawal at a remote chain's OriginalTokenVault
* @param _token local token address
* @param _amount locked token amount
* @param _withdrawAccount account who withdraw original tokens on the remote chain
* @param _nonce user input to guarantee unique depositId
*/
function burn(
address _token,
uint256 _amount,
address _withdrawAccount,
uint64 _nonce
) external;
/**
* @notice Mint tokens triggered by deposit at a remote chain's OriginalTokenVault.
* @param _request The serialized Mint protobuf.
* @param _sigs The list of signatures sorted by signing addresses in ascending order. A relay must be signed-off by
* +2/3 of the sigsVerifier's current signing power to be delivered.
* @param _signers The sorted list of signers.
* @param _powers The signing powers of the signers.
*/
function mint(
bytes calldata _request,
bytes[] calldata _sigs,
address[] calldata _signers,
uint256[] calldata _powers
) external;
function records(bytes32 recordId) external view returns (bool);
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity >=0.8.0;
interface IPeggedTokenBridgeV2 {
/**
* @notice Burn pegged tokens to trigger a cross-chain withdrawal of the original tokens at a remote chain's
* OriginalTokenVault, or mint at another remote chain
* @param _token The pegged token address.
* @param _amount The amount to burn.
* @param _toChainId If zero, withdraw from original vault; otherwise, the remote chain to mint tokens.
* @param _toAccount The account to receive tokens on the remote chain
* @param _nonce A number to guarantee unique depositId. Can be timestamp in practice.
*/
function burn(
address _token,
uint256 _amount,
uint64 _toChainId,
address _toAccount,
uint64 _nonce
) external returns (bytes32);
// same with `burn` above, use openzeppelin ERC20Burnable interface
function burnFrom(
address _token,
uint256 _amount,
uint64 _toChainId,
address _toAccount,
uint64 _nonce
) external returns (bytes32);
/**
* @notice Mint tokens triggered by deposit at a remote chain's OriginalTokenVault.
* @param _request The serialized Mint protobuf.
* @param _sigs The list of signatures sorted by signing addresses in ascending order. A relay must be signed-off by
* +2/3 of the sigsVerifier's current signing power to be delivered.
* @param _signers The sorted list of signers.
* @param _powers The signing powers of the signers.
*/
function mint(
bytes calldata _request,
bytes[] calldata _sigs,
address[] calldata _signers,
uint256[] calldata _powers
) external returns (bytes32);
function records(bytes32 recordId) external view returns (bool);
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity >=0.8.0;
import "../libraries/MsgDataTypes.sol";
interface IMessageBus {
function liquidityBridge() external view returns (address);
function pegBridge() external view returns (address);
function pegBridgeV2() external view returns (address);
function pegVault() external view returns (address);
function pegVaultV2() external view returns (address);
/**
* @notice Calculates the required fee for the message.
* @param _message Arbitrary message bytes to be decoded by the destination app contract.
@ @return The required fee.
*/
function calcFee(bytes calldata _message) external view returns (uint256);
/**
* @notice Sends a message to a contract on another chain.
* Sender needs to make sure the uniqueness of the message Id, which is computed as
* hash(type.MessageOnly, sender, receiver, srcChainId, srcTxHash, dstChainId, message).
* If messages with the same Id are sent, only one of them will succeed at dst chain..
* A fee is charged in the native gas token.
* @param _receiver The address of the destination app contract.
* @param _dstChainId The destination chain ID.
* @param _message Arbitrary message bytes to be decoded by the destination app contract.
*/
function sendMessage(
address _receiver,
uint256 _dstChainId,
bytes calldata _message
) external payable;
/**
* @notice Sends a message associated with a transfer to a contract on another chain.
* If messages with the same srcTransferId are sent, only one of them will succeed at dst chain..
* A fee is charged in the native token.
* @param _receiver The address of the destination app contract.
* @param _dstChainId The destination chain ID.
* @param _srcBridge The bridge contract to send the transfer with.
* @param _srcTransferId The transfer ID.
* @param _dstChainId The destination chain ID.
* @param _message Arbitrary message bytes to be decoded by the destination app contract.
*/
function sendMessageWithTransfer(
address _receiver,
uint256 _dstChainId,
address _srcBridge,
bytes32 _srcTransferId,
bytes calldata _message
) external payable;
/**
* @notice Withdraws message fee in the form of native gas token.
* @param _account The address receiving the fee.
* @param _cumulativeFee The cumulative fee credited to the account. Tracked by SGN.
* @param _sigs The list of signatures sorted by signing addresses in ascending order. A withdrawal must be
* signed-off by +2/3 of the sigsVerifier's current signing power to be delivered.
* @param _signers The sorted list of signers.
* @param _powers The signing powers of the signers.
*/
function withdrawFee(
address _account,
uint256 _cumulativeFee,
bytes[] calldata _sigs,
address[] calldata _signers,
uint256[] calldata _powers
) external;
/**
* @notice Execute a message with a successful transfer.
* @param _message Arbitrary message bytes originated from and encoded by the source app contract
* @param _transfer The transfer info.
* @param _sigs The list of signatures sorted by signing addresses in ascending order. A relay must be signed-off by
* +2/3 of the sigsVerifier's current signing power to be delivered.
* @param _signers The sorted list of signers.
* @param _powers The signing powers of the signers.
*/
function executeMessageWithTransfer(
bytes calldata _message,
MsgDataTypes.TransferInfo calldata _transfer,
bytes[] calldata _sigs,
address[] calldata _signers,
uint256[] calldata _powers
) external payable;
/**
* @notice Execute a message with a refunded transfer.
* @param _message Arbitrary message bytes originated from and encoded by the source app contract
* @param _transfer The transfer info.
* @param _sigs The list of signatures sorted by signing addresses in ascending order. A relay must be signed-off by
* +2/3 of the sigsVerifier's current signing power to be delivered.
* @param _signers The sorted list of signers.
* @param _powers The signing powers of the signers.
*/
function executeMessageWithTransferRefund(
bytes calldata _message, // the same message associated with the original transfer
MsgDataTypes.TransferInfo calldata _transfer,
bytes[] calldata _sigs,
address[] calldata _signers,
uint256[] calldata _powers
) external payable;
/**
* @notice Execute a message not associated with a transfer.
* @param _message Arbitrary message bytes originated from and encoded by the source app contract
* @param _sigs The list of signatures sorted by signing addresses in ascending order. A relay must be signed-off by
* +2/3 of the sigsVerifier's current signing power to be delivered.
* @param _signers The sorted list of signers.
* @param _powers The signing powers of the signers.
*/
function executeMessage(
bytes calldata _message,
MsgDataTypes.RouteInfo calldata _route,
bytes[] calldata _sigs,
address[] calldata _signers,
uint256[] calldata _powers
) external payable;
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.8.9;
import "../../safeguard/Ownable.sol";
import "../../interfaces/ISigsVerifier.sol";
contract MessageBusSender is Ownable {
ISigsVerifier public immutable sigsVerifier;
uint256 public feeBase;
uint256 public feePerByte;
mapping(address => uint256) public withdrawnFees;
event Message(address indexed sender, address receiver, uint256 dstChainId, bytes message, uint256 fee);
event MessageWithTransfer(
address indexed sender,
address receiver,
uint256 dstChainId,
address bridge,
bytes32 srcTransferId,
bytes message,
uint256 fee
);
event FeeBaseUpdated(uint256 feeBase);
event FeePerByteUpdated(uint256 feePerByte);
constructor(ISigsVerifier _sigsVerifier) {
sigsVerifier = _sigsVerifier;
}
/**
* @notice Sends a message to a contract on another chain.
* Sender needs to make sure the uniqueness of the message Id, which is computed as
* hash(type.MessageOnly, sender, receiver, srcChainId, srcTxHash, dstChainId, message).
* If messages with the same Id are sent, only one of them will succeed at dst chain.
* A fee is charged in the native gas token.
* @param _receiver The address of the destination app contract.
* @param _dstChainId The destination chain ID.
* @param _message Arbitrary message bytes to be decoded by the destination app contract.
*/
function sendMessage(
address _receiver,
uint256 _dstChainId,
bytes calldata _message
) external payable {
require(_dstChainId != block.chainid, "Invalid chainId");
uint256 minFee = calcFee(_message);
require(msg.value >= minFee, "Insufficient fee");
emit Message(msg.sender, _receiver, _dstChainId, _message, msg.value);
}
/**
* @notice Sends a message associated with a transfer to a contract on another chain.
* If messages with the same srcTransferId are sent, only one of them will succeed.
* A fee is charged in the native token.
* @param _receiver The address of the destination app contract.
* @param _dstChainId The destination chain ID.
* @param _srcBridge The bridge contract to send the transfer with.
* @param _srcTransferId The transfer ID.
* @param _dstChainId The destination chain ID.
* @param _message Arbitrary message bytes to be decoded by the destination app contract.
*/
function sendMessageWithTransfer(
address _receiver,
uint256 _dstChainId,
address _srcBridge,
bytes32 _srcTransferId,
bytes calldata _message
) external payable {
require(_dstChainId != block.chainid, "Invalid chainId");
uint256 minFee = calcFee(_message);
require(msg.value >= minFee, "Insufficient fee");
// SGN needs to verify
// 1. msg.sender matches sender of the src transfer
// 2. dstChainId matches dstChainId of the src transfer
// 3. bridge is either liquidity bridge, peg src vault, or peg dst bridge
emit MessageWithTransfer(msg.sender, _receiver, _dstChainId, _srcBridge, _srcTransferId, _message, msg.value);
}
/**
* @notice Withdraws message fee in the form of native gas token.
* @param _account The address receiving the fee.
* @param _cumulativeFee The cumulative fee credited to the account. Tracked by SGN.
* @param _sigs The list of signatures sorted by signing addresses in ascending order. A withdrawal must be
* signed-off by +2/3 of the sigsVerifier's current signing power to be delivered.
* @param _signers The sorted list of signers.
* @param _powers The signing powers of the signers.
*/
function withdrawFee(
address _account,
uint256 _cumulativeFee,
bytes[] calldata _sigs,
address[] calldata _signers,
uint256[] calldata _powers
) external {
bytes32 domain = keccak256(abi.encodePacked(block.chainid, address(this), "withdrawFee"));
sigsVerifier.verifySigs(abi.encodePacked(domain, _account, _cumulativeFee), _sigs, _signers, _powers);
uint256 amount = _cumulativeFee - withdrawnFees[_account];
require(amount > 0, "No new amount to withdraw");
withdrawnFees[_account] = _cumulativeFee;
(bool sent, ) = _account.call{value: amount, gas: 50000}("");
require(sent, "failed to withdraw fee");
}
/**
* @notice Calculates the required fee for the message.
* @param _message Arbitrary message bytes to be decoded by the destination app contract.
@ @return The required fee.
*/
function calcFee(bytes calldata _message) public view returns (uint256) {
return feeBase + _message.length * feePerByte;
}
// -------------------- Admin --------------------
function setFeePerByte(uint256 _fee) external onlyOwner {
feePerByte = _fee;
emit FeePerByteUpdated(feePerByte);
}
function setFeeBase(uint256 _fee) external onlyOwner {
feeBase = _fee;
emit FeeBaseUpdated(feeBase);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.8.9;
import "../libraries/MsgDataTypes.sol";
import "../interfaces/IMessageReceiverApp.sol";
import "../interfaces/IMessageBus.sol";
import "../../interfaces/IBridge.sol";
import "../../interfaces/IOriginalTokenVault.sol";
import "../../interfaces/IOriginalTokenVaultV2.sol";
import "../../interfaces/IPeggedTokenBridge.sol";
import "../../interfaces/IPeggedTokenBridgeV2.sol";
import "../../safeguard/Ownable.sol";
contract MessageBusReceiver is Ownable {
mapping(bytes32 => MsgDataTypes.TxStatus) public executedMessages;
address public liquidityBridge; // liquidity bridge address
address public pegBridge; // peg bridge address
address public pegVault; // peg original vault address
address public pegBridgeV2; // peg bridge address
address public pegVaultV2; // peg original vault address
// minimum amount of gas needed by this contract before it tries to
// deliver a message to the target contract.
uint256 public preExecuteMessageGasUsage;
event Executed(
MsgDataTypes.MsgType msgType,
bytes32 msgId,
MsgDataTypes.TxStatus status,
address indexed receiver,
uint64 srcChainId,
bytes32 srcTxHash
);
event NeedRetry(MsgDataTypes.MsgType msgType, bytes32 msgId, uint64 srcChainId, bytes32 srcTxHash);
event CallReverted(string reason); // help debug
event LiquidityBridgeUpdated(address liquidityBridge);
event PegBridgeUpdated(address pegBridge);
event PegVaultUpdated(address pegVault);
event PegBridgeV2Updated(address pegBridgeV2);
event PegVaultV2Updated(address pegVaultV2);
constructor(
address _liquidityBridge,
address _pegBridge,
address _pegVault,
address _pegBridgeV2,
address _pegVaultV2
) {
liquidityBridge = _liquidityBridge;
pegBridge = _pegBridge;
pegVault = _pegVault;
pegBridgeV2 = _pegBridgeV2;
pegVaultV2 = _pegVaultV2;
}
function initReceiver(
address _liquidityBridge,
address _pegBridge,
address _pegVault,
address _pegBridgeV2,
address _pegVaultV2
) internal {
require(liquidityBridge == address(0), "liquidityBridge already set");
liquidityBridge = _liquidityBridge;
pegBridge = _pegBridge;
pegVault = _pegVault;
pegBridgeV2 = _pegBridgeV2;
pegVaultV2 = _pegVaultV2;
}
// ============== functions called by executor ==============
/**
* @notice Execute a message with a successful transfer.
* @param _message Arbitrary message bytes originated from and encoded by the source app contract
* @param _transfer The transfer info.
* @param _sigs The list of signatures sorted by signing addresses in ascending order. A relay must be signed-off by
* +2/3 of the sigsVerifier's current signing power to be delivered.
* @param _signers The sorted list of signers.
* @param _powers The signing powers of the signers.
*/
function executeMessageWithTransfer(
bytes calldata _message,
MsgDataTypes.TransferInfo calldata _transfer,
bytes[] calldata _sigs,
address[] calldata _signers,
uint256[] calldata _powers
) public payable {
// For message with token transfer, message Id is computed through transfer info
// in order to guarantee that each transfer can only be used once.
bytes32 messageId = verifyTransfer(_transfer);
require(executedMessages[messageId] == MsgDataTypes.TxStatus.Null, "transfer already executed");
executedMessages[messageId] = MsgDataTypes.TxStatus.Pending;
bytes32 domain = keccak256(abi.encodePacked(block.chainid, address(this), "MessageWithTransfer"));
IBridge(liquidityBridge).verifySigs(
abi.encodePacked(domain, messageId, _message, _transfer.srcTxHash),
_sigs,
_signers,
_powers
);
MsgDataTypes.TxStatus status;
IMessageReceiverApp.ExecutionStatus est = executeMessageWithTransfer(_transfer, _message);
if (est == IMessageReceiverApp.ExecutionStatus.Success) {
status = MsgDataTypes.TxStatus.Success;
} else if (est == IMessageReceiverApp.ExecutionStatus.Retry) {
executedMessages[messageId] = MsgDataTypes.TxStatus.Null;
emit NeedRetry(
MsgDataTypes.MsgType.MessageWithTransfer,
messageId,
_transfer.srcChainId,
_transfer.srcTxHash
);
return;
} else {
est = executeMessageWithTransferFallback(_transfer, _message);
if (est == IMessageReceiverApp.ExecutionStatus.Success) {
status = MsgDataTypes.TxStatus.Fallback;
} else {
status = MsgDataTypes.TxStatus.Fail;
}
}
executedMessages[messageId] = status;
emitMessageWithTransferExecutedEvent(messageId, status, _transfer);
}
/**
* @notice Execute a message with a refunded transfer.
* @param _message Arbitrary message bytes originated from and encoded by the source app contract
* @param _transfer The transfer info.
* @param _sigs The list of signatures sorted by signing addresses in ascending order. A relay must be signed-off by
* +2/3 of the sigsVerifier's current signing power to be delivered.
* @param _signers The sorted list of signers.
* @param _powers The signing powers of the signers.
*/
function executeMessageWithTransferRefund(
bytes calldata _message, // the same message associated with the original transfer
MsgDataTypes.TransferInfo calldata _transfer,
bytes[] calldata _sigs,
address[] calldata _signers,
uint256[] calldata _powers
) public payable {
// similar to executeMessageWithTransfer
bytes32 messageId = verifyTransfer(_transfer);
require(executedMessages[messageId] == MsgDataTypes.TxStatus.Null, "transfer already executed");
executedMessages[messageId] = MsgDataTypes.TxStatus.Pending;
bytes32 domain = keccak256(abi.encodePacked(block.chainid, address(this), "MessageWithTransferRefund"));
IBridge(liquidityBridge).verifySigs(
abi.encodePacked(domain, messageId, _message, _transfer.srcTxHash),
_sigs,
_signers,
_powers
);
MsgDataTypes.TxStatus status;
IMessageReceiverApp.ExecutionStatus est = executeMessageWithTransferRefund(_transfer, _message);
if (est == IMessageReceiverApp.ExecutionStatus.Success) {
status = MsgDataTypes.TxStatus.Success;
} else if (est == IMessageReceiverApp.ExecutionStatus.Retry) {
executedMessages[messageId] = MsgDataTypes.TxStatus.Null;
emit NeedRetry(
MsgDataTypes.MsgType.MessageWithTransfer,
messageId,
_transfer.srcChainId,
_transfer.srcTxHash
);
return;
} else {
status = MsgDataTypes.TxStatus.Fail;
}
executedMessages[messageId] = status;
emitMessageWithTransferExecutedEvent(messageId, status, _transfer);
}
/**
* @notice Execute a message not associated with a transfer.
* @param _message Arbitrary message bytes originated from and encoded by the source app contract
* @param _sigs The list of signatures sorted by signing addresses in ascending order. A relay must be signed-off by
* +2/3 of the sigsVerifier's current signing power to be delivered.
* @param _signers The sorted list of signers.
* @param _powers The signing powers of the signers.
*/
function executeMessage(
bytes calldata _message,
MsgDataTypes.RouteInfo calldata _route,
bytes[] calldata _sigs,
address[] calldata _signers,
uint256[] calldata _powers
) external payable {
// For message without associated token transfer, message Id is computed through message info,
// in order to guarantee that each message can only be applied once
bytes32 messageId = computeMessageOnlyId(_route, _message);
require(executedMessages[messageId] == MsgDataTypes.TxStatus.Null, "message already executed");
executedMessages[messageId] = MsgDataTypes.TxStatus.Pending;
bytes32 domain = keccak256(abi.encodePacked(block.chainid, address(this), "Message"));
IBridge(liquidityBridge).verifySigs(abi.encodePacked(domain, messageId), _sigs, _signers, _powers);
MsgDataTypes.TxStatus status;
IMessageReceiverApp.ExecutionStatus est = executeMessage(_route, _message);
if (est == IMessageReceiverApp.ExecutionStatus.Success) {
status = MsgDataTypes.TxStatus.Success;
} else if (est == IMessageReceiverApp.ExecutionStatus.Retry) {
executedMessages[messageId] = MsgDataTypes.TxStatus.Null;
emit NeedRetry(MsgDataTypes.MsgType.MessageOnly, messageId, _route.srcChainId, _route.srcTxHash);
return;
} else {
status = MsgDataTypes.TxStatus.Fail;
}
executedMessages[messageId] = status;
emitMessageOnlyExecutedEvent(messageId, status, _route);
}
// ================= utils (to avoid stack too deep) =================
function emitMessageWithTransferExecutedEvent(
bytes32 _messageId,
MsgDataTypes.TxStatus _status,
MsgDataTypes.TransferInfo calldata _transfer
) private {
emit Executed(
MsgDataTypes.MsgType.MessageWithTransfer,
_messageId,
_status,
_transfer.receiver,
_transfer.srcChainId,
_transfer.srcTxHash
);
}
function emitMessageOnlyExecutedEvent(
bytes32 _messageId,
MsgDataTypes.TxStatus _status,
MsgDataTypes.RouteInfo calldata _route
) private {
emit Executed(
MsgDataTypes.MsgType.MessageOnly,
_messageId,
_status,
_route.receiver,
_route.srcChainId,
_route.srcTxHash
);
}
function executeMessageWithTransfer(MsgDataTypes.TransferInfo calldata _transfer, bytes calldata _message)
private
returns (IMessageReceiverApp.ExecutionStatus)
{
uint256 gasLeftBeforeExecution = gasleft();
(bool ok, bytes memory res) = address(_transfer.receiver).call{value: msg.value}(
abi.encodeWithSelector(
IMessageReceiverApp.executeMessageWithTransfer.selector,
_transfer.sender,
_transfer.token,
_transfer.amount,
_transfer.srcChainId,
_message,
msg.sender
)
);
if (ok) {
return abi.decode((res), (IMessageReceiverApp.ExecutionStatus));
}
handleExecutionRevert(gasLeftBeforeExecution, res);
return IMessageReceiverApp.ExecutionStatus.Fail;
}
function executeMessageWithTransferFallback(MsgDataTypes.TransferInfo calldata _transfer, bytes calldata _message)
private
returns (IMessageReceiverApp.ExecutionStatus)
{
uint256 gasLeftBeforeExecution = gasleft();
(bool ok, bytes memory res) = address(_transfer.receiver).call{value: msg.value}(
abi.encodeWithSelector(
IMessageReceiverApp.executeMessageWithTransferFallback.selector,
_transfer.sender,
_transfer.token,
_transfer.amount,
_transfer.srcChainId,
_message,
msg.sender
)
);
if (ok) {
return abi.decode((res), (IMessageReceiverApp.ExecutionStatus));
}
handleExecutionRevert(gasLeftBeforeExecution, res);
return IMessageReceiverApp.ExecutionStatus.Fail;
}
function executeMessageWithTransferRefund(MsgDataTypes.TransferInfo calldata _transfer, bytes calldata _message)
private
returns (IMessageReceiverApp.ExecutionStatus)
{
uint256 gasLeftBeforeExecution = gasleft();
(bool ok, bytes memory res) = address(_transfer.receiver).call{value: msg.value}(
abi.encodeWithSelector(
IMessageReceiverApp.executeMessageWithTransferRefund.selector,
_transfer.token,
_transfer.amount,
_message,
msg.sender
)
);
if (ok) {
return abi.decode((res), (IMessageReceiverApp.ExecutionStatus));
}
handleExecutionRevert(gasLeftBeforeExecution, res);
return IMessageReceiverApp.ExecutionStatus.Fail;
}
function verifyTransfer(MsgDataTypes.TransferInfo calldata _transfer) private view returns (bytes32) {
bytes32 transferId;
address bridgeAddr;
if (_transfer.t == MsgDataTypes.TransferType.LqRelay) {
transferId = keccak256(
abi.encodePacked(
_transfer.sender,
_transfer.receiver,
_transfer.token,
_transfer.amount,
_transfer.srcChainId,
uint64(block.chainid),
_transfer.refId
)
);
bridgeAddr = liquidityBridge;
require(IBridge(bridgeAddr).transfers(transferId) == true, "bridge relay not exist");
} else if (_transfer.t == MsgDataTypes.TransferType.LqWithdraw) {
transferId = keccak256(
abi.encodePacked(
uint64(block.chainid),
_transfer.wdseq,
_transfer.receiver,
_transfer.token,
_transfer.amount
)
);
bridgeAddr = liquidityBridge;
require(IBridge(bridgeAddr).withdraws(transferId) == true, "bridge withdraw not exist");
} else if (
_transfer.t == MsgDataTypes.TransferType.PegMint || _transfer.t == MsgDataTypes.TransferType.PegWithdraw
) {
transferId = keccak256(
abi.encodePacked(
_transfer.receiver,
_transfer.token,
_transfer.amount,
_transfer.sender,
_transfer.srcChainId,
_transfer.refId
)
);
if (_transfer.t == MsgDataTypes.TransferType.PegMint) {
bridgeAddr = pegBridge;
require(IPeggedTokenBridge(bridgeAddr).records(transferId) == true, "mint record not exist");
} else {
// _transfer.t == MsgDataTypes.TransferType.PegWithdraw
bridgeAddr = pegVault;
require(IOriginalTokenVault(bridgeAddr).records(transferId) == true, "withdraw record not exist");
}
} else if (
_transfer.t == MsgDataTypes.TransferType.PegV2Mint || _transfer.t == MsgDataTypes.TransferType.PegV2Withdraw
) {
if (_transfer.t == MsgDataTypes.TransferType.PegV2Mint) {
bridgeAddr = pegBridgeV2;
} else {
// MsgDataTypes.TransferType.PegV2Withdraw
bridgeAddr = pegVaultV2;
}
transferId = keccak256(
abi.encodePacked(
_transfer.receiver,
_transfer.token,
_transfer.amount,
_transfer.sender,
_transfer.srcChainId,
_transfer.refId,
bridgeAddr
)
);
if (_transfer.t == MsgDataTypes.TransferType.PegV2Mint) {
require(IPeggedTokenBridgeV2(bridgeAddr).records(transferId) == true, "mint record not exist");
} else {
// MsgDataTypes.TransferType.PegV2Withdraw
require(IOriginalTokenVaultV2(bridgeAddr).records(transferId) == true, "withdraw record not exist");
}
}
return keccak256(abi.encodePacked(MsgDataTypes.MsgType.MessageWithTransfer, bridgeAddr, transferId));
}
function computeMessageOnlyId(MsgDataTypes.RouteInfo calldata _route, bytes calldata _message)
private
view
returns (bytes32)
{
return
keccak256(
abi.encodePacked(
MsgDataTypes.MsgType.MessageOnly,
_route.sender,
_route.receiver,
_route.srcChainId,
_route.srcTxHash,
uint64(block.chainid),
_message
)
);
}
function executeMessage(MsgDataTypes.RouteInfo calldata _route, bytes calldata _message)
private
returns (IMessageReceiverApp.ExecutionStatus)
{
uint256 gasLeftBeforeExecution = gasleft();
(bool ok, bytes memory res) = address(_route.receiver).call{value: msg.value}(
abi.encodeWithSelector(
IMessageReceiverApp.executeMessage.selector,
_route.sender,
_route.srcChainId,
_message,
msg.sender
)
);
if (ok) {
return abi.decode((res), (IMessageReceiverApp.ExecutionStatus));
}
handleExecutionRevert(gasLeftBeforeExecution, res);
return IMessageReceiverApp.ExecutionStatus.Fail;
}
function handleExecutionRevert(uint256 _gasLeftBeforeExecution, bytes memory _returnData) private {
uint256 gasLeftAfterExecution = gasleft();
uint256 maxTargetGasLimit = block.gaslimit - preExecuteMessageGasUsage;
if (_gasLeftBeforeExecution < maxTargetGasLimit && gasLeftAfterExecution <= _gasLeftBeforeExecution / 64) {
// if this happens, the executor must have not provided sufficient gas limit,
// then the tx should revert instead of recording a non-retryable failure status
// https://github.com/wolflo/evm-opcodes/blob/main/gas.md#aa-f-gas-to-send-with-call-operations
assembly {
invalid()
}
}
emit CallReverted(getRevertMsg(_returnData));
}
// https://ethereum.stackexchange.com/a/83577
// https://github.com/Uniswap/v3-periphery/blob/v1.0.0/contracts/base/Multicall.sol
function getRevertMsg(bytes memory _returnData) private pure returns (string memory) {
// If the _res length is less than 68, then the transaction failed silently (without a revert message)
if (_returnData.length < 68) return "Transaction reverted silently";
assembly {
// Slice the sighash.
_returnData := add(_returnData, 0x04)
}
return abi.decode(_returnData, (string)); // All that remains is the revert string
}
// ================= helper functions =====================
/**
* @notice combine bridge transfer and msg execution calls into a single tx
* @dev caller needs to get the required input params from SGN
* @param _transferParams params to call bridge transfer
* @param _msgParams params to execute message
*/
function transferAndExecuteMsg(
MsgDataTypes.BridgeTransferParams calldata _transferParams,
MsgDataTypes.MsgWithTransferExecutionParams calldata _msgParams
) external {
_bridgeTransfer(_msgParams.transfer.t, _transferParams);
executeMessageWithTransfer(
_msgParams.message,
_msgParams.transfer,
_msgParams.sigs,
_msgParams.signers,
_msgParams.powers
);
}
/**
* @notice combine bridge refund and msg execution calls into a single tx
* @dev caller needs to get the required input params from SGN
* @param _transferParams params to call bridge transfer for refund
* @param _msgParams params to execute message for refund
*/
function refundAndExecuteMsg(
MsgDataTypes.BridgeTransferParams calldata _transferParams,
MsgDataTypes.MsgWithTransferExecutionParams calldata _msgParams
) external {
_bridgeTransfer(_msgParams.transfer.t, _transferParams);
executeMessageWithTransferRefund(
_msgParams.message,
_msgParams.transfer,
_msgParams.sigs,
_msgParams.signers,
_msgParams.powers
);
}
function _bridgeTransfer(MsgDataTypes.TransferType t, MsgDataTypes.BridgeTransferParams calldata _transferParams)
private
{
if (t == MsgDataTypes.TransferType.LqRelay) {
IBridge(liquidityBridge).relay(
_transferParams.request,
_transferParams.sigs,
_transferParams.signers,
_transferParams.powers
);
} else if (t == MsgDataTypes.TransferType.LqWithdraw) {
IBridge(liquidityBridge).withdraw(
_transferParams.request,
_transferParams.sigs,
_transferParams.signers,
_transferParams.powers
);
} else if (t == MsgDataTypes.TransferType.PegMint) {
IPeggedTokenBridge(pegBridge).mint(
_transferParams.request,
_transferParams.sigs,
_transferParams.signers,
_transferParams.powers
);
} else if (t == MsgDataTypes.TransferType.PegV2Mint) {
IPeggedTokenBridgeV2(pegBridgeV2).mint(
_transferParams.request,
_transferParams.sigs,
_transferParams.signers,
_transferParams.powers
);
} else if (t == MsgDataTypes.TransferType.PegWithdraw) {
IOriginalTokenVault(pegVault).withdraw(
_transferParams.request,
_transferParams.sigs,
_transferParams.signers,
_transferParams.powers
);
} else if (t == MsgDataTypes.TransferType.PegV2Withdraw) {
IOriginalTokenVaultV2(pegVaultV2).withdraw(
_transferParams.request,
_transferParams.sigs,
_transferParams.signers,
_transferParams.powers
);
}
}
// ================= contract config =================
function setLiquidityBridge(address _addr) public onlyOwner {
require(_addr != address(0), "invalid address");
liquidityBridge = _addr;
emit LiquidityBridgeUpdated(liquidityBridge);
}
function setPegBridge(address _addr) public onlyOwner {
require(_addr != address(0), "invalid address");
pegBridge = _addr;
emit PegBridgeUpdated(pegBridge);
}
function setPegVault(address _addr) public onlyOwner {
require(_addr != address(0), "invalid address");
pegVault = _addr;
emit PegVaultUpdated(pegVault);
}
function setPegBridgeV2(address _addr) public onlyOwner {
require(_addr != address(0), "invalid address");
pegBridgeV2 = _addr;
emit PegBridgeV2Updated(pegBridgeV2);
}
function setPegVaultV2(address _addr) public onlyOwner {
require(_addr != address(0), "invalid address");
pegVaultV2 = _addr;
emit PegVaultV2Updated(pegVaultV2);
}
function setPreExecuteMessageGasUsage(uint256 _usage) public onlyOwner {
preExecuteMessageGasUsage = _usage;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity >=0.8.0;
interface IMessageReceiverApp {
enum ExecutionStatus {
Fail, // execution failed, finalized
Success, // execution succeeded, finalized
Retry // execution rejected, can retry later
}
/**
* @notice Called by MessageBus (MessageBusReceiver) if the process is originated from MessageBus (MessageBusSender)'s
* sendMessageWithTransfer it is only called when the tokens are checked to be arrived at this contract's address.
* @param _sender The address of the source app contract
* @param _token The address of the token that comes out of the bridge
* @param _amount The amount of tokens received at this contract through the cross-chain bridge.
* the contract that implements this contract can safely assume that the tokens will arrive before this
* function is called.
* @param _srcChainId The source chain ID where the transfer is originated from
* @param _message Arbitrary message bytes originated from and encoded by the source app contract
* @param _executor Address who called the MessageBus execution function
*/
function executeMessageWithTransfer(
address _sender,
address _token,
uint256 _amount,
uint64 _srcChainId,
bytes calldata _message,
address _executor
) external payable returns (ExecutionStatus);
/**
* @notice Only called by MessageBus (MessageBusReceiver) if
* 1. executeMessageWithTransfer reverts, or
* 2. executeMessageWithTransfer returns ExecutionStatus.Fail
* @param _sender The address of the source app contract
* @param _token The address of the token that comes out of the bridge
* @param _amount The amount of tokens received at this contract through the cross-chain bridge.
* the contract that implements this contract can safely assume that the tokens will arrive before this
* function is called.
* @param _srcChainId The source chain ID where the transfer is originated from
* @param _message Arbitrary message bytes originated from and encoded by the source app contract
* @param _executor Address who called the MessageBus execution function
*/
function executeMessageWithTransferFallback(
address _sender,
address _token,
uint256 _amount,
uint64 _srcChainId,
bytes calldata _message,
address _executor
) external payable returns (ExecutionStatus);
/**
* @notice Called by MessageBus (MessageBusReceiver) to process refund of the original transfer from this contract
* @param _token The token address of the original transfer
* @param _amount The amount of the original transfer
* @param _message The same message associated with the original transfer
* @param _executor Address who called the MessageBus execution function
*/
function executeMessageWithTransferRefund(
address _token,
uint256 _amount,
bytes calldata _message,
address _executor
) external payable returns (ExecutionStatus);
/**
* @notice Called by MessageBus (MessageBusReceiver)
* @param _sender The address of the source app contract
* @param _srcChainId The source chain ID where the transfer is originated from
* @param _message Arbitrary message bytes originated from and encoded by the source app contract
* @param _executor Address who called the MessageBus execution function
*/
function executeMessage(
address _sender,
uint64 _srcChainId,
bytes calldata _message,
address _executor
) external payable returns (ExecutionStatus);
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity >=0.8.9;
import "../framework/MessageSenderApp.sol";
import "../framework/MessageReceiverApp.sol";
interface ISwapToken {
// function sellBase(address to) external returns (uint256);
// uniswap v2
function swapExactTokensForTokens(
uint256,
uint256,
address[] calldata,
address,
uint256
) external returns (uint256[] memory);
}
contract CrossChainSwap is MessageSenderApp, MessageReceiverApp {
using SafeERC20 for IERC20;
address public dex; // needed on swap chain
struct SwapInfo {
address wantToken; // token user want to receive on dest chain
address user;
bool sendBack; // if true, send wantToken back to start chain
uint32 cbrMaxSlippage; // _maxSlippage for cbridge send
}
constructor(address dex_) {
dex = dex_;
}
// ========== on start chain ==========
uint64 nonce; // required by IBridge.send
// this func could be called by a router contract
function startCrossChainSwap(
address _receiver,
address _token,
uint256 _amount,
uint64 _dstChainId,
SwapInfo calldata swapInfo // wantToken on destChain and actual user address as receiver when send back
) external payable {
nonce += 1;
IERC20(_token).safeTransferFrom(msg.sender, address(this), _amount);
bytes memory message = abi.encode(swapInfo);
sendMessageWithTransfer(
_receiver,
_token,
_amount,
_dstChainId,
nonce,
swapInfo.cbrMaxSlippage,
message,
MsgDataTypes.BridgeSendType.Liquidity,
msg.value
);
}
// ========== on swap chain ==========
// do dex, send received asset to src chain via bridge
function executeMessageWithTransfer(
address, // _sender
address _token,
uint256 _amount,
uint64 _srcChainId,
bytes memory _message,
address // executor
) external payable override onlyMessageBus returns (ExecutionStatus) {
SwapInfo memory swapInfo = abi.decode((_message), (SwapInfo));
IERC20(_token).approve(dex, _amount);
address[] memory path = new address[](2);
path[0] = _token;
path[1] = swapInfo.wantToken;
if (swapInfo.sendBack) {
nonce += 1;
uint256[] memory swapReturn = ISwapToken(dex).swapExactTokensForTokens(
_amount,
0,
path,
address(this),
type(uint256).max
);
// send received token back to start chain. swapReturn[1] is amount of wantToken
sendTokenTransfer(
swapInfo.user,
swapInfo.wantToken,
swapReturn[1],
_srcChainId,
nonce,
swapInfo.cbrMaxSlippage,
MsgDataTypes.BridgeSendType.Liquidity
);
} else {
// swap to wantToken and send to user
ISwapToken(dex).swapExactTokensForTokens(_amount, 0, path, swapInfo.user, type(uint256).max);
}
// bytes memory notice; // send back to src chain to handleMessage
// sendMessage(_sender, _srcChainId, notice);
return ExecutionStatus.Success;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity >=0.8.9;
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../framework/MessageSenderApp.sol";
import "../framework/MessageReceiverApp.sol";
/** @title Application to test message with transfer refund flow */
contract MsgTest is MessageSenderApp, MessageReceiverApp {
using SafeERC20 for IERC20;
uint64 nonce;
event MessageReceivedWithTransfer(
address token,
uint256 amount,
address sender,
uint64 srcChainId,
address receiver,
bytes message
);
event Refunded(address receiver, address token, uint256 amount, bytes message);
event MessageReceived(address sender, uint64 srcChainId, uint64 nonce, bytes message);
constructor(address _messageBus) {
messageBus = _messageBus;
}
function sendMessageWithTransfer(
address _receiver,
address _token,
uint256 _amount,
uint64 _dstChainId,
uint32 _maxSlippage,
bytes calldata _message,
MsgDataTypes.BridgeSendType _bridgeSendType
) external payable {
IERC20(_token).safeTransferFrom(msg.sender, address(this), _amount);
bytes memory message = abi.encode(msg.sender, _message);
sendMessageWithTransfer(
_receiver,
_token,
_amount,
_dstChainId,
nonce,
_maxSlippage,
message,
_bridgeSendType,
msg.value
);
nonce++;
}
function executeMessageWithTransfer(
address _sender,
address _token,
uint256 _amount,
uint64 _srcChainId,
bytes memory _message,
address // executor
) external payable override onlyMessageBus returns (ExecutionStatus) {
(address receiver, bytes memory message) = abi.decode((_message), (address, bytes));
IERC20(_token).safeTransfer(receiver, _amount);
emit MessageReceivedWithTransfer(_token, _amount, _sender, _srcChainId, receiver, message);
return ExecutionStatus.Success;
}
function executeMessageWithTransferRefund(
address _token,
uint256 _amount,
bytes calldata _message,
address // executor
) external payable override onlyMessageBus returns (ExecutionStatus) {
(address receiver, bytes memory message) = abi.decode((_message), (address, bytes));
IERC20(_token).safeTransfer(receiver, _amount);
emit Refunded(receiver, _token, _amount, message);
return ExecutionStatus.Success;
}
function sendMessage(
address _receiver,
uint64 _dstChainId,
bytes calldata _message
) external payable {
bytes memory message = abi.encode(nonce, _message);
nonce++;
sendMessage(_receiver, _dstChainId, message, msg.value);
}
function executeMessage(
address _sender,
uint64 _srcChainId,
bytes calldata _message,
address // executor
) external payable override onlyMessageBus returns (ExecutionStatus) {
(uint64 n, bytes memory message) = abi.decode((_message), (uint64, bytes));
require(n != 100000000000001, "invalid nonce"); // test revert with reason
if (n == 100000000000002) {
// test revert without reason
revert();
}
emit MessageReceived(_sender, _srcChainId, n, message);
return ExecutionStatus.Success;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity >=0.8.9;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
contract DummySwap {
using SafeERC20 for IERC20;
uint256 fakeSlippage; // 100% = 100 * 1e4
uint256 hundredPercent = 100 * 1e4;
constructor(uint256 _fakeSlippage) {
fakeSlippage = _fakeSlippage;
}
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts) {
require(deadline != 0 && deadline > block.timestamp, "deadline exceeded");
require(path.length > 1, "path must have more than 1 token in it");
IERC20(path[0]).transferFrom(msg.sender, address(this), amountIn);
// fake simulate slippage
uint256 amountAfterSlippage = (amountIn * (hundredPercent - fakeSlippage)) / hundredPercent;
require(amountAfterSlippage > amountOutMin, "bad slippage");
IERC20(path[path.length - 1]).safeTransfer(to, amountAfterSlippage);
uint256[] memory ret = new uint256[](2);
ret[0] = amountIn;
ret[1] = amountAfterSlippage;
return ret;
}
function setFakeSlippage(uint256 _fakeSlippage) public {
fakeSlippage = _fakeSlippage;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.8.9;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {DataTypes as dt} from "./DataTypes.sol";
import "./Staking.sol";
/**
* @title Governance module for Staking contract
*/
contract Govern {
using SafeERC20 for IERC20;
Staking public immutable staking;
IERC20 public immutable celerToken;
enum ProposalStatus {
Uninitiated,
Voting,
Closed
}
enum VoteOption {
Null,
Yes,
Abstain,
No
}
struct ParamProposal {
address proposer;
uint256 deposit;
uint256 voteDeadline;
dt.ParamName name;
uint256 newValue;
ProposalStatus status;
mapping(address => VoteOption) votes;
}
mapping(uint256 => ParamProposal) public paramProposals;
uint256 public nextParamProposalId;
uint256 public forfeiture;
address public immutable collector;
event CreateParamProposal(
uint256 proposalId,
address proposer,
uint256 deposit,
uint256 voteDeadline,
dt.ParamName name,
uint256 newValue
);
event VoteParam(uint256 proposalId, address voter, VoteOption vote);
event ConfirmParamProposal(uint256 proposalId, bool passed, dt.ParamName name, uint256 newValue);
constructor(
Staking _staking,
address _celerTokenAddress,
address _collector
) {
staking = _staking;
celerToken = IERC20(_celerTokenAddress);
collector = _collector;
}
/**
* @notice Get the vote type of a voter on a parameter proposal
* @param _proposalId the proposal id
* @param _voter the voter address
* @return the vote type of the given voter on the given parameter proposal
*/
function getParamProposalVote(uint256 _proposalId, address _voter) public view returns (VoteOption) {
return paramProposals[_proposalId].votes[_voter];
}
/**
* @notice Create a parameter proposal
* @param _name the key of this parameter
* @param _value the new proposed value of this parameter
*/
function createParamProposal(dt.ParamName _name, uint256 _value) external {
ParamProposal storage p = paramProposals[nextParamProposalId];
nextParamProposalId = nextParamProposalId + 1;
address msgSender = msg.sender;
uint256 deposit = staking.getParamValue(dt.ParamName.ProposalDeposit);
p.proposer = msgSender;
p.deposit = deposit;
p.voteDeadline = block.number + staking.getParamValue(dt.ParamName.VotingPeriod);
p.name = _name;
p.newValue = _value;
p.status = ProposalStatus.Voting;
celerToken.safeTransferFrom(msgSender, address(this), deposit);
emit CreateParamProposal(nextParamProposalId - 1, msgSender, deposit, p.voteDeadline, _name, _value);
}
/**
* @notice Vote for a parameter proposal with a specific type of vote
* @param _proposalId the id of the parameter proposal
* @param _vote the type of vote
*/
function voteParam(uint256 _proposalId, VoteOption _vote) external {
address valAddr = msg.sender;
require(staking.getValidatorStatus(valAddr) == dt.ValidatorStatus.Bonded, "Voter is not a bonded validator");
ParamProposal storage p = paramProposals[_proposalId];
require(p.status == ProposalStatus.Voting, "Invalid proposal status");
require(block.number < p.voteDeadline, "Vote deadline passed");
require(p.votes[valAddr] == VoteOption.Null, "Voter has voted");
require(_vote != VoteOption.Null, "Invalid vote");
p.votes[valAddr] = _vote;
emit VoteParam(_proposalId, valAddr, _vote);
}
/**
* @notice Confirm a parameter proposal
* @param _proposalId the id of the parameter proposal
*/
function confirmParamProposal(uint256 _proposalId) external {
uint256 yesVotes;
uint256 bondedTokens;
dt.ValidatorTokens[] memory validators = staking.getBondedValidatorsTokens();
for (uint32 i = 0; i < validators.length; i++) {
if (getParamProposalVote(_proposalId, validators[i].valAddr) == VoteOption.Yes) {
yesVotes += validators[i].tokens;
}
bondedTokens += validators[i].tokens;
}
bool passed = (yesVotes >= (bondedTokens * 2) / 3 + 1);
ParamProposal storage p = paramProposals[_proposalId];
require(p.status == ProposalStatus.Voting, "Invalid proposal status");
require(block.number >= p.voteDeadline, "Vote deadline not reached");
p.status = ProposalStatus.Closed;
if (passed) {
staking.setParamValue(p.name, p.newValue);
celerToken.safeTransfer(p.proposer, p.deposit);
} else {
forfeiture += p.deposit;
}
emit ConfirmParamProposal(_proposalId, passed, p.name, p.newValue);
}
function collectForfeiture() external {
require(forfeiture > 0, "Nothing to collect");
celerToken.safeTransfer(collector, forfeiture);
forfeiture = 0;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity >=0.8.9;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
interface ISwapCanoToken {
function swapBridgeForCanonical(address, uint256) external returns (uint256);
function swapCanonicalForBridge(address, uint256) external returns (uint256);
}
/**
* @title Per bridge intermediary token that supports swapping with a canonical token.
*/
contract SwapBridgeToken is ERC20, Ownable {
using SafeERC20 for IERC20;
address public bridge;
address public immutable canonical; // canonical token that support swap
event BridgeUpdated(address bridge);
modifier onlyBridge() {
require(msg.sender == bridge, "caller is not bridge");
_;
}
constructor(
string memory name_,
string memory symbol_,
address bridge_,
address canonical_
) ERC20(name_, symbol_) {
bridge = bridge_;
canonical = canonical_;
}
function mint(address _to, uint256 _amount) external onlyBridge returns (bool) {
_mint(address(this), _amount); // add amount to myself so swapBridgeForCanonical can transfer amount
uint256 got = ISwapCanoToken(canonical).swapBridgeForCanonical(address(this), _amount);
// now this has canonical token, next step is to transfer to user
IERC20(canonical).safeTransfer(_to, got);
return true;
}
function burn(address _from, uint256 _amount) external onlyBridge returns (bool) {
IERC20(canonical).safeTransferFrom(_from, address(this), _amount);
uint256 got = ISwapCanoToken(canonical).swapCanonicalForBridge(address(this), _amount);
_burn(address(this), got);
return true;
}
function updateBridge(address _bridge) external onlyOwner {
bridge = _bridge;
emit BridgeUpdated(bridge);
}
// approve canonical token so swapBridgeForCanonical can work. or we approve before call it in mint w/ added gas
function approveCanonical() external onlyOwner {
_approve(address(this), canonical, type(uint256).max);
}
function revokeCanonical() external onlyOwner {
_approve(address(this), canonical, 0);
}
// to make compatible with BEP20
function getOwner() external view returns (address) {
return owner();
}
function decimals() public view virtual override returns (uint8) {
return ERC20(canonical).decimals();
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.0;
import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address to, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_transfer(owner, to, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_approve(owner, spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
* - the caller must have allowance for ``from``'s tokens of at least
* `amount`.
*/
function transferFrom(
address from,
address to,
uint256 amount
) public virtual override returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, amount);
_transfer(from, to, amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, _allowances[owner][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
address owner = _msgSender();
uint256 currentAllowance = _allowances[owner][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(owner, spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
*/
function _transfer(
address from,
address to,
uint256 amount
) internal virtual {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(from, to, amount);
uint256 fromBalance = _balances[from];
require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[from] = fromBalance - amount;
}
_balances[to] += amount;
emit Transfer(from, to, amount);
_afterTokenTransfer(from, to, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Spend `amount` form the allowance of `owner` toward `spender`.
*
* Does not update the allowance amount in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Might emit an {Approval} event.
*/
function _spendAllowance(
address owner,
address spender,
uint256 amount
) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance != type(uint256).max) {
require(currentAllowance >= amount, "ERC20: insufficient allowance");
unchecked {
_approve(owner, spender, currentAllowance - amount);
}
}
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.8.9;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
/**
* @title Example Pegged ERC20 token
*/
contract SingleBridgeToken is ERC20, Ownable {
address public bridge;
uint8 private immutable _decimals;
event BridgeUpdated(address bridge);
modifier onlyBridge() {
require(msg.sender == bridge, "caller is not bridge");
_;
}
constructor(
string memory name_,
string memory symbol_,
uint8 decimals_,
address bridge_
) ERC20(name_, symbol_) {
_decimals = decimals_;
bridge = bridge_;
}
/**
* @notice Mints tokens to an address.
* @param _to The address to mint tokens to.
* @param _amount The amount to mint.
*/
function mint(address _to, uint256 _amount) external onlyBridge returns (bool) {
_mint(_to, _amount);
return true;
}
/**
* @notice Burns tokens for msg.sender.
* @param _amount The amount to burn.
*/
function burn(uint256 _amount) external returns (bool) {
_burn(msg.sender, _amount);
return true;
}
/**
* @notice Burns tokens from an address.
* Alternative to {burnFrom} for compatibility with some bridge implementations.
* See {_burnFrom}.
* @param _from The address to burn tokens from.
* @param _amount The amount to burn.
*/
function burn(address _from, uint256 _amount) external returns (bool) {
return _burnFrom(_from, _amount);
}
/**
* @notice Burns tokens from an address.
* See {_burnFrom}.
* @param _from The address to burn tokens from.
* @param _amount The amount to burn.
*/
function burnFrom(address _from, uint256 _amount) external returns (bool) {
return _burnFrom(_from, _amount);
}
/**
* @dev Burns tokens from an address, deducting from the caller's allowance.
* @param _from The address to burn tokens from.
* @param _amount The amount to burn.
*/
function _burnFrom(address _from, uint256 _amount) internal returns (bool) {
_spendAllowance(_from, msg.sender, _amount);
_burn(_from, _amount);
return true;
}
/**
* @notice Returns the decimals of the token.
*/
function decimals() public view virtual override returns (uint8) {
return _decimals;
}
/**
* @notice Updates the bridge address.
* @param _bridge The bridge address.
*/
function updateBridge(address _bridge) external onlyOwner {
bridge = _bridge;
emit BridgeUpdated(bridge);
}
/**
* @notice Returns the owner address. Required by BEP20.
*/
function getOwner() external view returns (address) {
return owner();
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity >=0.8.9;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
contract WETH is ERC20 {
constructor() ERC20("WETH", "WETH") {}
function deposit() external payable {
_mint(msg.sender, msg.value);
}
function withdraw(uint256 _amount) external {
_burn(msg.sender, _amount);
(bool sent, ) = msg.sender.call{value: _amount, gas: 50000}("");
require(sent, "failed to send");
}
receive() external payable {}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.8.9;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
/**
* @title A test ERC20 token.
*/
contract TestERC20 is ERC20 {
uint256 public constant INITIAL_SUPPLY = 1e28;
/**
* @dev Constructor that gives msg.sender all of the existing tokens.
*/
constructor() ERC20("TestERC20", "TERC20") {
_mint(msg.sender, INITIAL_SUPPLY);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.8.9;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "../../safeguard/Ownable.sol";
/**
* @title Example Multi-Bridge Pegged ERC20 token
*/
contract MultiBridgeToken is ERC20, Ownable {
struct Supply {
uint256 cap;
uint256 total;
}
mapping(address => Supply) public bridges; // bridge address -> supply
uint8 private immutable _decimals;
event BridgeSupplyCapUpdated(address bridge, uint256 supplyCap);
constructor(
string memory name_,
string memory symbol_,
uint8 decimals_
) ERC20(name_, symbol_) {
_decimals = decimals_;
}
/**
* @notice Mints tokens to an address. Increases total amount minted by the calling bridge.
* @param _to The address to mint tokens to.
* @param _amount The amount to mint.
*/
function mint(address _to, uint256 _amount) external returns (bool) {
Supply storage b = bridges[msg.sender];
require(b.cap > 0, "invalid caller");
b.total += _amount;
require(b.total <= b.cap, "exceeds bridge supply cap");
_mint(_to, _amount);
return true;
}
/**
* @notice Burns tokens for msg.sender.
* @param _amount The amount to burn.
*/
function burn(uint256 _amount) external returns (bool) {
_burn(msg.sender, _amount);
return true;
}
/**
* @notice Burns tokens from an address. Decreases total amount minted if called by a bridge.
* Alternative to {burnFrom} for compatibility with some bridge implementations.
* See {_burnFrom}.
* @param _from The address to burn tokens from.
* @param _amount The amount to burn.
*/
function burn(address _from, uint256 _amount) external returns (bool) {
return _burnFrom(_from, _amount);
}
/**
* @notice Burns tokens from an address. Decreases total amount minted if called by a bridge.
* See {_burnFrom}.
* @param _from The address to burn tokens from.
* @param _amount The amount to burn.
*/
function burnFrom(address _from, uint256 _amount) external returns (bool) {
return _burnFrom(_from, _amount);
}
/**
* @dev Burns tokens from an address, deducting from the caller's allowance.
* Decreases total amount minted if called by a bridge.
* @param _from The address to burn tokens from.
* @param _amount The amount to burn.
*/
function _burnFrom(address _from, uint256 _amount) internal returns (bool) {
Supply storage b = bridges[msg.sender];
if (b.cap > 0 || b.total > 0) {
// set cap to 1 would effectively disable a deprecated bridge's ability to burn
require(b.total >= _amount, "exceeds bridge minted amount");
unchecked {
b.total -= _amount;
}
}
_spendAllowance(_from, msg.sender, _amount);
_burn(_from, _amount);
return true;
}
/**
* @notice Returns the decimals of the token.
*/
function decimals() public view virtual override returns (uint8) {
return _decimals;
}
/**
* @notice Updates the supply cap for a bridge.
* @param _bridge The bridge address.
* @param _cap The new supply cap.
*/
function updateBridgeSupplyCap(address _bridge, uint256 _cap) external onlyOwner {
// cap == 0 means revoking bridge role
bridges[_bridge].cap = _cap;
emit BridgeSupplyCapUpdated(_bridge, _cap);
}
/**
* @notice Returns the owner address. Required by BEP20.
*/
function getOwner() external view returns (address) {
return owner();
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.8.9;
import "@openzeppelin/contracts/token/ERC20/extensions/draft-ERC20Permit.sol";
import "../MultiBridgeToken.sol";
/**
* @title Example Multi-Bridge Pegged ERC20Permit token
*/
contract MultiBridgeTokenPermit is ERC20Permit, MultiBridgeToken {
uint8 private immutable _decimals;
constructor(
string memory name_,
string memory symbol_,
uint8 decimals_
) MultiBridgeToken(name_, symbol_, decimals_) ERC20Permit(name_) {
_decimals = decimals_;
}
function decimals() public view override(ERC20, MultiBridgeToken) returns (uint8) {
return _decimals;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-ERC20Permit.sol)
pragma solidity ^0.8.0;
import "./draft-IERC20Permit.sol";
import "../ERC20.sol";
import "../../../utils/cryptography/draft-EIP712.sol";
import "../../../utils/cryptography/ECDSA.sol";
import "../../../utils/Counters.sol";
/**
* @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* _Available since v3.4._
*/
abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712 {
using Counters for Counters.Counter;
mapping(address => Counters.Counter) private _nonces;
// solhint-disable-next-line var-name-mixedcase
bytes32 private immutable _PERMIT_TYPEHASH =
keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
/**
* @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`.
*
* It's a good idea to use the same `name` that is defined as the ERC20 token name.
*/
constructor(string memory name) EIP712(name, "1") {}
/**
* @dev See {IERC20Permit-permit}.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public virtual override {
require(block.timestamp <= deadline, "ERC20Permit: expired deadline");
bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline));
bytes32 hash = _hashTypedDataV4(structHash);
address signer = ECDSA.recover(hash, v, r, s);
require(signer == owner, "ERC20Permit: invalid signature");
_approve(owner, spender, value);
}
/**
* @dev See {IERC20Permit-nonces}.
*/
function nonces(address owner) public view virtual override returns (uint256) {
return _nonces[owner].current();
}
/**
* @dev See {IERC20Permit-DOMAIN_SEPARATOR}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view override returns (bytes32) {
return _domainSeparatorV4();
}
/**
* @dev "Consume a nonce": return the current value and increment.
*
* _Available since v4.1._
*/
function _useNonce(address owner) internal virtual returns (uint256 current) {
Counters.Counter storage nonce = _nonces[owner];
current = nonce.current();
nonce.increment();
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/cryptography/draft-EIP712.sol)
pragma solidity ^0.8.0;
import "./ECDSA.sol";
/**
* @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
*
* The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
* thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
* they need in their contracts using a combination of `abi.encode` and `keccak256`.
*
* This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
* scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
* ({_hashTypedDataV4}).
*
* The implementation of the domain separator was designed to be as efficient as possible while still properly updating
* the chain id to protect against replay attacks on an eventual fork of the chain.
*
* NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
* https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
*
* _Available since v3.4._
*/
abstract contract EIP712 {
/* solhint-disable var-name-mixedcase */
// Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to
// invalidate the cached domain separator if the chain id changes.
bytes32 private immutable _CACHED_DOMAIN_SEPARATOR;
uint256 private immutable _CACHED_CHAIN_ID;
address private immutable _CACHED_THIS;
bytes32 private immutable _HASHED_NAME;
bytes32 private immutable _HASHED_VERSION;
bytes32 private immutable _TYPE_HASH;
/* solhint-enable var-name-mixedcase */
/**
* @dev Initializes the domain separator and parameter caches.
*
* The meaning of `name` and `version` is specified in
* https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
*
* - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
* - `version`: the current major version of the signing domain.
*
* NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
* contract upgrade].
*/
constructor(string memory name, string memory version) {
bytes32 hashedName = keccak256(bytes(name));
bytes32 hashedVersion = keccak256(bytes(version));
bytes32 typeHash = keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
);
_HASHED_NAME = hashedName;
_HASHED_VERSION = hashedVersion;
_CACHED_CHAIN_ID = block.chainid;
_CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion);
_CACHED_THIS = address(this);
_TYPE_HASH = typeHash;
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view returns (bytes32) {
if (address(this) == _CACHED_THIS && block.chainid == _CACHED_CHAIN_ID) {
return _CACHED_DOMAIN_SEPARATOR;
} else {
return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION);
}
}
function _buildDomainSeparator(
bytes32 typeHash,
bytes32 nameHash,
bytes32 versionHash
) private view returns (bytes32) {
return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this)));
}
/**
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
* function returns the hash of the fully encoded EIP712 message for this domain.
*
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
*
* ```solidity
* bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
* keccak256("Mail(address to,string contents)"),
* mailTo,
* keccak256(bytes(mailContents))
* )));
* address signer = ECDSA.recover(digest, signature);
* ```
*/
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.8.9;
import "@openzeppelin/contracts/token/ERC20/extensions/draft-ERC20Permit.sol";
import "../SingleBridgeToken.sol";
/**
* @title Example Pegged ERC20Permit token
*/
contract SingleBridgeTokenPermit is ERC20Permit, SingleBridgeToken {
uint8 private immutable _decimals;
constructor(
string memory name_,
string memory symbol_,
uint8 decimals_,
address bridge_
) SingleBridgeToken(name_, symbol_, decimals_, bridge_) ERC20Permit(name_) {
_decimals = decimals_;
}
function decimals() public view override(ERC20, SingleBridgeToken) returns (uint8) {
return _decimals;
}
}
// 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 v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/extensions/ERC20Burnable.sol)
pragma solidity ^0.8.0;
import "../ERC20.sol";
import "../../../utils/Context.sol";
/**
* @dev Extension of {ERC20} that allows token holders to destroy both their own
* tokens and those that they have an allowance for, in a way that can be
* recognized off-chain (via event analysis).
*/
abstract contract ERC20Burnable is Context, ERC20 {
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public virtual {
_burn(_msgSender(), amount);
}
/**
* @dev Destroys `amount` tokens from `account`, deducting from the caller's
* allowance.
*
* See {ERC20-_burn} and {ERC20-allowance}.
*
* Requirements:
*
* - the caller must have allowance for ``accounts``'s tokens of at least
* `amount`.
*/
function burnFrom(address account, uint256 amount) public virtual {
_spendAllowance(account, _msgSender(), amount);
_burn(account, amount);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.8.9;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol";
/**
* @title A mintable {ERC20} token.
*/
contract MintableERC20 is ERC20Burnable, Ownable {
uint8 private _decimals;
/**
* @dev Constructor that gives msg.sender an initial supply of tokens.
*/
constructor(
string memory name_,
string memory symbol_,
uint8 decimals_,
uint256 initialSupply_
) ERC20(name_, symbol_) {
_decimals = decimals_;
_mint(msg.sender, initialSupply_);
}
/**
* @dev Creates `amount` new tokens for `to`.
*/
function mint(address to, uint256 amount) public onlyOwner {
_mint(to, amount);
}
function decimals() public view override returns (uint8) {
return _decimals;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721URIStorage.sol)
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: GPL-3.0-only
pragma solidity 0.8.9;
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
contract PegNFT is ERC721URIStorage {
address public immutable nftBridge;
constructor(
string memory name_,
string memory symbol_,
address _nftBridge
) ERC721(name_, symbol_) {
nftBridge = _nftBridge;
}
modifier onlyNftBridge() {
require(msg.sender == nftBridge, "caller is not bridge");
_;
}
function mint(
address to,
uint256 id,
string memory uri
) external onlyNftBridge {
_mint(to, id);
_setTokenURI(id, uri);
}
function burn(uint256 id) external onlyNftBridge {
_burn(id);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.8.9;
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
import "../../safeguard/Ownable.sol";
contract OrigNFT is ERC721URIStorage, Ownable {
constructor(string memory name_, string memory symbol_) ERC721(name_, symbol_) {}
function mint(
address to,
uint256 id,
string memory uri
) external onlyOwner {
_mint(to, id);
_setTokenURI(id, uri);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.8.9;
import "../../../safeguard/Ownable.sol";
interface IMultiBridgeToken {
function updateBridgeSupplyCap(address _bridge, uint256 _cap) external;
}
// restrict multi-bridge token to effectively only have one bridge (minter)
contract RestrictedMultiBridgeTokenOwner is Ownable {
address public immutable token;
address public bridge;
constructor(address _token, address _bridge) {
token = _token;
bridge = _bridge;
}
function updateBridgeSupplyCap(uint256 _cap) external onlyOwner {
IMultiBridgeToken(token).updateBridgeSupplyCap(bridge, _cap);
}
function changeBridge(address _bridge, uint256 _cap) external onlyOwner {
// set previous bridge cap to 1 to disable mint but still allow burn
// till its total supply becomes zero
IMultiBridgeToken(token).updateBridgeSupplyCap(bridge, 1);
// set new bridge and cap
IMultiBridgeToken(token).updateBridgeSupplyCap(_bridge, _cap);
bridge = _bridge;
}
function revokeBridge(address _bridge) external onlyOwner {
// set previous bridge cap to 0 to disable both mint and burn
IMultiBridgeToken(token).updateBridgeSupplyCap(_bridge, 0);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.8.9;
import "../framework/MessageReceiverApp.sol";
import "../interfaces/IMessageBus.sol";
// interface for NFT contract, ERC721 and metadata, only funcs needed by NFTBridge
interface INFT {
function tokenURI(uint256 tokenId) external view returns (string memory);
function ownerOf(uint256 tokenId) external view returns (address owner);
// we do not support NFT that charges transfer fees
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
// impl by NFToken contract, mint an NFT with id and uri to user or burn
function mint(
address to,
uint256 id,
string memory uri
) external;
function burn(uint256 id) external;
}
/** @title NFT Bridge */
contract NFTBridge is MessageReceiverApp {
/// per dest chain id executor fee in this chain's gas token
mapping(uint64 => uint256) public destTxFee;
enum MsgType {
Mint,
Withdraw
}
struct NFTMsg {
MsgType msgType; // mint or withdraw
address user; // receiver of minted or withdrawn NFT
address nft; // NFT contract on mint/withdraw chain
uint256 id; // token ID
string uri; // tokenURI from source NFT
}
// emit in deposit or burn
event Sent(address sender, address srcNft, uint256 id, uint64 dstChid, address receiver, address dstNft);
// emit for mint or withdraw message
event Received(address receiver, address nft, uint256 id, uint64 srcChid);
constructor(address _msgBus) {
messageBus = _msgBus;
}
/**
* @notice totalFee returns gas token value to be set in user tx, includes both cbridge msg fee and executor fee on dest chain
* @dev we use _nft address for user as it's same length so same msg cost
* @param _dstChid dest chain ID
* @param _nft address of source NFT contract
* @param _id token ID to bridge (need to get accurate tokenURI length)
* @return total fee needed for user tx
*/
function totalFee(
uint64 _dstChid,
address _nft,
uint256 _id
) external view returns (uint256) {
string memory _uri = INFT(_nft).tokenURI(_id);
bytes memory message = abi.encode(NFTMsg(MsgType.Mint, _nft, _nft, _id, _uri));
return IMessageBus(messageBus).calcFee(message) + destTxFee[_dstChid];
}
// ===== called by user
/**
* @notice deposit locks user's NFT in this contract and send message to mint on dest chain
* @param _nft address of source NFT contract
* @param _id nft token ID to bridge
* @param _dstChid dest chain ID
* @param _receiver receiver address on dest chain
* @param _dstNft dest chain NFT address
* @param _dstBridge dest chain NFTBridge address, so we know what address should receive msg. we could save in map and not require this?
*/
function deposit(
address _nft,
uint256 _id,
uint64 _dstChid,
address _receiver,
address _dstNft,
address _dstBridge
) external payable {
INFT(_nft).transferFrom(msg.sender, address(this), _id);
require(INFT(_nft).ownerOf(_id) == address(this), "transfer NFT failed");
bytes memory message = abi.encode(NFTMsg(MsgType.Mint, _receiver, _dstNft, _id, INFT(_nft).tokenURI(_id)));
uint256 fee = IMessageBus(messageBus).calcFee(message);
require(msg.value >= fee + destTxFee[_dstChid], "insufficient fee");
IMessageBus(messageBus).sendMessage{value: fee}(_dstBridge, _dstChid, message);
emit Sent(msg.sender, _nft, _id, _dstChid, _receiver, _dstNft);
}
// burn to withdraw or mint on another chain, arg has backToOrig bool if dest chain is NFT's orig, set to true
// sendMessage withdraw or mint
/**
* @notice burn deletes user's NFT in nft contract and send message to withdraw or mint on dest chain
* @param _nft address of source NFT contract
* @param _id nft token ID to bridge
* @param _dstChid dest chain ID
* @param _receiver receiver address on dest chain
* @param _dstNft dest chain NFT address
* @param _dstBridge dest chain NFTBridge address, so we know what address should receive msg. we could save in map and not require this?
* @param _backToOrigin if dest chain is the original chain of this NFT, set to true
*/
function burn(
address _nft,
uint256 _id,
uint64 _dstChid,
address _receiver,
address _dstNft,
address _dstBridge,
bool _backToOrigin
) external payable {
string memory _uri = INFT(_nft).tokenURI(_id);
INFT(_nft).burn(_id);
NFTMsg memory nftMsg = NFTMsg(MsgType.Mint, _receiver, _dstNft, _id, _uri);
if (_backToOrigin) {
nftMsg.msgType = MsgType.Withdraw;
}
bytes memory message = abi.encode(nftMsg);
uint256 fee = IMessageBus(messageBus).calcFee(message);
require(msg.value >= fee + destTxFee[_dstChid], "insufficient fee");
IMessageBus(messageBus).sendMessage{value: fee}(_dstBridge, _dstChid, message);
emit Sent(msg.sender, _nft, _id, _dstChid, _receiver, _dstNft);
}
// ===== called by msgbus
function executeMessage(
address,
uint64 srcChid,
bytes memory _message,
address // executor
) external payable override onlyMessageBus returns (ExecutionStatus) {
// withdraw original locked nft back to user, or mint new nft depending on msg.type
NFTMsg memory nftMsg = abi.decode((_message), (NFTMsg));
if (nftMsg.msgType == MsgType.Mint) {
INFT(nftMsg.nft).mint(nftMsg.user, nftMsg.id, nftMsg.uri);
} else if (nftMsg.msgType == MsgType.Withdraw) {
INFT(nftMsg.nft).transferFrom(address(this), nftMsg.user, nftMsg.id);
} else {
revert("invalid message type");
}
emit Received(nftMsg.user, nftMsg.nft, nftMsg.id, srcChid);
return ExecutionStatus.Success;
}
// only owner
// set destTxFee
function setTxFee(uint64 chid, uint256 fee) external onlyOwner {
destTxFee[chid] = fee;
}
// send all gas token this contract has to owner
function claimFee() external onlyOwner {
payable(msg.sender).transfer(address(this).balance);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity >=0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./PbBridge.sol";
import "./PbPegged.sol";
import "./PbPool.sol";
import "../interfaces/IBridge.sol";
import "../interfaces/IOriginalTokenVault.sol";
import "../interfaces/IOriginalTokenVaultV2.sol";
import "../interfaces/IPeggedTokenBridge.sol";
import "../interfaces/IPeggedTokenBridgeV2.sol";
library BridgeTransferLib {
using SafeERC20 for IERC20;
enum BridgeSendType {
Null,
Liquidity,
PegDeposit,
PegBurn,
PegV2Deposit,
PegV2Burn,
PegV2BurnFrom
}
enum BridgeReceiveType {
Null,
LqRelay,
LqWithdraw,
PegMint,
PegWithdraw,
PegV2Mint,
PegV2Withdraw
}
struct ReceiveInfo {
bytes32 transferId;
address receiver;
address token;
uint256 amount;
bytes32 refid; // reference id, e.g., srcTransferId for refund
}
// ============== Internal library functions called by apps ==============
/**
* @notice Send a cross-chain transfer either via liquidity pool-based bridge or in the form of pegged mint / burn.
* @param _receiver The address of the receiver.
* @param _token The address of the token.
* @param _amount The amount of the transfer.
* @param _dstChainId The destination chain ID.
* @param _nonce A number input to guarantee uniqueness of transferId. Can be timestamp in practice.
* @param _maxSlippage The max slippage accepted, given as percentage in point (pip). Eg. 5000 means 0.5%.
* Must be greater than minimalMaxSlippage. Receiver is guaranteed to receive at least
* (100% - max slippage percentage) * amount or the transfer can be refunded.
* Only applicable to the {BridgeSendType.Liquidity}.
* @param _bridgeSendType The type of the bridge used by this transfer. One of the {BridgeSendType} enum.
* @param _bridgeAddr The address of the bridge used.
*/
function sendTransfer(
address _receiver,
address _token,
uint256 _amount,
uint64 _dstChainId,
uint64 _nonce,
uint32 _maxSlippage, // slippage * 1M, eg. 0.5% -> 5000
BridgeSendType _bridgeSendType,
address _bridgeAddr
) internal returns (bytes32) {
bytes32 transferId;
IERC20(_token).safeIncreaseAllowance(_bridgeAddr, _amount);
if (_bridgeSendType == BridgeSendType.Liquidity) {
IBridge(_bridgeAddr).send(_receiver, _token, _amount, _dstChainId, _nonce, _maxSlippage);
transferId = keccak256(
abi.encodePacked(address(this), _receiver, _token, _amount, _dstChainId, _nonce, uint64(block.chainid))
);
} else if (_bridgeSendType == BridgeSendType.PegDeposit) {
IOriginalTokenVault(_bridgeAddr).deposit(_token, _amount, _dstChainId, _receiver, _nonce);
transferId = keccak256(
abi.encodePacked(address(this), _token, _amount, _dstChainId, _receiver, _nonce, uint64(block.chainid))
);
} else if (_bridgeSendType == BridgeSendType.PegBurn) {
IPeggedTokenBridge(_bridgeAddr).burn(_token, _amount, _receiver, _nonce);
transferId = keccak256(
abi.encodePacked(address(this), _token, _amount, _receiver, _nonce, uint64(block.chainid))
);
// handle cases where certain tokens do not spend allowance for role-based burn
IERC20(_token).safeApprove(_bridgeAddr, 0);
} else if (_bridgeSendType == BridgeSendType.PegV2Deposit) {
transferId = IOriginalTokenVaultV2(_bridgeAddr).deposit(_token, _amount, _dstChainId, _receiver, _nonce);
} else if (_bridgeSendType == BridgeSendType.PegV2Burn) {
transferId = IPeggedTokenBridgeV2(_bridgeAddr).burn(_token, _amount, _dstChainId, _receiver, _nonce);
// handle cases where certain tokens do not spend allowance for role-based burn
IERC20(_token).safeApprove(_bridgeAddr, 0);
} else if (_bridgeSendType == BridgeSendType.PegV2BurnFrom) {
transferId = IPeggedTokenBridgeV2(_bridgeAddr).burnFrom(_token, _amount, _dstChainId, _receiver, _nonce);
// handle cases where certain tokens do not spend allowance for role-based burn
IERC20(_token).safeApprove(_bridgeAddr, 0);
} else {
revert("bridge send type not supported");
}
return transferId;
}
/**
* @notice Receive a cross-chain transfer.
* @param _request The serialized request protobuf.
* @param _sigs The list of signatures sorted by signing addresses in ascending order.
* @param _signers The sorted list of signers.
* @param _powers The signing powers of the signers.
* @param _bridgeReceiveType The type of the received transfer. One of the {BridgeReceiveType} enum.
* @param _bridgeAddr The address of the bridge used.
*/
function receiveTransfer(
bytes calldata _request,
bytes[] calldata _sigs,
address[] calldata _signers,
uint256[] calldata _powers,
BridgeReceiveType _bridgeReceiveType,
address _bridgeAddr
) internal returns (ReceiveInfo memory) {
if (_bridgeReceiveType == BridgeReceiveType.LqRelay) {
return receiveLiquidityRelay(_request, _sigs, _signers, _powers, _bridgeAddr);
} else if (_bridgeReceiveType == BridgeReceiveType.LqWithdraw) {
return receiveLiquidityWithdraw(_request, _sigs, _signers, _powers, _bridgeAddr);
} else if (_bridgeReceiveType == BridgeReceiveType.PegWithdraw) {
return receivePegWithdraw(_request, _sigs, _signers, _powers, _bridgeAddr);
} else if (_bridgeReceiveType == BridgeReceiveType.PegMint) {
return receivePegMint(_request, _sigs, _signers, _powers, _bridgeAddr);
} else if (_bridgeReceiveType == BridgeReceiveType.PegV2Withdraw) {
return receivePegV2Withdraw(_request, _sigs, _signers, _powers, _bridgeAddr);
} else if (_bridgeReceiveType == BridgeReceiveType.PegV2Mint) {
return receivePegV2Mint(_request, _sigs, _signers, _powers, _bridgeAddr);
} else {
revert("bridge receive type not supported");
}
}
/**
* @notice Receive a liquidity bridge relay.
* @param _request The serialized request protobuf.
* @param _sigs The list of signatures sorted by signing addresses in ascending order.
* @param _signers The sorted list of signers.
* @param _powers The signing powers of the signers.
* @param _bridgeAddr The address of liquidity bridge.
*/
function receiveLiquidityRelay(
bytes calldata _request,
bytes[] calldata _sigs,
address[] calldata _signers,
uint256[] calldata _powers,
address _bridgeAddr
) internal returns (ReceiveInfo memory) {
ReceiveInfo memory recv;
PbBridge.Relay memory request = PbBridge.decRelay(_request);
recv.transferId = keccak256(
abi.encodePacked(
request.sender,
request.receiver,
request.token,
request.amount,
request.srcChainId,
uint64(block.chainid),
request.srcTransferId
)
);
recv.refid = request.srcTransferId;
recv.receiver = request.receiver;
recv.token = request.token;
recv.amount = request.amount;
if (!IBridge(_bridgeAddr).transfers(recv.transferId)) {
IBridge(_bridgeAddr).relay(_request, _sigs, _signers, _powers);
}
return recv;
}
/**
* @notice Receive a liquidity bridge withdrawal.
* @param _request The serialized request protobuf.
* @param _sigs The list of signatures sorted by signing addresses in ascending order.
* @param _signers The sorted list of signers.
* @param _powers The signing powers of the signers.
* @param _bridgeAddr The address of liquidity bridge.
*/
function receiveLiquidityWithdraw(
bytes calldata _request,
bytes[] calldata _sigs,
address[] calldata _signers,
uint256[] calldata _powers,
address _bridgeAddr
) internal returns (ReceiveInfo memory) {
ReceiveInfo memory recv;
PbPool.WithdrawMsg memory request = PbPool.decWithdrawMsg(_request);
recv.transferId = keccak256(
abi.encodePacked(request.chainid, request.seqnum, request.receiver, request.token, request.amount)
);
recv.refid = request.refid;
recv.receiver = request.receiver;
recv.token = request.token;
recv.amount = request.amount;
if (!IBridge(_bridgeAddr).withdraws(recv.transferId)) {
IBridge(_bridgeAddr).withdraw(_request, _sigs, _signers, _powers);
}
return recv;
}
/**
* @notice Receive an OriginalTokenVault withdrawal.
* @param _request The serialized request protobuf.
* @param _sigs The list of signatures sorted by signing addresses in ascending order.
* @param _signers The sorted list of signers.
* @param _powers The signing powers of the signers.
* @param _bridgeAddr The address of OriginalTokenVault.
*/
function receivePegWithdraw(
bytes calldata _request,
bytes[] calldata _sigs,
address[] calldata _signers,
uint256[] calldata _powers,
address _bridgeAddr
) internal returns (ReceiveInfo memory) {
ReceiveInfo memory recv;
PbPegged.Withdraw memory request = PbPegged.decWithdraw(_request);
recv.transferId = keccak256(
abi.encodePacked(
request.receiver,
request.token,
request.amount,
request.burnAccount,
request.refChainId,
request.refId
)
);
recv.refid = request.refId;
recv.receiver = request.receiver;
recv.token = request.token;
recv.amount = request.amount;
if (!IOriginalTokenVault(_bridgeAddr).records(recv.transferId)) {
IOriginalTokenVault(_bridgeAddr).withdraw(_request, _sigs, _signers, _powers);
}
return recv;
}
/**
* @notice Receive a PeggedTokenBridge mint.
* @param _request The serialized request protobuf.
* @param _sigs The list of signatures sorted by signing addresses in ascending order.
* @param _signers The sorted list of signers.
* @param _powers The signing powers of the signers.
* @param _bridgeAddr The address of PeggedTokenBridge.
*/
function receivePegMint(
bytes calldata _request,
bytes[] calldata _sigs,
address[] calldata _signers,
uint256[] calldata _powers,
address _bridgeAddr
) internal returns (ReceiveInfo memory) {
ReceiveInfo memory recv;
PbPegged.Mint memory request = PbPegged.decMint(_request);
recv.transferId = keccak256(
abi.encodePacked(
request.account,
request.token,
request.amount,
request.depositor,
request.refChainId,
request.refId
)
);
recv.refid = request.refId;
recv.receiver = request.account;
recv.token = request.token;
recv.amount = request.amount;
if (!IPeggedTokenBridge(_bridgeAddr).records(recv.transferId)) {
IPeggedTokenBridge(_bridgeAddr).mint(_request, _sigs, _signers, _powers);
}
return recv;
}
/**
* @notice Receive an OriginalTokenVaultV2 withdrawal.
* @param _request The serialized request protobuf.
* @param _sigs The list of signatures sorted by signing addresses in ascending order. A request must be signed-off by
* +2/3 of the bridge's current signing power to be delivered.
* @param _signers The sorted list of signers.
* @param _powers The signing powers of the signers.
* @param _bridgeAddr The address of OriginalTokenVaultV2.
*/
function receivePegV2Withdraw(
bytes calldata _request,
bytes[] calldata _sigs,
address[] calldata _signers,
uint256[] calldata _powers,
address _bridgeAddr
) internal returns (ReceiveInfo memory) {
ReceiveInfo memory recv;
PbPegged.Withdraw memory request = PbPegged.decWithdraw(_request);
if (IOriginalTokenVaultV2(_bridgeAddr).records(request.refId)) {
recv.transferId = keccak256(
abi.encodePacked(
request.receiver,
request.token,
request.amount,
request.burnAccount,
request.refChainId,
request.refId,
_bridgeAddr
)
);
} else {
recv.transferId = IOriginalTokenVaultV2(_bridgeAddr).withdraw(_request, _sigs, _signers, _powers);
}
recv.refid = request.refId;
recv.receiver = request.receiver;
recv.token = request.token;
recv.amount = request.amount;
return recv;
}
/**
* @notice Receive a PeggedTokenBridgeV2 mint.
* @param _request The serialized request protobuf.
* @param _sigs The list of signatures sorted by signing addresses in ascending order. A request must be signed-off by
* +2/3 of the bridge's current signing power to be delivered.
* @param _signers The sorted list of signers.
* @param _powers The signing powers of the signers.
* @param _bridgeAddr The address of PeggedTokenBridgeV2.
*/
function receivePegV2Mint(
bytes calldata _request,
bytes[] calldata _sigs,
address[] calldata _signers,
uint256[] calldata _powers,
address _bridgeAddr
) internal returns (ReceiveInfo memory) {
ReceiveInfo memory recv;
PbPegged.Mint memory request = PbPegged.decMint(_request);
if (IPeggedTokenBridgeV2(_bridgeAddr).records(request.refId)) {
recv.transferId = keccak256(
abi.encodePacked(
request.account,
request.token,
request.amount,
request.depositor,
request.refChainId,
request.refId,
_bridgeAddr
)
);
} else {
recv.transferId = IPeggedTokenBridgeV2(_bridgeAddr).mint(_request, _sigs, _signers, _powers);
}
recv.refid = request.refId;
recv.receiver = request.account;
recv.token = request.token;
recv.amount = request.amount;
return recv;
}
function bridgeRefundType(BridgeSendType _bridgeSendType) internal pure returns (BridgeReceiveType) {
if (_bridgeSendType == BridgeSendType.Liquidity) {
return BridgeReceiveType.LqWithdraw;
}
if (_bridgeSendType == BridgeSendType.PegDeposit) {
return BridgeReceiveType.PegWithdraw;
}
if (_bridgeSendType == BridgeSendType.PegBurn) {
return BridgeReceiveType.PegMint;
}
if (_bridgeSendType == BridgeSendType.PegV2Deposit) {
return BridgeReceiveType.PegV2Withdraw;
}
if (_bridgeSendType == BridgeSendType.PegV2Burn || _bridgeSendType == BridgeSendType.PegV2BurnFrom) {
return BridgeReceiveType.PegV2Mint;
}
return BridgeReceiveType.Null;
}
}
// SPDX-License-Identifier: GPL-3.0-only
// Code generated by protoc-gen-sol. DO NOT EDIT.
// source: bridge.proto
pragma solidity 0.8.9;
import "./Pb.sol";
library PbBridge {
using Pb for Pb.Buffer; // so we can call Pb funcs on Buffer obj
struct Relay {
address sender; // tag: 1
address receiver; // tag: 2
address token; // tag: 3
uint256 amount; // tag: 4
uint64 srcChainId; // tag: 5
uint64 dstChainId; // tag: 6
bytes32 srcTransferId; // tag: 7
} // end struct Relay
function decRelay(bytes memory raw) internal pure returns (Relay memory m) {
Pb.Buffer memory buf = Pb.fromBytes(raw);
uint256 tag;
Pb.WireType wire;
while (buf.hasMore()) {
(tag, wire) = buf.decKey();
if (false) {}
// solidity has no switch/case
else if (tag == 1) {
m.sender = Pb._address(buf.decBytes());
} else if (tag == 2) {
m.receiver = Pb._address(buf.decBytes());
} else if (tag == 3) {
m.token = Pb._address(buf.decBytes());
} else if (tag == 4) {
m.amount = Pb._uint256(buf.decBytes());
} else if (tag == 5) {
m.srcChainId = uint64(buf.decVarint());
} else if (tag == 6) {
m.dstChainId = uint64(buf.decVarint());
} else if (tag == 7) {
m.srcTransferId = Pb._bytes32(buf.decBytes());
} else {
buf.skipValue(wire);
} // skip value of unknown tag
}
} // end decoder Relay
}
// SPDX-License-Identifier: GPL-3.0-only
// Code generated by protoc-gen-sol. DO NOT EDIT.
// source: contracts/libraries/proto/pool.proto
pragma solidity 0.8.9;
import "./Pb.sol";
library PbPool {
using Pb for Pb.Buffer; // so we can call Pb funcs on Buffer obj
struct WithdrawMsg {
uint64 chainid; // tag: 1
uint64 seqnum; // tag: 2
address receiver; // tag: 3
address token; // tag: 4
uint256 amount; // tag: 5
bytes32 refid; // tag: 6
} // end struct WithdrawMsg
function decWithdrawMsg(bytes memory raw) internal pure returns (WithdrawMsg memory m) {
Pb.Buffer memory buf = Pb.fromBytes(raw);
uint256 tag;
Pb.WireType wire;
while (buf.hasMore()) {
(tag, wire) = buf.decKey();
if (false) {}
// solidity has no switch/case
else if (tag == 1) {
m.chainid = uint64(buf.decVarint());
} else if (tag == 2) {
m.seqnum = uint64(buf.decVarint());
} else if (tag == 3) {
m.receiver = Pb._address(buf.decBytes());
} else if (tag == 4) {
m.token = Pb._address(buf.decBytes());
} else if (tag == 5) {
m.amount = Pb._uint256(buf.decBytes());
} else if (tag == 6) {
m.refid = Pb._bytes32(buf.decBytes());
} else {
buf.skipValue(wire);
} // skip value of unknown tag
}
} // end decoder WithdrawMsg
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.8.9;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "../interfaces/IWETH.sol";
import "../libraries/PbPool.sol";
import "../safeguard/Pauser.sol";
import "../safeguard/VolumeControl.sol";
import "../safeguard/DelayedTransfer.sol";
import "./Signers.sol";
/**
* @title Liquidity pool functions for {Bridge}.
*/
contract Pool is Signers, ReentrancyGuard, Pauser, VolumeControl, DelayedTransfer {
using SafeERC20 for IERC20;
uint64 public addseq; // ensure unique LiquidityAdded event, start from 1
mapping(address => uint256) public minAdd; // add _amount must > minAdd
// map of successful withdraws, if true means already withdrew money or added to delayedTransfers
mapping(bytes32 => bool) public withdraws;
// erc20 wrap of gas token of this chain, eg. WETH, when relay ie. pay out,
// if request.token equals this, will withdraw and send native token to receiver
// note we don't check whether it's zero address. when this isn't set, and request.token
// is all 0 address, guarantee fail
address public nativeWrap;
// liquidity events
event LiquidityAdded(
uint64 seqnum,
address provider,
address token,
uint256 amount // how many tokens were added
);
event WithdrawDone(
bytes32 withdrawId,
uint64 seqnum,
address receiver,
address token,
uint256 amount,
bytes32 refid
);
event MinAddUpdated(address token, uint256 amount);
/**
* @notice Add liquidity to the pool-based bridge.
* NOTE: This function DOES NOT SUPPORT fee-on-transfer / rebasing tokens.
* NOTE: ONLY call this from an EOA. DO NOT call from a contract address.
* @param _token The address of the token.
* @param _amount The amount to add.
*/
function addLiquidity(address _token, uint256 _amount) external nonReentrant whenNotPaused {
require(_amount > minAdd[_token], "amount too small");
addseq += 1;
IERC20(_token).safeTransferFrom(msg.sender, address(this), _amount);
emit LiquidityAdded(addseq, msg.sender, _token, _amount);
}
/**
* @notice Add native token liquidity to the pool-based bridge.
* NOTE: ONLY call this from an EOA. DO NOT call from a contract address.
* @param _amount The amount to add.
*/
function addNativeLiquidity(uint256 _amount) external payable nonReentrant whenNotPaused {
require(msg.value == _amount, "Amount mismatch");
require(nativeWrap != address(0), "Native wrap not set");
require(_amount > minAdd[nativeWrap], "amount too small");
addseq += 1;
IWETH(nativeWrap).deposit{value: _amount}();
emit LiquidityAdded(addseq, msg.sender, nativeWrap, _amount);
}
/**
* @notice Withdraw funds from the bridge pool.
* @param _wdmsg The serialized Withdraw protobuf.
* @param _sigs The list of signatures sorted by signing addresses in ascending order. A withdrawal must be
* signed-off by +2/3 of the bridge's current signing power to be delivered.
* @param _signers The sorted list of signers.
* @param _powers The signing powers of the signers.
*/
function withdraw(
bytes calldata _wdmsg,
bytes[] calldata _sigs,
address[] calldata _signers,
uint256[] calldata _powers
) external whenNotPaused {
bytes32 domain = keccak256(abi.encodePacked(block.chainid, address(this), "WithdrawMsg"));
verifySigs(abi.encodePacked(domain, _wdmsg), _sigs, _signers, _powers);
// decode and check wdmsg
PbPool.WithdrawMsg memory wdmsg = PbPool.decWithdrawMsg(_wdmsg);
// len = 8 + 8 + 20 + 20 + 32 = 88
bytes32 wdId = keccak256(
abi.encodePacked(wdmsg.chainid, wdmsg.seqnum, wdmsg.receiver, wdmsg.token, wdmsg.amount)
);
require(withdraws[wdId] == false, "withdraw already succeeded");
withdraws[wdId] = true;
_updateVolume(wdmsg.token, wdmsg.amount);
uint256 delayThreshold = delayThresholds[wdmsg.token];
if (delayThreshold > 0 && wdmsg.amount > delayThreshold) {
_addDelayedTransfer(wdId, wdmsg.receiver, wdmsg.token, wdmsg.amount);
} else {
_sendToken(wdmsg.receiver, wdmsg.token, wdmsg.amount);
}
emit WithdrawDone(wdId, wdmsg.seqnum, wdmsg.receiver, wdmsg.token, wdmsg.amount, wdmsg.refid);
}
function executeDelayedTransfer(bytes32 id) external whenNotPaused {
delayedTransfer memory transfer = _executeDelayedTransfer(id);
_sendToken(transfer.receiver, transfer.token, transfer.amount);
}
function setMinAdd(address[] calldata _tokens, uint256[] calldata _amounts) external onlyGovernor {
require(_tokens.length == _amounts.length, "length mismatch");
for (uint256 i = 0; i < _tokens.length; i++) {
minAdd[_tokens[i]] = _amounts[i];
emit MinAddUpdated(_tokens[i], _amounts[i]);
}
}
function _sendToken(
address _receiver,
address _token,
uint256 _amount
) internal {
if (_token == nativeWrap) {
// withdraw then transfer native to receiver
IWETH(nativeWrap).withdraw(_amount);
(bool sent, ) = _receiver.call{value: _amount, gas: 50000}("");
require(sent, "failed to send native token");
} else {
IERC20(_token).safeTransfer(_receiver, _amount);
}
}
// set nativeWrap, for relay requests, if token == nativeWrap, will withdraw first then transfer native to receiver
function setWrap(address _weth) external onlyOwner {
nativeWrap = _weth;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.8.9;
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "../interfaces/ISigsVerifier.sol";
/**
* @title Multi-sig verification and management functions for {Bridge}.
*/
contract Signers is Ownable, ISigsVerifier {
using ECDSA for bytes32;
bytes32 public ssHash;
uint256 public triggerTime; // timestamp when last update was triggered
// reset can be called by the owner address for emergency recovery
uint256 public resetTime;
uint256 public noticePeriod; // advance notice period as seconds for reset
uint256 constant MAX_INT = 2**256 - 1;
event SignersUpdated(address[] _signers, uint256[] _powers);
event ResetNotification(uint256 resetTime);
/**
* @notice Verifies that a message is signed by a quorum among the signers
* The sigs must be sorted by signer addresses in ascending order.
* @param _msg signed message
* @param _sigs list of signatures sorted by signer addresses in ascending order
* @param _signers sorted list of current signers
* @param _powers powers of current signers
*/
function verifySigs(
bytes memory _msg,
bytes[] calldata _sigs,
address[] calldata _signers,
uint256[] calldata _powers
) public view override {
bytes32 h = keccak256(abi.encodePacked(_signers, _powers));
require(ssHash == h, "Mismatch current signers");
_verifySignedPowers(keccak256(_msg).toEthSignedMessageHash(), _sigs, _signers, _powers);
}
/**
* @notice Update new signers.
* @param _newSigners sorted list of new signers
* @param _curPowers powers of new signers
* @param _sigs list of signatures sorted by signer addresses in ascending order
* @param _curSigners sorted list of current signers
* @param _curPowers powers of current signers
*/
function updateSigners(
uint256 _triggerTime,
address[] calldata _newSigners,
uint256[] calldata _newPowers,
bytes[] calldata _sigs,
address[] calldata _curSigners,
uint256[] calldata _curPowers
) external {
// use trigger time for nonce protection, must be ascending
require(_triggerTime > triggerTime, "Trigger time is not increasing");
// make sure triggerTime is not too large, as it cannot be decreased once set
require(_triggerTime < block.timestamp + 3600, "Trigger time is too large");
bytes32 domain = keccak256(abi.encodePacked(block.chainid, address(this), "UpdateSigners"));
verifySigs(abi.encodePacked(domain, _triggerTime, _newSigners, _newPowers), _sigs, _curSigners, _curPowers);
_updateSigners(_newSigners, _newPowers);
triggerTime = _triggerTime;
}
/**
* @notice reset signers, only used for init setup and emergency recovery
*/
function resetSigners(address[] calldata _signers, uint256[] calldata _powers) external onlyOwner {
require(block.timestamp > resetTime, "not reach reset time");
resetTime = MAX_INT;
_updateSigners(_signers, _powers);
}
function notifyResetSigners() external onlyOwner {
resetTime = block.timestamp + noticePeriod;
emit ResetNotification(resetTime);
}
function increaseNoticePeriod(uint256 period) external onlyOwner {
require(period > noticePeriod, "notice period can only be increased");
noticePeriod = period;
}
// separate from verifySigs func to avoid "stack too deep" issue
function _verifySignedPowers(
bytes32 _hash,
bytes[] calldata _sigs,
address[] calldata _signers,
uint256[] calldata _powers
) private pure {
require(_signers.length == _powers.length, "signers and powers length not match");
uint256 totalPower; // sum of all signer.power
for (uint256 i = 0; i < _signers.length; i++) {
totalPower += _powers[i];
}
uint256 quorum = (totalPower * 2) / 3 + 1;
uint256 signedPower; // sum of signer powers who are in sigs
address prev = address(0);
uint256 index = 0;
for (uint256 i = 0; i < _sigs.length; i++) {
address signer = _hash.recover(_sigs[i]);
require(signer > prev, "signers not in ascending order");
prev = signer;
// now find match signer add its power
while (signer > _signers[index]) {
index += 1;
require(index < _signers.length, "signer not found");
}
if (signer == _signers[index]) {
signedPower += _powers[index];
}
if (signedPower >= quorum) {
// return early to save gas
return;
}
}
revert("quorum not reached");
}
function _updateSigners(address[] calldata _signers, uint256[] calldata _powers) private {
require(_signers.length == _powers.length, "signers and powers length not match");
address prev = address(0);
for (uint256 i = 0; i < _signers.length; i++) {
require(_signers[i] > prev, "New signers not in ascending order");
prev = _signers[i];
}
ssHash = keccak256(abi.encodePacked(_signers, _powers));
emit SignersUpdated(_signers, _powers);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.8.9;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "../libraries/BridgeTransferLib.sol";
import "../safeguard/Pauser.sol";
/**
* @title Example contract to send cBridge transfers. Supports the liquidity pool-based {Bridge}, the {OriginalTokenVault} for pegged
* deposit and the {PeggedTokenBridge} for pegged burn. Includes handling of refunds for failed transfers.
*/
contract ContractAsSender is ReentrancyGuard, Pauser {
using SafeERC20 for IERC20;
mapping(BridgeTransferLib.BridgeSendType => address) public bridges;
mapping(bytes32 => address) public records;
event Deposited(address depositor, address token, uint256 amount);
event BridgeUpdated(BridgeTransferLib.BridgeSendType bridgeSendType, address bridgeAddr);
/**
* @notice Send a cross-chain transfer either via liquidity pool-based bridge or in form of mint/burn.
* @param _receiver The address of the receiver.
* @param _token The address of the token.
* @param _amount The amount of the transfer.
* @param _dstChainId The destination chain ID.
* @param _nonce A number input to guarantee uniqueness of transferId. Can be timestamp in practice.
* @param _maxSlippage The max slippage accepted, given as percentage in point (pip). Eg. 5000 means 0.5%.
* Must be greater than minimalMaxSlippage. Receiver is guaranteed to receive at least
* (100% - max slippage percentage) * amount or the transfer can be refunded.
* Only applicable to the {BridgeSendType.Liquidity}.
* @param _bridgeSendType The type of bridge used by this transfer. One of the {BridgeSendType} enum.
*/
function transfer(
address _receiver,
address _token,
uint256 _amount,
uint64 _dstChainId,
uint64 _nonce,
uint32 _maxSlippage, // slippage * 1M, eg. 0.5% -> 5000
BridgeTransferLib.BridgeSendType _bridgeSendType
) external nonReentrant whenNotPaused onlyOwner returns (bytes32) {
address _bridgeAddr = bridges[_bridgeSendType];
require(_bridgeAddr != address(0), "unknown bridge type");
bytes32 transferId = BridgeTransferLib.sendTransfer(
_receiver,
_token,
_amount,
_dstChainId,
_nonce,
_maxSlippage,
_bridgeSendType,
_bridgeAddr
);
require(records[transferId] == address(0), "record exists");
records[transferId] = msg.sender;
return transferId;
}
/**
* @notice Refund a failed cross-chain transfer.
* @param _request The serialized request protobuf.
* @param _sigs The list of signatures sorted by signing addresses in ascending order.
* @param _signers The sorted list of signers.
* @param _powers The signing powers of the signers.
* @param _bridgeSendType The type of bridge used by this failed transfer. One of the {BridgeSendType} enum.
*/
function refund(
bytes calldata _request,
bytes[] calldata _sigs,
address[] calldata _signers,
uint256[] calldata _powers,
BridgeTransferLib.BridgeSendType _bridgeSendType
) external nonReentrant whenNotPaused onlyOwner returns (bytes32) {
address _bridgeAddr = bridges[_bridgeSendType];
require(_bridgeAddr != address(0), "unknown bridge type");
BridgeTransferLib.ReceiveInfo memory refundInfo = BridgeTransferLib.receiveTransfer(
_request,
_sigs,
_signers,
_powers,
BridgeTransferLib.bridgeRefundType(_bridgeSendType),
_bridgeAddr
);
require(refundInfo.receiver == address(this), "invalid refund");
address _receiver = records[refundInfo.refid];
require(_receiver != address(0), "unknown transfer id or already refunded");
delete records[refundInfo.refid];
IERC20(refundInfo.token).safeTransfer(_receiver, refundInfo.amount);
return refundInfo.transferId;
}
/**
* @notice Lock tokens.
* @param _token The deposited token address.
* @param _amount The amount to deposit.
*/
function deposit(address _token, uint256 _amount) external nonReentrant whenNotPaused onlyOwner {
IERC20(_token).safeTransferFrom(msg.sender, address(this), _amount);
emit Deposited(msg.sender, _token, _amount);
}
// ----------------------Admin operation-----------------------
function setBridgeAddress(BridgeTransferLib.BridgeSendType _bridgeSendType, address _addr) public onlyOwner {
require(_addr != address(0), "invalid address");
bridges[_bridgeSendType] = _addr;
emit BridgeUpdated(_bridgeSendType, _addr);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.8.9;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "../libraries/PbBridge.sol";
import "./Pool.sol";
/**
* @title The liquidity-pool based bridge.
*/
contract Bridge is Pool {
using SafeERC20 for IERC20;
// liquidity events
event Send(
bytes32 transferId,
address sender,
address receiver,
address token,
uint256 amount,
uint64 dstChainId,
uint64 nonce,
uint32 maxSlippage
);
event Relay(
bytes32 transferId,
address sender,
address receiver,
address token,
uint256 amount,
uint64 srcChainId,
bytes32 srcTransferId
);
// gov events
event MinSendUpdated(address token, uint256 amount);
event MaxSendUpdated(address token, uint256 amount);
mapping(bytes32 => bool) public transfers;
mapping(address => uint256) public minSend; // send _amount must > minSend
mapping(address => uint256) public maxSend;
// min allowed max slippage uint32 value is slippage * 1M, eg. 0.5% -> 5000
uint32 public minimalMaxSlippage;
/**
* @notice Send a cross-chain transfer via the liquidity pool-based bridge.
* NOTE: This function DOES NOT SUPPORT fee-on-transfer / rebasing tokens.
* @param _receiver The address of the receiver.
* @param _token The address of the token.
* @param _amount The amount of the transfer.
* @param _dstChainId The destination chain ID.
* @param _nonce A number input to guarantee uniqueness of transferId. Can be timestamp in practice.
* @param _maxSlippage The max slippage accepted, given as percentage in point (pip). Eg. 5000 means 0.5%.
* Must be greater than minimalMaxSlippage. Receiver is guaranteed to receive at least (100% - max slippage percentage) * amount or the
* transfer can be refunded.
*/
function send(
address _receiver,
address _token,
uint256 _amount,
uint64 _dstChainId,
uint64 _nonce,
uint32 _maxSlippage // slippage * 1M, eg. 0.5% -> 5000
) external nonReentrant whenNotPaused {
bytes32 transferId = _send(_receiver, _token, _amount, _dstChainId, _nonce, _maxSlippage);
IERC20(_token).safeTransferFrom(msg.sender, address(this), _amount);
emit Send(transferId, msg.sender, _receiver, _token, _amount, _dstChainId, _nonce, _maxSlippage);
}
/**
* @notice Send a cross-chain transfer via the liquidity pool-based bridge using the native token.
* @param _receiver The address of the receiver.
* @param _amount The amount of the transfer.
* @param _dstChainId The destination chain ID.
* @param _nonce A unique number. Can be timestamp in practice.
* @param _maxSlippage The max slippage accepted, given as percentage in point (pip). Eg. 5000 means 0.5%.
* Must be greater than minimalMaxSlippage. Receiver is guaranteed to receive at least (100% - max slippage percentage) * amount or the
* transfer can be refunded.
*/
function sendNative(
address _receiver,
uint256 _amount,
uint64 _dstChainId,
uint64 _nonce,
uint32 _maxSlippage
) external payable nonReentrant whenNotPaused {
require(msg.value == _amount, "Amount mismatch");
require(nativeWrap != address(0), "Native wrap not set");
bytes32 transferId = _send(_receiver, nativeWrap, _amount, _dstChainId, _nonce, _maxSlippage);
IWETH(nativeWrap).deposit{value: _amount}();
emit Send(transferId, msg.sender, _receiver, nativeWrap, _amount, _dstChainId, _nonce, _maxSlippage);
}
function _send(
address _receiver,
address _token,
uint256 _amount,
uint64 _dstChainId,
uint64 _nonce,
uint32 _maxSlippage
) private returns (bytes32) {
require(_amount > minSend[_token], "amount too small");
require(maxSend[_token] == 0 || _amount <= maxSend[_token], "amount too large");
require(_maxSlippage > minimalMaxSlippage, "max slippage too small");
bytes32 transferId = keccak256(
// uint64(block.chainid) for consistency as entire system uses uint64 for chain id
// len = 20 + 20 + 20 + 32 + 8 + 8 + 8 = 116
abi.encodePacked(msg.sender, _receiver, _token, _amount, _dstChainId, _nonce, uint64(block.chainid))
);
require(transfers[transferId] == false, "transfer exists");
transfers[transferId] = true;
return transferId;
}
/**
* @notice Relay a cross-chain transfer sent from a liquidity pool-based bridge on another chain.
* @param _relayRequest The serialized Relay protobuf.
* @param _sigs The list of signatures sorted by signing addresses in ascending order. A relay must be signed-off by
* +2/3 of the bridge's current signing power to be delivered.
* @param _signers The sorted list of signers.
* @param _powers The signing powers of the signers.
*/
function relay(
bytes calldata _relayRequest,
bytes[] calldata _sigs,
address[] calldata _signers,
uint256[] calldata _powers
) external whenNotPaused {
bytes32 domain = keccak256(abi.encodePacked(block.chainid, address(this), "Relay"));
verifySigs(abi.encodePacked(domain, _relayRequest), _sigs, _signers, _powers);
PbBridge.Relay memory request = PbBridge.decRelay(_relayRequest);
// len = 20 + 20 + 20 + 32 + 8 + 8 + 32 = 140
bytes32 transferId = keccak256(
abi.encodePacked(
request.sender,
request.receiver,
request.token,
request.amount,
request.srcChainId,
request.dstChainId,
request.srcTransferId
)
);
require(transfers[transferId] == false, "transfer exists");
transfers[transferId] = true;
_updateVolume(request.token, request.amount);
uint256 delayThreshold = delayThresholds[request.token];
if (delayThreshold > 0 && request.amount > delayThreshold) {
_addDelayedTransfer(transferId, request.receiver, request.token, request.amount);
} else {
_sendToken(request.receiver, request.token, request.amount);
}
emit Relay(
transferId,
request.sender,
request.receiver,
request.token,
request.amount,
request.srcChainId,
request.srcTransferId
);
}
function setMinSend(address[] calldata _tokens, uint256[] calldata _amounts) external onlyGovernor {
require(_tokens.length == _amounts.length, "length mismatch");
for (uint256 i = 0; i < _tokens.length; i++) {
minSend[_tokens[i]] = _amounts[i];
emit MinSendUpdated(_tokens[i], _amounts[i]);
}
}
function setMaxSend(address[] calldata _tokens, uint256[] calldata _amounts) external onlyGovernor {
require(_tokens.length == _amounts.length, "length mismatch");
for (uint256 i = 0; i < _tokens.length; i++) {
maxSend[_tokens[i]] = _amounts[i];
emit MaxSendUpdated(_tokens[i], _amounts[i]);
}
}
function setMinimalMaxSlippage(uint32 _minimalMaxSlippage) external onlyGovernor {
minimalMaxSlippage = _minimalMaxSlippage;
}
// This is needed to receive ETH when calling `IWETH.withdraw`
receive() external payable {}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.8.9;
import "../safeguard/Ownable.sol";
/**
* @title A contract to initiate withdrawal requests for contracts tha provide liquidity to {Bridge}.
*/
contract WithdrawInbox is Ownable {
// min allowed max slippage uint32 value is slippage * 1M, eg. 0.5% -> 5000
uint32 public minimalMaxSlippage;
// the period of time during which a withdrawal request is intended to be valid
uint256 public validityPeriod;
// contract LP withdrawal request
event WithdrawalRequest(
uint64 seqNum,
address sender,
address receiver,
uint64 toChain,
uint64[] fromChains,
address[] tokens,
uint32[] ratios,
uint32[] slippages,
uint256 deadline
);
constructor() {
// default validityPeriod is 2 hours
validityPeriod = 7200;
}
/**
* @notice Withdraw liquidity from the pool-based bridge.
* NOTE: Each of your withdrawal request should have different _wdSeq.
* NOTE: Tokens to withdraw within one withdrawal request should have the same symbol.
* @param _wdSeq The unique sequence number to identify this withdrawal request.
* @param _receiver The receiver address on _toChain.
* @param _toChain The chain Id to receive the withdrawn tokens.
* @param _fromChains The chain Ids to withdraw tokens.
* @param _tokens The token to withdraw on each fromChain.
* @param _ratios The withdrawal ratios of each token.
* @param _slippages The max slippages of each token for cross-chain withdraw.
*/
function withdraw(
uint64 _wdSeq,
address _receiver,
uint64 _toChain,
uint64[] calldata _fromChains,
address[] calldata _tokens,
uint32[] calldata _ratios,
uint32[] calldata _slippages
) external {
require(_fromChains.length > 0, "empty withdrawal request");
require(
_tokens.length == _fromChains.length &&
_ratios.length == _fromChains.length &&
_slippages.length == _fromChains.length,
"length mismatch"
);
for (uint256 i = 0; i < _ratios.length; i++) {
require(_ratios[i] > 0 && _ratios[i] <= 1e8, "invalid ratio");
require(_slippages[i] >= minimalMaxSlippage, "slippage too small");
}
uint256 _deadline = block.timestamp + validityPeriod;
emit WithdrawalRequest(
_wdSeq,
msg.sender,
_receiver,
_toChain,
_fromChains,
_tokens,
_ratios,
_slippages,
_deadline
);
}
// ------------------------Admin operations--------------------------
function setMinimalMaxSlippage(uint32 _minimalMaxSlippage) external onlyOwner {
minimalMaxSlippage = _minimalMaxSlippage;
}
function setValidityPeriod(uint256 _validityPeriod) external onlyOwner {
validityPeriod = _validityPeriod;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.8.9;
import "@openzeppelin/contracts/token/ERC20/extensions/draft-ERC20Permit.sol";
import "../MintSwapCanonicalToken.sol";
/**
* @title MintSwapCanonicalToke with ERC20Permit
*/
contract MintSwapCanonicalTokenPermit is ERC20Permit, MintSwapCanonicalToken {
uint8 private immutable _decimals;
constructor(
string memory name_,
string memory symbol_,
uint8 decimals_
) MintSwapCanonicalToken(name_, symbol_, decimals_) ERC20Permit(name_) {
_decimals = decimals_;
}
function decimals() public view override(ERC20, MultiBridgeToken) returns (uint8) {
return _decimals;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity >=0.8.9;
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./MultiBridgeToken.sol";
/**
* @title Canonical token that supports multi-bridge minter and multi-token swap
*/
contract MintSwapCanonicalToken is MultiBridgeToken {
using SafeERC20 for IERC20;
// bridge token address -> minted amount and cap for each bridge
mapping(address => Supply) public swapSupplies;
event TokenSwapCapUpdated(address token, uint256 cap);
constructor(
string memory name_,
string memory symbol_,
uint8 decimals_
) MultiBridgeToken(name_, symbol_, decimals_) {}
/**
* @notice msg.sender has bridge token and wants to get canonical token.
* @param _bridgeToken The intermediary token address for a particular bridge.
* @param _amount The amount.
*/
function swapBridgeForCanonical(address _bridgeToken, uint256 _amount) external returns (uint256) {
Supply storage supply = swapSupplies[_bridgeToken];
require(supply.cap > 0, "invalid bridge token");
require(supply.total + _amount < supply.cap, "exceed swap cap");
supply.total += _amount;
_mint(msg.sender, _amount);
// move bridge token from msg.sender to canonical token _amount
IERC20(_bridgeToken).safeTransferFrom(msg.sender, address(this), _amount);
return _amount;
}
/**
* @notice msg.sender has canonical token and wants to get bridge token (eg. for cross chain burn).
* @param _bridgeToken The intermediary token address for a particular bridge.
* @param _amount The amount.
*/
function swapCanonicalForBridge(address _bridgeToken, uint256 _amount) external returns (uint256) {
Supply storage supply = swapSupplies[_bridgeToken];
require(supply.cap > 0, "invalid bridge token");
supply.total -= _amount;
_burn(msg.sender, _amount);
IERC20(_bridgeToken).safeTransfer(msg.sender, _amount);
return _amount;
}
/**
* @dev Update existing bridge token swap cap or add a new bridge token with swap cap.
* Setting cap to 0 will disable the bridge token.
* @param _bridgeToken The intermediary token address for a particular bridge.
* @param _swapCap The new swap cap.
*/
function setBridgeTokenSwapCap(address _bridgeToken, uint256 _swapCap) external onlyOwner {
swapSupplies[_bridgeToken].cap = _swapCap;
emit TokenSwapCapUpdated(_bridgeToken, _swapCap);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity >=0.8.9;
import "./MintSwapCanonicalToken.sol";
/**
* @title Upgradable canonical token that supports multi-bridge minter and multi-token swap
*/
// First deploy this contract, constructor will set name, symbol and owner in contract state, but these are NOT used.
// decimal isn't saved in state because it's immutable in MultiBridgeToken and will be set in the code binary.
// Then deploy proxy contract with this contract as impl, proxy constructor will delegatecall this.init which sets name, symbol and owner in proxy contract state.
// why we need to shadow name and symbol: ERC20 only allows set them in constructor which isn't available after deploy so proxy state can't be updated.
contract MintSwapCanonicalTokenUpgradable is MintSwapCanonicalToken {
string private _name;
string private _symbol;
constructor(
string memory name_,
string memory symbol_,
uint8 decimals_
) MintSwapCanonicalToken(name_, symbol_, decimals_) {}
// only to be called by Proxy via delegatecall and will modify Proxy state
// this func has no access control because initOwner only allows delegateCall
function init(string memory name_, string memory symbol_) external {
initOwner(); // this will fail if Ownable._owner is already set
_name = name_;
_symbol = symbol_;
}
// override name, symbol and owner getters
function name() public view virtual override returns (string memory) {
return _name;
}
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.8.9;
import "./Freezable.sol";
import "../MintSwapCanonicalTokenUpgradable.sol";
/**
* @title Upgradable canonical token that supports multi-bridge minter and multi-token swap. Support freezable erc20 transfer
*/
contract MintSwapCanonicalTokenUpgradableFreezable is MintSwapCanonicalTokenUpgradable, Freezable {
string private _name;
string private _symbol;
constructor(
string memory name_,
string memory symbol_,
uint8 decimals_
) MintSwapCanonicalTokenUpgradable(name_, symbol_, decimals_) {}
// freezable related
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual override {
super._beforeTokenTransfer(from, to, amount);
require(!isFrozen(from), "ERC20Freezable: from account is frozen");
require(!isFrozen(to), "ERC20Freezable: to account is frozen");
}
function freeze(address _account) public onlyOwner {
freezes[_account] = true;
emit Frozen(_account);
}
function unfreeze(address _account) public onlyOwner {
freezes[_account] = false;
emit Unfrozen(_account);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.8.9;
abstract contract Freezable {
event Frozen(address account);
event Unfrozen(address account);
mapping(address => bool) internal freezes;
function isFrozen(address _account) public view virtual returns (bool) {
return freezes[_account];
}
modifier whenAccountNotFrozen(address _account) {
require(!isFrozen(_account), "Freezable: frozen");
_;
}
modifier whenAccountFrozen(address _account) {
require(isFrozen(_account), "Freezable: not frozen");
_;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity >=0.8.9;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
interface IMaiBridgeHub {
// send bridge token, get asset
function swapIn(address, uint256) external;
// send asset, get bridge token back
function swapOut(address, uint256) external;
// asset address
function asset() external view returns (address);
}
/**
* @title Intermediary bridge token that supports swapping with the Mai hub.
* NOTE: Mai hub is NOT the canonical token itself. The asset is set in the hub constructor.
*/
contract MaiBridgeToken is ERC20, Ownable {
using SafeERC20 for IERC20;
// The PeggedTokenBridge
address public bridge;
// Mai hub for swapping
address public immutable maihub;
// The canonical Mai token
address public immutable asset;
event BridgeUpdated(address bridge);
modifier onlyBridge() {
require(msg.sender == bridge, "caller is not bridge");
_;
}
constructor(
string memory name_,
string memory symbol_,
address bridge_,
address maihub_
) ERC20(name_, symbol_) {
bridge = bridge_;
maihub = maihub_;
asset = IMaiBridgeHub(maihub_).asset();
}
function mint(address _to, uint256 _amount) external onlyBridge returns (bool) {
_mint(address(this), _amount); // add amount to myself so swapIn can transfer amount to hub
_approve(address(this), maihub, _amount);
IMaiBridgeHub(maihub).swapIn(address(this), _amount);
// now this has canonical token, next step is to transfer to user
IERC20(asset).safeTransfer(_to, _amount);
return true;
}
function burn(address _from, uint256 _amount) external onlyBridge returns (bool) {
IERC20(asset).safeTransferFrom(_from, address(this), _amount);
IERC20(asset).safeIncreaseAllowance(address(maihub), _amount);
IMaiBridgeHub(maihub).swapOut(address(this), _amount);
_burn(address(this), _amount);
return true;
}
function updateBridge(address _bridge) external onlyOwner {
bridge = _bridge;
emit BridgeUpdated(bridge);
}
function decimals() public view virtual override returns (uint8) {
return ERC20(asset).decimals();
}
// to make compatible with BEP20
function getOwner() external view returns (address) {
return owner();
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity >=0.8.9;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
interface IFraxCanoToken {
function exchangeOldForCanonical(address, uint256) external returns (uint256);
function exchangeCanonicalForOld(address, uint256) external returns (uint256);
}
/**
* @title Intermediary bridge token that supports swapping with the canonical Frax token.
*/
contract FraxBridgeToken is ERC20, Ownable {
using SafeERC20 for IERC20;
// The PeggedTokenBridge
address public bridge;
// The canonical Frax token that supports swapping
address public immutable canonical;
event BridgeUpdated(address bridge);
modifier onlyBridge() {
require(msg.sender == bridge, "caller is not bridge");
_;
}
constructor(
string memory name_,
string memory symbol_,
address bridge_,
address canonical_
) ERC20(name_, symbol_) {
bridge = bridge_;
canonical = canonical_;
}
function mint(address _to, uint256 _amount) external onlyBridge returns (bool) {
_mint(address(this), _amount); // add amount to myself so exchangeOldForCanonical can transfer amount
_approve(address(this), canonical, _amount);
uint256 got = IFraxCanoToken(canonical).exchangeOldForCanonical(address(this), _amount);
// now this has canonical token, next step is to transfer to user
IERC20(canonical).safeTransfer(_to, got);
return true;
}
function burn(address _from, uint256 _amount) external onlyBridge returns (bool) {
IERC20(canonical).safeTransferFrom(_from, address(this), _amount);
uint256 got = IFraxCanoToken(canonical).exchangeCanonicalForOld(address(this), _amount);
_burn(address(this), got);
return true;
}
function updateBridge(address _bridge) external onlyOwner {
bridge = _bridge;
emit BridgeUpdated(bridge);
}
function decimals() public view virtual override returns (uint8) {
return ERC20(canonical).decimals();
}
// to make compatible with BEP20
function getOwner() external view returns (address) {
return owner();
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.8.9;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
contract Faucet is Ownable {
using SafeERC20 for IERC20;
uint256 public minDripBlkInterval;
mapping(address => uint256) public lastDripBlk;
/**
* @dev Sends 0.01% of each token to the caller.
* @param tokens The tokens to drip.
*/
function drip(address[] calldata tokens) public {
require(block.number - lastDripBlk[msg.sender] >= minDripBlkInterval, "too frequent");
for (uint256 i = 0; i < tokens.length; i++) {
IERC20 token = IERC20(tokens[i]);
uint256 balance = token.balanceOf(address(this));
require(balance > 0, "Faucet is empty");
token.safeTransfer(msg.sender, balance / 10000); // 0.01%
}
lastDripBlk[msg.sender] = block.number;
}
/**
* @dev Owner set minDripBlkInterval
*
* @param _interval minDripBlkInterval value
*/
function setMinDripBlkInterval(uint256 _interval) external onlyOwner {
minDripBlkInterval = _interval;
}
/**
* @dev Owner drains one type of tokens
*
* @param _asset drained asset address
* @param _amount drained asset amount
*/
function drainToken(address _asset, uint256 _amount) external onlyOwner {
IERC20(_asset).safeTransfer(msg.sender, _amount);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.8.9;
import "../framework/MessageSenderApp.sol";
import "../framework/MessageReceiverApp.sol";
/** @title Sample app to test message passing flow, not for production use */
contract BatchTransfer is MessageSenderApp, MessageReceiverApp {
using SafeERC20 for IERC20;
struct TransferRequest {
uint64 nonce;
address[] accounts;
uint256[] amounts;
address sender;
}
enum TransferStatus {
Null,
Success,
Fail
}
struct TransferReceipt {
uint64 nonce;
TransferStatus status;
}
constructor(address _messageBus) {
messageBus = _messageBus;
}
// ============== functions and states on source chain ==============
uint64 nonce;
struct BatchTransferStatus {
bytes32 h; // hash(receiver, dstChainId)
TransferStatus status;
}
mapping(uint64 => BatchTransferStatus) public status; // nonce -> BatchTransferStatus
modifier onlyEOA() {
require(msg.sender == tx.origin, "Not EOA");
_;
}
function batchTransfer(
address _receiver,
address _token,
uint256 _amount,
uint64 _dstChainId,
uint32 _maxSlippage,
MsgDataTypes.BridgeSendType _bridgeSendType,
address[] calldata _accounts,
uint256[] calldata _amounts
) external payable onlyEOA {
uint256 totalAmt;
for (uint256 i = 0; i < _amounts.length; i++) {
totalAmt += _amounts[i];
}
// commented out the slippage check below to trigger failure case for handleFailedMessageWithTransfer testing
// uint256 minRecv = _amount - (_amount * _maxSlippage) / 1e6;
// require(minRecv > totalAmt, "invalid maxSlippage");
nonce += 1;
status[nonce] = BatchTransferStatus({
h: keccak256(abi.encodePacked(_receiver, _dstChainId)),
status: TransferStatus.Null
});
IERC20(_token).safeTransferFrom(msg.sender, address(this), _amount);
bytes memory message = abi.encode(
TransferRequest({nonce: nonce, accounts: _accounts, amounts: _amounts, sender: msg.sender})
);
// MsgSenderApp util function
sendMessageWithTransfer(
_receiver,
_token,
_amount,
_dstChainId,
nonce,
_maxSlippage,
message,
_bridgeSendType,
msg.value
);
}
// called on source chain for handling of bridge failures (bad liquidity, bad slippage, etc...)
function executeMessageWithTransferRefund(
address _token,
uint256 _amount,
bytes calldata _message,
address // executor
) external payable override onlyMessageBus returns (ExecutionStatus) {
TransferRequest memory transfer = abi.decode((_message), (TransferRequest));
IERC20(_token).safeTransfer(transfer.sender, _amount);
return ExecutionStatus.Success;
}
// ============== functions on destination chain ==============
// handler function required by MsgReceiverApp
function executeMessage(
address _sender,
uint64 _srcChainId,
bytes memory _message,
address // executor
) external payable override onlyMessageBus returns (ExecutionStatus) {
TransferReceipt memory receipt = abi.decode((_message), (TransferReceipt));
require(status[receipt.nonce].h == keccak256(abi.encodePacked(_sender, _srcChainId)), "invalid message");
status[receipt.nonce].status = receipt.status;
return ExecutionStatus.Success;
}
// handler function required by MsgReceiverApp
function executeMessageWithTransfer(
address _sender,
address _token,
uint256 _amount,
uint64 _srcChainId,
bytes memory _message,
address // executor
) external payable override onlyMessageBus returns (ExecutionStatus) {
TransferRequest memory transfer = abi.decode((_message), (TransferRequest));
uint256 totalAmt;
for (uint256 i = 0; i < transfer.accounts.length; i++) {
IERC20(_token).safeTransfer(transfer.accounts[i], transfer.amounts[i]);
totalAmt += transfer.amounts[i];
}
uint256 remainder = _amount - totalAmt;
if (_amount > totalAmt) {
// transfer the remainder of the money to sender as fee for executing this transfer
IERC20(_token).safeTransfer(transfer.sender, remainder);
}
bytes memory message = abi.encode(TransferReceipt({nonce: transfer.nonce, status: TransferStatus.Success}));
// MsgSenderApp util function
sendMessage(_sender, _srcChainId, message, msg.value);
return ExecutionStatus.Success;
}
// handler function required by MsgReceiverApp
// called only if handleMessageWithTransfer above was reverted
function executeMessageWithTransferFallback(
address _sender,
address _token,
uint256 _amount,
uint64 _srcChainId,
bytes memory _message,
address // executor
) external payable override onlyMessageBus returns (ExecutionStatus) {
TransferRequest memory transfer = abi.decode((_message), (TransferRequest));
IERC20(_token).safeTransfer(transfer.sender, _amount);
bytes memory message = abi.encode(TransferReceipt({nonce: transfer.nonce, status: TransferStatus.Fail}));
sendMessage(_sender, _srcChainId, message, msg.value);
return ExecutionStatus.Success;
}
} | Deposit tokens. _token The deposited token address. _amount The amount to deposit./ | function deposit(address _token, uint256 _amount) external nonReentrant whenNotPaused onlyOwner {
IERC20(_token).safeTransferFrom(msg.sender, address(this), _amount);
emit Deposited(msg.sender, _token, _amount);
}
| 9,842,365 |
./full_match/84531/0xbb539f4827211e873868Eb4083e6dBf18c0c68c3/sources/libraries/SafeswapLibrary.sol | 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, 'SafeswapLibrary: 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);
}
}
| 11,509,004 |
./partial_match/1/0x75Be69fc0859874E722D97a7f464D402e3dCff58/sources/contracts/libraries/GridArt.sol | Get the honeycomb grid for a triangle shape. honeycomb The honeycomb data used for rendering. Get random rows from 2 to honeycomb.canvas.maxHexagonsPerLine. Determine positioning of entire grid, which is based on the longest row. Create grid based on hexagon base type. Iterate through rows - will only be north/south facing (design). Assign indexes for each hexagon. Each row has i + 1 hexagons. Iterate through rows - will only be west/east facing (design). Determine hexagons in row. First half is ascending. Second half is descending. ascending with peak, i.e. rows = 1 1 2 2 3 when rows = 5 descending with peak, i.e. rows = 2 2 1 1 when rows = 5 Assign indexes for each hexagon. Each row has i + 1 hexagons. | function getTriangleGrid(IHoneycombs.Honeycomb memory honeycomb) public pure returns (IHoneycombs.Grid memory) {
IHoneycombs.Grid memory grid;
grid.rows = uint8(Utilities.random(honeycomb.seed, "rows", honeycomb.canvas.maxHexagonsPerLine - 1) + 2);
grid.longestRowCount = grid.rows;
if (honeycomb.baseHexagon.hexagonType == uint8(HEXAGON_TYPE.POINTY)) {
grid.totalGradients = grid.rows;
for (uint8 i; i < grid.rows; ) {
for (uint8 j; j < i + 1; ) {
uint8 xIndex = grid.rows - 1 - i + (j * 2);
grid.hexagonsSvg = getUpdatedHexagonsSvg(grid, xIndex, i, i + 1);
unchecked {
++j;
}
}
unchecked {
++i;
}
}
uint8 flatTopRows = grid.rows * 2 - 1;
grid.totalGradients = flatTopRows;
for (uint8 i; i < flatTopRows; ) {
uint8 hexagonsInRow;
if (i <= flatTopRows / 2) {
hexagonsInRow = i / 2 + 1;
hexagonsInRow = ((flatTopRows - i - 1) / 2) + 1;
}
for (uint8 j; j < hexagonsInRow; ) {
uint8 xIndex = (i % 2) + (j * 2);
grid.hexagonsSvg = getUpdatedHexagonsSvg(grid, xIndex, i, i + 1);
unchecked {
++j;
}
}
unchecked {
++i;
}
}
}
return grid;
}
| 3,888,377 |
/*
* This file was generated by MyWish Platform (https://mywish.io/)
* The complete code could be found at https://github.com/MyWishPlatform/
* Copyright (C) 2018 MyWish
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
pragma solidity ^0.4.23;
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender)
public view returns (uint256);
function transferFrom(address from, address to, uint256 value)
public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
/**
* @title 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 Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale,
* allowing investors to purchase tokens with ether. This contract implements
* such functionality in its most fundamental form and can be extended to provide additional
* functionality and/or custom behavior.
* The external interface represents the basic interface for purchasing tokens, and conform
* the base architecture for crowdsales. They are *not* intended to be modified / overriden.
* The internal interface conforms the extensible and modifiable surface of crowdsales. Override
* the methods to add functionality. Consider using 'super' where appropiate to concatenate
* behavior.
*/
contract Crowdsale {
using SafeMath for uint256;
// The token being sold
ERC20 public token;
// Address where funds are collected
address public wallet;
// How many token units a buyer gets per wei.
// The rate is the conversion between wei and the smallest and indivisible token unit.
// So, if you are using a rate of 1 with a DetailedERC20 token with 3 decimals called TOK
// 1 wei will give you 1 unit, or 0.001 TOK.
uint256 public rate;
// Amount of wei raised
uint256 public weiRaised;
/**
* Event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokenPurchase(
address indexed purchaser,
address indexed beneficiary,
uint256 value,
uint256 amount
);
/**
* @param _rate Number of token units a buyer gets per wei
* @param _wallet Address where collected funds will be forwarded to
* @param _token Address of the token being sold
*/
constructor(uint256 _rate, address _wallet, ERC20 _token) public {
require(_rate > 0);
require(_wallet != address(0));
require(_token != address(0));
rate = _rate;
wallet = _wallet;
token = _token;
}
// -----------------------------------------
// Crowdsale external interface
// -----------------------------------------
/**
* @dev fallback function ***DO NOT OVERRIDE***
*/
function () external payable {
buyTokens(msg.sender);
}
/**
* @dev low level token purchase ***DO NOT OVERRIDE***
* @param _beneficiary Address performing the token purchase
*/
function buyTokens(address _beneficiary) public payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(_beneficiary, weiAmount);
// calculate token amount to be created
uint256 tokens = _getTokenAmount(weiAmount);
// update state
weiRaised = weiRaised.add(weiAmount);
_processPurchase(_beneficiary, tokens);
emit TokenPurchase(
msg.sender,
_beneficiary,
weiAmount,
tokens
);
_updatePurchasingState(_beneficiary, weiAmount);
_forwardFunds();
_postValidatePurchase(_beneficiary, weiAmount);
}
// -----------------------------------------
// Internal interface (extensible)
// -----------------------------------------
/**
* @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use super to concatenate validations.
* @param _beneficiary Address performing the token purchase
* @param _weiAmount Value in wei involved in the purchase
*/
function _preValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
{
require(_beneficiary != address(0));
require(_weiAmount != 0);
}
/**
* @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met.
* @param _beneficiary Address performing the token purchase
* @param _weiAmount Value in wei involved in the purchase
*/
function _postValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
{
// optional override
}
/**
* @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens.
* @param _beneficiary Address performing the token purchase
* @param _tokenAmount Number of tokens to be emitted
*/
function _deliverTokens(
address _beneficiary,
uint256 _tokenAmount
)
internal
{
token.transfer(_beneficiary, _tokenAmount);
}
/**
* @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens.
* @param _beneficiary Address receiving the tokens
* @param _tokenAmount Number of tokens to be purchased
*/
function _processPurchase(
address _beneficiary,
uint256 _tokenAmount
)
internal
{
_deliverTokens(_beneficiary, _tokenAmount);
}
/**
* @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.)
* @param _beneficiary Address receiving the tokens
* @param _weiAmount Value in wei involved in the purchase
*/
function _updatePurchasingState(
address _beneficiary,
uint256 _weiAmount
)
internal
{
// optional override
}
/**
* @dev Override to extend the way in which ether is converted to tokens.
* @param _weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(uint256 _weiAmount)
internal view returns (uint256)
{
return _weiAmount.mul(rate);
}
/**
* @dev Determines how ETH is stored/forwarded on purchases.
*/
function _forwardFunds() internal {
wallet.transfer(msg.value);
}
}
/**
* @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.
*/
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;
}
}
/**
* @title TimedCrowdsale
* @dev Crowdsale accepting contributions only within a time frame.
*/
contract TimedCrowdsale is Crowdsale {
using SafeMath for uint256;
uint256 public openingTime;
uint256 public closingTime;
/**
* @dev Reverts if not in crowdsale time range.
*/
modifier onlyWhileOpen {
// solium-disable-next-line security/no-block-members
require(block.timestamp >= openingTime && block.timestamp <= closingTime);
_;
}
/**
* @dev Constructor, takes crowdsale opening and closing times.
* @param _openingTime Crowdsale opening time
* @param _closingTime Crowdsale closing time
*/
constructor(uint256 _openingTime, uint256 _closingTime) public {
// solium-disable-next-line security/no-block-members
require(_openingTime >= block.timestamp);
require(_closingTime >= _openingTime);
openingTime = _openingTime;
closingTime = _closingTime;
}
/**
* @dev Checks whether the period in which the crowdsale is open has already elapsed.
* @return Whether crowdsale period has elapsed
*/
function hasClosed() public view returns (bool) {
// solium-disable-next-line security/no-block-members
return block.timestamp > closingTime;
}
/**
* @dev Extend parent behavior requiring to be within contributing period
* @param _beneficiary Token purchaser
* @param _weiAmount Amount of wei contributed
*/
function _preValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
onlyWhileOpen
{
super._preValidatePurchase(_beneficiary, _weiAmount);
}
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(
address _spender,
uint _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(
address _spender,
uint _subtractedValue
)
public
returns (bool)
{
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* @dev Issue: * https://github.com/OpenZeppelin/openzeppelin-solidity/issues/120
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
*/
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
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
)
hasMintPermission
canMint
public
returns (bool)
{
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
}
contract FreezableToken is StandardToken {
// freezing chains
mapping (bytes32 => uint64) internal chains;
// freezing amounts for each chain
mapping (bytes32 => uint) internal freezings;
// total freezing balance per address
mapping (address => uint) internal freezingBalance;
event Freezed(address indexed to, uint64 release, uint amount);
event Released(address indexed owner, uint amount);
/**
* @dev Gets the balance of the specified address include freezing tokens.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return super.balanceOf(_owner) + freezingBalance[_owner];
}
/**
* @dev Gets the balance of the specified address without freezing tokens.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function actualBalanceOf(address _owner) public view returns (uint256 balance) {
return super.balanceOf(_owner);
}
function freezingBalanceOf(address _owner) public view returns (uint256 balance) {
return freezingBalance[_owner];
}
/**
* @dev gets freezing count
* @param _addr Address of freeze tokens owner.
*/
function freezingCount(address _addr) public view returns (uint count) {
uint64 release = chains[toKey(_addr, 0)];
while (release != 0) {
count++;
release = chains[toKey(_addr, release)];
}
}
/**
* @dev gets freezing end date and freezing balance for the freezing portion specified by index.
* @param _addr Address of freeze tokens owner.
* @param _index Freezing portion index. It ordered by release date descending.
*/
function getFreezing(address _addr, uint _index) public view returns (uint64 _release, uint _balance) {
for (uint i = 0; i < _index + 1; i++) {
_release = chains[toKey(_addr, _release)];
if (_release == 0) {
return;
}
}
_balance = freezings[toKey(_addr, _release)];
}
/**
* @dev freeze your tokens to the specified address.
* Be careful, gas usage is not deterministic,
* and depends on how many freezes _to address already has.
* @param _to Address to which token will be freeze.
* @param _amount Amount of token to freeze.
* @param _until Release date, must be in future.
*/
function freezeTo(address _to, uint _amount, uint64 _until) public {
require(_to != address(0));
require(_amount <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_amount);
bytes32 currentKey = toKey(_to, _until);
freezings[currentKey] = freezings[currentKey].add(_amount);
freezingBalance[_to] = freezingBalance[_to].add(_amount);
freeze(_to, _until);
emit Transfer(msg.sender, _to, _amount);
emit Freezed(_to, _until, _amount);
}
/**
* @dev release first available freezing tokens.
*/
function releaseOnce() public {
bytes32 headKey = toKey(msg.sender, 0);
uint64 head = chains[headKey];
require(head != 0);
require(uint64(block.timestamp) > head);
bytes32 currentKey = toKey(msg.sender, head);
uint64 next = chains[currentKey];
uint amount = freezings[currentKey];
delete freezings[currentKey];
balances[msg.sender] = balances[msg.sender].add(amount);
freezingBalance[msg.sender] = freezingBalance[msg.sender].sub(amount);
if (next == 0) {
delete chains[headKey];
} else {
chains[headKey] = next;
delete chains[currentKey];
}
emit Released(msg.sender, amount);
}
/**
* @dev release all available for release freezing tokens. Gas usage is not deterministic!
* @return how many tokens was released
*/
function releaseAll() public returns (uint tokens) {
uint release;
uint balance;
(release, balance) = getFreezing(msg.sender, 0);
while (release != 0 && block.timestamp > release) {
releaseOnce();
tokens += balance;
(release, balance) = getFreezing(msg.sender, 0);
}
}
function toKey(address _addr, uint _release) internal pure returns (bytes32 result) {
// WISH masc to increase entropy
result = 0x5749534800000000000000000000000000000000000000000000000000000000;
assembly {
result := or(result, mul(_addr, 0x10000000000000000))
result := or(result, _release)
}
}
function freeze(address _to, uint64 _until) internal {
require(_until > block.timestamp);
bytes32 key = toKey(_to, _until);
bytes32 parentKey = toKey(_to, uint64(0));
uint64 next = chains[parentKey];
if (next == 0) {
chains[parentKey] = _until;
return;
}
bytes32 nextKey = toKey(_to, next);
uint parent;
while (next != 0 && _until > next) {
parent = next;
parentKey = nextKey;
next = chains[nextKey];
nextKey = toKey(_to, next);
}
if (_until == next) {
return;
}
if (next != 0) {
chains[key] = next;
}
chains[parentKey] = _until;
}
}
/**
* @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);
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
contract FreezableMintableToken is FreezableToken, MintableToken {
/**
* @dev Mint the specified amount of token to the specified address and freeze it until the specified date.
* Be careful, gas usage is not deterministic,
* and depends on how many freezes _to address already has.
* @param _to Address to which token will be freeze.
* @param _amount Amount of token to mint and freeze.
* @param _until Release date, must be in future.
* @return A boolean that indicates if the operation was successful.
*/
function mintAndFreeze(address _to, uint _amount, uint64 _until) public onlyOwner canMint returns (bool) {
totalSupply_ = totalSupply_.add(_amount);
bytes32 currentKey = toKey(_to, _until);
freezings[currentKey] = freezings[currentKey].add(_amount);
freezingBalance[_to] = freezingBalance[_to].add(_amount);
freeze(_to, _until);
emit Mint(_to, _amount);
emit Freezed(_to, _until, _amount);
emit Transfer(msg.sender, _to, _amount);
return true;
}
}
contract Consts {
uint public constant TOKEN_DECIMALS = 18;
uint8 public constant TOKEN_DECIMALS_UINT8 = 18;
uint public constant TOKEN_DECIMAL_MULTIPLIER = 10 ** TOKEN_DECIMALS;
string public constant TOKEN_NAME = "RĪX";
string public constant TOKEN_SYMBOL = "RĪX";
bool public constant PAUSED = true;
address public constant TARGET_USER = 0xAAaEEE162102491a3a27390277A0a4c61BfB7373;
uint public constant START_TIME = 1532016047;
bool public constant CONTINUE_MINTING = true;
}
/**
* @title FinalizableCrowdsale
* @dev Extension of Crowdsale where an owner can do extra work
* after finishing.
*/
contract FinalizableCrowdsale is TimedCrowdsale, Ownable {
using SafeMath for uint256;
bool public isFinalized = false;
event Finalized();
/**
* @dev Must be called after crowdsale ends, to do some extra finalization
* work. Calls the contract's finalization function.
*/
function finalize() onlyOwner public {
require(!isFinalized);
require(hasClosed());
finalization();
emit Finalized();
isFinalized = true;
}
/**
* @dev Can be overridden to add finalization logic. The overriding function
* should call super.finalization() to ensure the chain of finalization is
* executed entirely.
*/
function finalization() internal {
}
}
/**
* @title CappedCrowdsale
* @dev Crowdsale with a limit for total contributions.
*/
contract CappedCrowdsale is Crowdsale {
using SafeMath for uint256;
uint256 public cap;
/**
* @dev Constructor, takes maximum amount of wei accepted in the crowdsale.
* @param _cap Max amount of wei to be contributed
*/
constructor(uint256 _cap) public {
require(_cap > 0);
cap = _cap;
}
/**
* @dev Checks whether the cap has been reached.
* @return Whether the cap was reached
*/
function capReached() public view returns (bool) {
return weiRaised >= cap;
}
/**
* @dev Extend parent behavior requiring purchase to respect the funding cap.
* @param _beneficiary Token purchaser
* @param _weiAmount Amount of wei contributed
*/
function _preValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
{
super._preValidatePurchase(_beneficiary, _weiAmount);
require(weiRaised.add(_weiAmount) <= cap);
}
}
/**
* @title MintedCrowdsale
* @dev Extension of Crowdsale contract whose tokens are minted in each purchase.
* Token ownership should be transferred to MintedCrowdsale for minting.
*/
contract MintedCrowdsale is Crowdsale {
/**
* @dev Overrides delivery by minting tokens upon purchase.
* @param _beneficiary Token purchaser
* @param _tokenAmount Number of tokens to be minted
*/
function _deliverTokens(
address _beneficiary,
uint256 _tokenAmount
)
internal
{
require(MintableToken(token).mint(_beneficiary, _tokenAmount));
}
}
contract MainToken is Consts, FreezableMintableToken, BurnableToken, Pausable
{
function name() public pure returns (string _name) {
return TOKEN_NAME;
}
function symbol() public pure returns (string _symbol) {
return TOKEN_SYMBOL;
}
function decimals() public pure returns (uint8 _decimals) {
return TOKEN_DECIMALS_UINT8;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool _success) {
require(!paused);
return super.transferFrom(_from, _to, _value);
}
function transfer(address _to, uint256 _value) public returns (bool _success) {
require(!paused);
return super.transfer(_to, _value);
}
}
contract MainCrowdsale is Consts, FinalizableCrowdsale, MintedCrowdsale, CappedCrowdsale {
function hasStarted() public view returns (bool) {
return now >= openingTime;
}
function startTime() public view returns (uint256) {
return openingTime;
}
function endTime() public view returns (uint256) {
return closingTime;
}
function hasClosed() public view returns (bool) {
return super.hasClosed() || capReached();
}
function hasEnded() public view returns (bool) {
return hasClosed();
}
function finalization() internal {
super.finalization();
if (PAUSED) {
MainToken(token).unpause();
}
if (!CONTINUE_MINTING) {
require(MintableToken(token).finishMinting());
}
Ownable(token).transferOwnership(TARGET_USER);
}
/**
* @dev Override to extend the way in which ether is converted to tokens.
* @param _weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(uint256 _weiAmount)
internal view returns (uint256)
{
return _weiAmount.mul(rate).div(1 ether);
}
}
contract Checkable {
address private serviceAccount;
/**
* Flag means that contract accident already occurs.
*/
bool private triggered = false;
/**
* Occurs when accident happened.
*/
event Triggered(uint balance);
/**
* Occurs when check finished.
* isAccident is accident occurred
*/
event Checked(bool isAccident);
constructor() public {
serviceAccount = msg.sender;
}
/**
* @dev Replace service account with new one.
* @param _account Valid service account address.
*/
function changeServiceAccount(address _account) public onlyService {
require(_account != 0);
serviceAccount = _account;
}
/**
* @dev Is caller (sender) service account.
*/
function isServiceAccount() public view returns (bool) {
return msg.sender == serviceAccount;
}
/**
* Public check method.
*/
function check() public payable onlyService notTriggered {
if (internalCheck()) {
emit Triggered(address(this).balance);
triggered = true;
internalAction();
}
}
/**
* @dev Do inner check.
* @return bool true of accident triggered, false otherwise.
*/
function internalCheck() internal returns (bool);
/**
* @dev Do inner action if check was success.
*/
function internalAction() internal;
modifier onlyService {
require(msg.sender == serviceAccount);
_;
}
modifier notTriggered {
require(!triggered);
_;
}
}
contract BonusableCrowdsale is Consts, Crowdsale {
/**
* @dev Override to extend the way in which ether is converted to tokens.
* @param _weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(uint256 _weiAmount)
internal view returns (uint256)
{
uint256 bonusRate = getBonusRate(_weiAmount);
return _weiAmount.mul(bonusRate).div(1 ether);
}
function getBonusRate(uint256 _weiAmount) internal view returns (uint256) {
uint256 bonusRate = rate;
// apply bonus for time & weiRaised
uint[1] memory weiRaisedStartsBounds = [uint(0)];
uint[1] memory weiRaisedEndsBounds = [uint(62500000000000000000000)];
uint64[1] memory timeStartsBounds = [uint64(1532016047)];
uint64[1] memory timeEndsBounds = [uint64(1535471995)];
uint[1] memory weiRaisedAndTimeRates = [uint(500)];
for (uint i = 0; i < 1; i++) {
bool weiRaisedInBound = (weiRaisedStartsBounds[i] <= weiRaised) && (weiRaised < weiRaisedEndsBounds[i]);
bool timeInBound = (timeStartsBounds[i] <= now) && (now < timeEndsBounds[i]);
if (weiRaisedInBound && timeInBound) {
bonusRate += bonusRate * weiRaisedAndTimeRates[i] / 1000;
}
}
return bonusRate;
}
}
contract WhitelistedCrowdsale is Crowdsale, Ownable {
mapping (address => bool) private whitelist;
event WhitelistedAddressAdded(address indexed _address);
event WhitelistedAddressRemoved(address indexed _address);
/**
* @dev throws if buyer is not whitelisted.
* @param _buyer address
*/
modifier onlyIfWhitelisted(address _buyer) {
require(whitelist[_buyer]);
_;
}
/**
* @dev add single address to whitelist
*/
function addAddressToWhitelist(address _address) external onlyOwner {
whitelist[_address] = true;
emit WhitelistedAddressAdded(_address);
}
/**
* @dev add addresses to whitelist
*/
function addAddressesToWhitelist(address[] _addresses) external onlyOwner {
for (uint i = 0; i < _addresses.length; i++) {
whitelist[_addresses[i]] = true;
emit WhitelistedAddressAdded(_addresses[i]);
}
}
/**
* @dev remove single address from whitelist
*/
function removeAddressFromWhitelist(address _address) external onlyOwner {
delete whitelist[_address];
emit WhitelistedAddressRemoved(_address);
}
/**
* @dev remove addresses from whitelist
*/
function removeAddressesFromWhitelist(address[] _addresses) external onlyOwner {
for (uint i = 0; i < _addresses.length; i++) {
delete whitelist[_addresses[i]];
emit WhitelistedAddressRemoved(_addresses[i]);
}
}
/**
* @dev getter to determine if address is in whitelist
*/
function isWhitelisted(address _address) public view returns (bool) {
return whitelist[_address];
}
/**
* @dev Extend parent behavior requiring beneficiary to be in whitelist.
* @param _beneficiary Token beneficiary
* @param _weiAmount Amount of wei contributed
*/
function _preValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
onlyIfWhitelisted(_beneficiary)
{
super._preValidatePurchase(_beneficiary, _weiAmount);
}
}
contract TemplateCrowdsale is Consts, MainCrowdsale
, BonusableCrowdsale
, Checkable
, WhitelistedCrowdsale
{
event Initialized();
event TimesChanged(uint startTime, uint endTime, uint oldStartTime, uint oldEndTime);
bool public initialized = false;
constructor(MintableToken _token) public
Crowdsale(8000 * TOKEN_DECIMAL_MULTIPLIER, 0xbC5F8A2d64026248EA2C3Aef800F96fB659cf027, _token)
TimedCrowdsale(START_TIME > now ? START_TIME : now, 1535472000)
CappedCrowdsale(62500000000000000000000)
{
}
function init() public onlyOwner {
require(!initialized);
initialized = true;
if (PAUSED) {
MainToken(token).pause();
}
transferOwnership(TARGET_USER);
emit Initialized();
}
/**
* @dev override hasClosed to add minimal value logic
* @return true if remained to achieve less than minimal
*/
function hasClosed() public view returns (bool) {
bool remainValue = cap.sub(weiRaised) < 230000000000000000;
return super.hasClosed() || remainValue;
}
/**
* @dev Do inner check.
* @return bool true of accident triggered, false otherwise.
*/
function internalCheck() internal returns (bool) {
bool result = !isFinalized && hasClosed();
emit Checked(result);
return result;
}
/**
* @dev Do inner action if check was success.
*/
function internalAction() internal {
finalization();
emit Finalized();
isFinalized = true;
}
/**
* @dev override purchase validation to add extra value logic.
* @return true if sended more than minimal value
*/
function _preValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
{
require(msg.value >= 230000000000000000);
require(msg.value <= 575000000000000000000);
super._preValidatePurchase(_beneficiary, _weiAmount);
}
} | add addresses to whitelist/ | function addAddressesToWhitelist(address[] _addresses) external onlyOwner {
for (uint i = 0; i < _addresses.length; i++) {
whitelist[_addresses[i]] = true;
emit WhitelistedAddressAdded(_addresses[i]);
}
}
| 165,326 |
./partial_match/1/0x17b1FF602d824eefFcdF6546FCb87A5C6BC69aDD/sources/RaiseFactory.sol | return The address of the RaiseOperators contract./ | function getRaiseOperatorsContract() public view returns(address) {
return address(raiseOperatorsInst);
}
| 2,859,394 |
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "./libraries/PoolDepositable.sol";
import "./libraries/Tierable.sol";
import "./libraries/Suspendable.sol";
import "./libraries/PoolVestingDepositable.sol";
/** @title LockedLBToken.
* @dev PoolDepositable contract implementation with tiers
*/
contract LockedLBToken is
Initializable,
PoolDepositable,
Tierable,
Suspendable,
PoolVestingDepositable
{
/**
* @notice Initializer
* @param _depositToken: the deposited token
* @param tiersMinAmount: the tiers min amount
* @param _pauser: the address of the account granted with PAUSER_ROLE
*/
function initialize(
IERC20Upgradeable _depositToken,
uint256[] memory tiersMinAmount,
address _pauser
) external initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__AccessControl_init_unchained();
__Poolable_init_unchained();
__Depositable_init_unchained(_depositToken);
__PoolDepositable_init_unchained();
__Tierable_init_unchained(tiersMinAmount);
__Pausable_init_unchained();
__Suspendable_init_unchained(_pauser);
__PoolVestingable_init_unchained();
__PoolVestingDepositable_init_unchained();
__LockedLBToken_init_unchained();
}
function __LockedLBToken_init_unchained() internal onlyInitializing {
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
}
function _deposit(
address,
address,
uint256
)
internal
pure
override(PoolDepositable, Depositable, PoolVestingDepositable)
returns (uint256)
{
revert("LockedLBToken: Must deposit with poolIndex");
}
function _withdraw(address, uint256)
internal
pure
override(PoolDepositable, Depositable, PoolVestingDepositable)
returns (uint256)
{
revert("LockedLBToken: Must withdraw with poolIndex");
}
function _withdraw(
address,
uint256,
uint256
)
internal
pure
override(PoolDepositable, PoolVestingDepositable)
returns (uint256)
{
revert("LockedLBToken: Must withdraw with on a specific pool type");
}
/**
* @notice Deposit amount token in pool at index `poolIndex` to the sender address balance
*/
function deposit(uint256 amount, uint256 poolIndex) external whenNotPaused {
PoolDepositable._deposit(_msgSender(), _msgSender(), amount, poolIndex);
}
/**
* @notice Withdraw amount token in pool at index `poolIndex` from the sender address balance
*/
function withdraw(uint256 amount, uint256 poolIndex)
external
whenNotPaused
{
PoolDepositable._withdraw(_msgSender(), amount, poolIndex);
}
/**
* @notice Batch deposits into a vesting pool
*/
function vestingBatchDeposits(
address from,
address[] memory to,
uint256[] memory amounts,
uint256 poolIndex
) external whenNotPaused onlyRole(DEFAULT_ADMIN_ROLE) {
PoolVestingDepositable._batchDeposits(from, to, amounts, poolIndex);
}
/**
* @notice Withdraw from a vesting pool
*/
function vestingWithdraw(uint256 amount, uint256 poolIndex)
external
whenNotPaused
{
PoolVestingDepositable._withdraw(_msgSender(), amount, poolIndex);
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/utils/Initializable.sol)
pragma solidity ^0.8.0;
import "../../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since 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.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the
* initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() initializer {}
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
// If the contract is initializing we ignore whether _initialized is set in order to support multiple
// inheritance patterns, but we only do this in the context of a constructor, because in other contexts the
// contract may have been reentered.
require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} modifier, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;
pragma abicoder v2;
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol";
import "./Poolable.sol";
import "./Depositable.sol";
/** @title PoolDepositable.
@dev This contract manage pool of deposits
*/
abstract contract PoolDepositable is
Initializable,
AccessControlUpgradeable,
Poolable,
Depositable
{
using SafeMathUpgradeable for uint256;
struct UserPoolDeposit {
uint256 poolIndex; // index of the pool
uint256 amount; // amount deposited in the pool
uint256 depositDate; // date of last deposit
}
struct BatchDeposit {
address to; // destination address
uint256 amount; // amount deposited
uint256 poolIndex; // index of the pool
}
// mapping of deposits for a user
mapping(address => UserPoolDeposit[]) private _poolDeposits;
/**
* @dev Emitted when a user deposit in a pool
*/
event PoolDeposit(
address indexed from,
address indexed to,
uint256 amount,
uint256 poolIndex
);
/**
* @dev Emitted when a user withdraw from a pool
*/
event PoolWithdraw(address indexed to, uint256 amount, uint256 poolIndex);
/**
* @notice Initializer
* @param _depositToken: the deposited token
*/
function __PoolDepositable_init(IERC20Upgradeable _depositToken)
internal
onlyInitializing
{
__Context_init_unchained();
__ERC165_init_unchained();
__AccessControl_init_unchained();
__Poolable_init_unchained();
__Depositable_init_unchained(_depositToken);
__PoolDepositable_init_unchained();
}
function __PoolDepositable_init_unchained() internal onlyInitializing {}
/**
* @dev returns the index of a user's pool deposit (`UserPoolDeposit`) for the specified pool at index `poolIndex`
*/
function _indexOfPoolDeposit(address account, uint256 poolIndex)
private
view
returns (int256)
{
for (uint256 i = 0; i < _poolDeposits[account].length; i++) {
if (_poolDeposits[account][i].poolIndex == poolIndex) {
return int256(i);
}
}
return -1;
}
/**
* @dev returns the list of pool deposits for an account
*/
function poolDepositsOf(address account)
public
view
returns (UserPoolDeposit[] memory)
{
return _poolDeposits[account];
}
/**
* @dev returns the list of pool deposits for an account
*/
function poolDepositOf(address account, uint256 poolIndex)
external
view
returns (UserPoolDeposit memory poolDeposit)
{
int256 depositIndex = _indexOfPoolDeposit(account, poolIndex);
if (depositIndex > -1) {
poolDeposit = _poolDeposits[account][uint256(depositIndex)];
}
}
// block the default implementation
function _deposit(
address,
address,
uint256
) internal pure virtual override returns (uint256) {
revert("PoolDepositable: Must deposit with poolIndex");
}
// block the default implementation
function _withdraw(address, uint256)
internal
pure
virtual
override
returns (uint256)
{
revert("PoolDepositable: Must withdraw with poolIndex");
}
/**
* @dev Deposit tokens to pool at `poolIndex`
*/
function _deposit(
address from,
address to,
uint256 amount,
uint256 poolIndex
) internal virtual whenPoolOpened(poolIndex) returns (uint256) {
uint256 depositAmount = Depositable._deposit(from, to, amount);
int256 depositIndex = _indexOfPoolDeposit(to, poolIndex);
if (depositIndex > -1) {
UserPoolDeposit storage pool = _poolDeposits[to][
uint256(depositIndex)
];
pool.amount = pool.amount.add(depositAmount);
pool.depositDate = block.timestamp; // update date to last deposit
} else {
_poolDeposits[to].push(
UserPoolDeposit({
poolIndex: poolIndex,
amount: depositAmount,
depositDate: block.timestamp
})
);
}
emit PoolDeposit(from, to, amount, poolIndex);
return depositAmount;
}
/**
* @dev Withdraw tokens from a specific pool
*/
function _withdrawPoolDeposit(
address to,
uint256 amount,
UserPoolDeposit storage poolDeposit
)
private
whenUnlocked(poolDeposit.poolIndex, poolDeposit.depositDate)
returns (uint256)
{
require(
poolDeposit.amount >= amount,
"PoolDepositable: Pool deposit less than amount"
);
require(poolDeposit.amount > 0, "PoolDepositable: No deposit in pool");
uint256 withdrawAmount = Depositable._withdraw(to, amount);
poolDeposit.amount = poolDeposit.amount.sub(withdrawAmount);
emit PoolWithdraw(to, amount, poolDeposit.poolIndex);
return withdrawAmount;
}
/**
* @dev Withdraw tokens from pool at `poolIndex`
*/
function _withdraw(
address to,
uint256 amount,
uint256 poolIndex
) internal virtual returns (uint256) {
int256 depositIndex = _indexOfPoolDeposit(to, poolIndex);
require(depositIndex > -1, "PoolDepositable: Not deposited");
return
_withdrawPoolDeposit(
to,
amount,
_poolDeposits[to][uint256(depositIndex)]
);
}
/**
* @dev Batch deposits token in pools
*/
function batchDeposits(address from, BatchDeposit[] memory deposits)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
for (uint256 i = 0; i < deposits.length; i++) {
_deposit(
from,
deposits[i].to,
deposits[i].amount,
deposits[i].poolIndex
);
}
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import "./Depositable.sol";
import "../interfaces/ITierable.sol";
/** @title Tierable.
* @dev Depositable contract implementation with tiers
*/
abstract contract Tierable is
Initializable,
AccessControlUpgradeable,
Depositable,
ITierable
{
using EnumerableSet for EnumerableSet.AddressSet;
uint256[] private _tiersMinAmount;
EnumerableSet.AddressSet private _whitelist;
/**
* @dev Emitted when tiers amount are changed
*/
event TiersMinAmountChange(uint256[] amounts);
/**
* @dev Emitted when a new account is added to the whitelist
*/
event AddToWhitelist(address account);
/**
* @dev Emitted when an account is removed from the whitelist
*/
event RemoveFromWhitelist(address account);
/**
* @notice Initializer
* @param _depositToken: the deposited token
* @param tiersMinAmount: the tiers min amount
*/
function __Tierable_init(
IERC20Upgradeable _depositToken,
uint256[] memory tiersMinAmount
) internal onlyInitializing {
__Context_init_unchained();
__ERC165_init_unchained();
__AccessControl_init_unchained();
__Depositable_init_unchained(_depositToken);
__Tierable_init_unchained(tiersMinAmount);
}
function __Tierable_init_unchained(uint256[] memory tiersMinAmount)
internal
onlyInitializing
{
_tiersMinAmount = tiersMinAmount;
}
/**
* @dev Returns the index of the tier for `account`
* @notice returns -1 if the total deposit of `account` is below the first tier
*/
function tierOf(address account) public view override returns (int256) {
// set max tier
uint256 max = _tiersMinAmount.length;
// check if account in whitelist
if (_whitelist.contains(account)) {
// return max tier
return int256(max) - 1;
}
// check balance of account
uint256 balance = depositOf(account);
for (uint256 i = 0; i < max; i++) {
// return its tier
if (balance < _tiersMinAmount[i]) return int256(i) - 1;
}
// return max tier if balance more than last tiersMinAmount
return int256(max) - 1;
}
/**
* @notice update the tiers brackets
* Only callable by owners
*/
function changeTiersMinAmount(uint256[] memory tiersMinAmount)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
_tiersMinAmount = tiersMinAmount;
emit TiersMinAmountChange(_tiersMinAmount);
}
/**
* @notice returns the list of min amount per tier
*/
function getTiersMinAmount() external view returns (uint256[] memory) {
return _tiersMinAmount;
}
/**
* @notice Add new accounts to the whitelist
* Only callable by owners
*/
function addToWhitelist(address[] memory accounts)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
for (uint256 i = 0; i < accounts.length; i++) {
bool result = _whitelist.add(accounts[i]);
if (result) emit AddToWhitelist(accounts[i]);
}
}
/**
* @notice Remove an account from the whitelist
* Only callable by owners
*/
function removeFromWhitelist(address[] memory accounts)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
for (uint256 i = 0; i < accounts.length; i++) {
bool result = _whitelist.remove(accounts[i]);
if (result) emit RemoveFromWhitelist(accounts[i]);
}
}
/**
* @notice Remove accounts from whitelist
* Only callable by owners
*/
function getWhitelist()
external
view
onlyRole(DEFAULT_ADMIN_ROLE)
returns (address[] memory)
{
return _whitelist.values();
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol";
/** @title RoleBasedPausable.
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*/
abstract contract Suspendable is
Initializable,
AccessControlUpgradeable,
PausableUpgradeable
{
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
/**
* @notice Initializer
* @param _pauser: the address of the account granted with PAUSER_ROLE
*/
function __Suspendable_init(address _pauser) internal onlyInitializing {
__Context_init_unchained();
__ERC165_init_unchained();
__AccessControl_init_unchained();
__Pausable_init_unchained();
__Suspendable_init_unchained(_pauser);
}
function __Suspendable_init_unchained(address _pauser)
internal
onlyInitializing
{
_setupRole(PAUSER_ROLE, _pauser);
}
/**
* @dev Returns true if the contract is suspended/paused, and false otherwise.
*/
function suspended() public view virtual returns (bool) {
return paused();
}
/**
* @notice suspend/pause the contract.
* Only callable by members of PAUSER_ROLE
*/
function suspend() external onlyRole(PAUSER_ROLE) {
_pause();
}
/**
* @notice resume/unpause the contract.
* Only callable by members of PAUSER_ROLE
*/
function resume() external onlyRole(PAUSER_ROLE) {
_unpause();
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;
pragma abicoder v2;
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol";
import "./PoolVestingable.sol";
import "./Depositable.sol";
/** @title PoolVestingDepositable.
@dev This contract manage deposits in vesting pools
*/
abstract contract PoolVestingDepositable is
Initializable,
PoolVestingable,
Depositable
{
using SafeMathUpgradeable for uint256;
struct UserVestingPoolDeposit {
uint256 initialAmount; // initial amount deposited in the pool
uint256 withdrawnAmount; // amount already withdrawn from the pool
}
// mapping of deposits for a user
// user -> pool index -> user deposit
mapping(address => mapping(uint256 => UserVestingPoolDeposit))
private _poolDeposits;
/**
* @dev Emitted when a user deposit in a pool
*/
event VestingPoolDeposit(
address indexed from,
address indexed to,
uint256 amount,
uint256 poolIndex
);
/**
* @dev Emitted when a user withdraw from a pool
*/
event VestingPoolWithdraw(
address indexed to,
uint256 amount,
uint256 poolIndex
);
/**
* @notice Initializer
* @param _depositToken: the deposited token
*/
function __PoolVestingDepositable_init(IERC20Upgradeable _depositToken)
internal
onlyInitializing
{
__Context_init_unchained();
__ERC165_init_unchained();
__AccessControl_init_unchained();
__PoolVestingable_init_unchained();
__Depositable_init_unchained(_depositToken);
__PoolVestingDepositable_init_unchained();
}
function __PoolVestingDepositable_init_unchained()
internal
onlyInitializing
{}
/**
* @dev returns the vested amount of a pool deposit
*/
function _vestedAmountOf(address account, uint256 poolIndex)
private
view
returns (uint256 vestedAmount)
{
VestingPool memory pool = getVestingPool(poolIndex);
for (uint256 i = 0; i < pool.timestamps.length; i++) {
if (block.timestamp >= pool.timestamps[i]) {
// this schedule is reached, calculate its amount
uint256 scheduleAmount = _poolDeposits[account][poolIndex]
.initialAmount
.mul(pool.ratiosPerHundredThousand[i])
.div(100000);
// add it to vested amount
vestedAmount = vestedAmount.add(scheduleAmount);
}
}
}
/**
* @dev returns the amount that can be withdraw from a pool deposit
*/
function _withdrawableAmountOf(address account, uint256 poolIndex)
private
view
returns (uint256)
{
require(
poolIndex < vestingPoolsLength(),
"PoolVestingDepositable: Invalid poolIndex"
);
return
_vestedAmountOf(account, poolIndex).sub(
_poolDeposits[account][poolIndex].withdrawnAmount
);
}
/**
* @dev returns the list of pool deposits for an account
*/
function vestingPoolDepositOf(address account, uint256 poolIndex)
external
view
returns (UserVestingPoolDeposit memory)
{
require(
poolIndex < vestingPoolsLength(),
"PoolVestingDepositable: Invalid poolIndex"
);
return _poolDeposits[account][poolIndex];
}
/**
* @dev returns vested amount of an account for a specific pool. Public version
*/
function vestingPoolVestedAmountOf(address account, uint256 poolIndex)
external
view
returns (uint256)
{
return _vestedAmountOf(account, poolIndex);
}
/**
* @dev returns the amount that can be withdraw from a pool
*/
function vestingPoolWithdrawableAmountOf(address account, uint256 poolIndex)
external
view
returns (uint256)
{
return _withdrawableAmountOf(account, poolIndex);
}
// block the default implementation
function _deposit(
address,
address,
uint256
) internal pure virtual override returns (uint256) {
revert("PoolVestingDepositable: Must deposit with poolIndex");
}
// block the default implementation
function _withdraw(address, uint256)
internal
pure
virtual
override
returns (uint256)
{
revert("PoolVestingDepositable: Must withdraw with poolIndex");
}
/**
* @dev Deposit tokens to pool at `poolIndex`
*/
function _savePoolDeposit(
address from,
address to,
uint256 amount,
uint256 poolIndex
) private {
require(
poolIndex < vestingPoolsLength(),
"PoolVestingDepositable: Invalid poolIndex"
);
UserVestingPoolDeposit storage poolDeposit = _poolDeposits[to][
poolIndex
];
poolDeposit.initialAmount = poolDeposit.initialAmount.add(amount);
emit VestingPoolDeposit(from, to, amount, poolIndex);
}
/**
* @dev Batch deposit tokens to pool at `poolIndex`
*/
function _batchDeposits(
address from,
address[] memory to,
uint256[] memory amounts,
uint256 poolIndex
) internal virtual returns (uint256) {
require(
to.length == amounts.length,
"PoolVestingDepositable: arrays to and amounts have different length"
);
uint256 totalTransferredAmount = 0;
for (uint256 i = 0; i < amounts.length; i++) {
uint256 transferredAmount = Depositable._deposit(
from,
to[i],
amounts[i]
);
_savePoolDeposit(from, to[i], transferredAmount, poolIndex);
totalTransferredAmount = totalTransferredAmount.add(
transferredAmount
);
}
return totalTransferredAmount;
}
/**
* @dev Withdraw tokens from pool at `poolIndex`
*/
function _withdraw(
address to,
uint256 amount,
uint256 poolIndex
) internal virtual returns (uint256) {
require(
poolIndex < vestingPoolsLength(),
"PoolVestingDepositable: Invalid poolIndex"
);
UserVestingPoolDeposit storage poolDeposit = _poolDeposits[to][
poolIndex
];
uint256 withdrawableAmount = _withdrawableAmountOf(to, poolIndex);
require(
withdrawableAmount >= amount,
"PoolVestingDepositable: Withdrawable amount less than amount to withdraw"
);
require(
withdrawableAmount > 0,
"PoolVestingDepositable: No withdrawable amount to withdraw"
);
uint256 withdrawAmount = Depositable._withdraw(to, amount);
poolDeposit.withdrawnAmount = poolDeposit.withdrawnAmount.add(
withdrawAmount
);
emit VestingPoolWithdraw(to, amount, poolIndex);
return withdrawAmount;
}
uint256[50] private __gap;
}
// 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 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
// OpenZeppelin Contracts v4.4.1 (access/AccessControl.sol)
pragma solidity ^0.8.0;
import "./IAccessControlUpgradeable.sol";
import "../utils/ContextUpgradeable.sol";
import "../utils/StringsUpgradeable.sol";
import "../utils/introspection/ERC165Upgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable {
function __AccessControl_init() internal onlyInitializing {
__Context_init_unchained();
__ERC165_init_unchained();
__AccessControl_init_unchained();
}
function __AccessControl_init_unchained() internal onlyInitializing {
}
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view 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 ",
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 revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*
* NOTE: This function is deprecated in favor of {_grantRole}.
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Grants `role` to `account`.
*
* Internal function without access restriction.
*/
function _grantRole(bytes32 role, address account) internal virtual {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
/**
* @dev Revokes `role` from `account`.
*
* Internal function without access restriction.
*/
function _revokeRole(bytes32 role, address account) internal virtual {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol)
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
* now has built in overflow checking.
*/
library SafeMathUpgradeable {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;
pragma abicoder v2;
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol";
/** @title Poolable.
@dev This contract manage configuration of pools
*/
abstract contract Poolable is Initializable, AccessControlUpgradeable {
using SafeMathUpgradeable for uint256;
struct Pool {
uint256 lockDuration; // locked timespan
bool opened; // flag indicating if the pool is open
}
// pools mapping
mapping(uint256 => Pool) private _pools;
uint256 public poolsLength;
/**
* @dev Emitted when a pool is created
*/
event PoolAdded(uint256 poolIndex, Pool pool);
/**
* @dev Emitted when a pool is updated
*/
event PoolUpdated(uint256 poolIndex, Pool pool);
/**
* @dev Modifier that checks that the pool at index `poolIndex` is open
*/
modifier whenPoolOpened(uint256 poolIndex) {
require(poolIndex < poolsLength, "Poolable: Invalid poolIndex");
require(_pools[poolIndex].opened, "Poolable: Pool is closed");
_;
}
/**
* @dev Modifier that checks that the now() - `depositDate` is above or equal to the min lock duration for pool at index `poolIndex`
*/
modifier whenUnlocked(uint256 poolIndex, uint256 depositDate) {
require(poolIndex < poolsLength, "Poolable: Invalid poolIndex");
require(
depositDate < block.timestamp,
"Poolable: Invalid deposit date"
);
require(
block.timestamp - depositDate >= _pools[poolIndex].lockDuration,
"Poolable: Not unlocked"
);
_;
}
/**
* @notice Initializer
*/
function __Poolable_init() internal onlyInitializing {
__Context_init_unchained();
__ERC165_init_unchained();
__AccessControl_init_unchained();
__Poolable_init_unchained();
}
function __Poolable_init_unchained() internal onlyInitializing {}
function getPool(uint256 poolIndex) public view returns (Pool memory) {
require(poolIndex < poolsLength, "Poolable: Invalid poolIndex");
return _pools[poolIndex];
}
function addPool(Pool calldata pool) external onlyRole(DEFAULT_ADMIN_ROLE) {
uint256 poolIndex = poolsLength;
_pools[poolIndex] = Pool({
lockDuration: pool.lockDuration,
opened: pool.opened
});
poolsLength = poolsLength + 1;
emit PoolAdded(poolIndex, _pools[poolIndex]);
}
function updatePool(uint256 poolIndex, Pool calldata pool)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
require(poolIndex < poolsLength, "Poolable: Invalid poolIndex");
Pool storage editedPool = _pools[poolIndex];
editedPool.lockDuration = pool.lockDuration;
editedPool.opened = pool.opened;
emit PoolUpdated(poolIndex, editedPool);
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol";
/** @title Depositable.
@dev It is a contract that allow to deposit an ERC20 token
*/
abstract contract Depositable is Initializable, AccessControlUpgradeable {
using SafeERC20Upgradeable for IERC20Upgradeable;
using SafeMathUpgradeable for uint256;
// Map of deposits per address
mapping(address => uint256) private _deposits;
// the deposited token
IERC20Upgradeable public depositToken;
// the total amount deposited
uint256 public totalDeposit;
/**
* @dev Emitted when `amount` tokens are deposited to account (`to`)
* Note that `amount` may be zero.
*/
event Deposit(address indexed from, address indexed to, uint256 amount);
/**
* @dev Emitted when `amount` tokens are withdrawn to account (`to`)
* Note that `amount` may be zero.
*/
event Withdraw(address indexed to, uint256 amount);
/**
* @dev Emitted when the deposited token is changed by the admin
*/
event DepositTokenChange(address indexed token);
/**
* @notice Intializer
* @param _depositToken: the deposited token
*/
function __Depositable_init(IERC20Upgradeable _depositToken)
internal
onlyInitializing
{
__Context_init_unchained();
__ERC165_init_unchained();
__AccessControl_init_unchained();
__Depositable_init_unchained(_depositToken);
}
function __Depositable_init_unchained(IERC20Upgradeable _depositToken)
internal
onlyInitializing
{
depositToken = _depositToken;
}
/**
* @dev Handle the deposit (transfer) of `amount` tokens from the `from` address
* The contract must be approved to spend the tokens from the `from` address before calling this function
* @param from: the depositor address
* @param to: the credited address
* @param amount: amount of token to deposit
* @return the amount deposited
*/
function _deposit(
address from,
address to,
uint256 amount
) internal virtual returns (uint256) {
// transfer tokens and check the real amount received
uint256 balance = depositToken.balanceOf(address(this));
depositToken.safeTransferFrom(from, address(this), amount);
uint256 newBalance = depositToken.balanceOf(address(this));
// replace amount by the real transferred amount
amount = newBalance.sub(balance);
// save deposit
_deposits[to] = _deposits[to].add(amount);
totalDeposit = totalDeposit.add(amount);
emit Deposit(from, to, amount);
return amount;
}
/**
* @dev Remove `amount` tokens from the `to` address deposit balance, and transfer the tokens to the `to` address
* @param to: the destination address
* @param amount: amount of token to deposit
* @return the amount withdrawn
*/
function _withdraw(address to, uint256 amount)
internal
virtual
returns (uint256)
{
require(amount <= _deposits[to], "Depositable: amount too high");
_deposits[to] = _deposits[to].sub(amount);
totalDeposit = totalDeposit.sub(amount);
depositToken.safeTransfer(to, amount);
emit Withdraw(to, amount);
return amount;
}
/**
* @notice get the total amount deposited by an address
*/
function depositOf(address _address) public view virtual returns (uint256) {
return _deposits[_address];
}
/**
* @notice Change the deposited token
*/
function changeDepositToken(IERC20Upgradeable _depositToken)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
require(totalDeposit == 0, "Depositable: total deposit != 0");
depositToken = _depositToken;
emit DepositTokenChange(address(_depositToken));
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControlUpgradeable {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
__Context_init_unchained();
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal onlyInitializing {
__ERC165_init_unchained();
}
function __ERC165_init_unchained() internal onlyInitializing {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: 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 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
// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20Upgradeable.sol";
import "../../../utils/AddressUpgradeable.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20Upgradeable {
using AddressUpgradeable for address;
function safeTransfer(
IERC20Upgradeable token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20Upgradeable token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20Upgradeable token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20Upgradeable token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20Upgradeable 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(IERC20Upgradeable token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/structs/EnumerableSet.sol)
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
return _values(set._inner);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly {
result := store
}
return result;
}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;
/** @title ITierable contract interface.
*/
interface ITierable {
function tierOf(address account) external returns (int256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/Pausable.sol)
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal onlyInitializing {
__Context_init_unchained();
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal onlyInitializing {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;
pragma abicoder v2;
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol";
/** @title PoolVestingable.
@dev This contract manage configuration of vesting pools
*/
abstract contract PoolVestingable is Initializable, AccessControlUpgradeable {
using SafeMathUpgradeable for uint256;
struct VestingPool {
uint256[] timestamps; // Timestamp at which the associated ratio is available.
uint256[] ratiosPerHundredThousand; // Ratio of initial amount to be available at the associated timestamp in / 100,000 (100% = 100,000, 1% = 1,000)
}
// pools
VestingPool[] private _pools;
/**
* @dev Emitted when a pool is created
*/
event VestingPoolAdded(uint256 poolIndex, VestingPool pool);
/**
* @dev Emitted when a pool is updated
*/
event VestingPoolUpdated(uint256 poolIndex, VestingPool pool);
/**
* @dev Modifier that checks pool is valid
*/
modifier checkVestingPool(VestingPool calldata pool) {
// check length of timestamps and ratiosPerHundredThousand are equal
require(
pool.timestamps.length == pool.ratiosPerHundredThousand.length,
"PoolVestingable: Number of timestamps is not equal to number of ratios"
);
// check the timestamps are increasing
// start at i = 1
for (uint256 i = 1; i < pool.timestamps.length; i++) {
require(
pool.timestamps[i - 1] < pool.timestamps[i],
"PoolVestingable: Timestamps be asc ordered"
);
}
// check sum of ratios = 100,000
uint256 totalRatio = 0;
for (uint256 i = 0; i < pool.ratiosPerHundredThousand.length; i++) {
totalRatio = totalRatio.add(pool.ratiosPerHundredThousand[i]);
}
require(
totalRatio == 100000,
"PoolVestingable: Sum of ratios per thousand must be equal to 100,000"
);
_;
}
/**
* @notice Initializer
*/
function __PoolVestingable_init() internal onlyInitializing {
__Context_init_unchained();
__ERC165_init_unchained();
__AccessControl_init_unchained();
__PoolVestingable_init_unchained();
}
function __PoolVestingable_init_unchained() internal onlyInitializing {}
function getVestingPool(uint256 poolIndex)
public
view
returns (VestingPool memory)
{
require(
poolIndex < _pools.length,
"PoolVestingable: Invalid poolIndex"
);
return _pools[poolIndex];
}
function vestingPoolsLength() public view returns (uint256) {
return _pools.length;
}
function addVestingPool(VestingPool calldata pool)
external
onlyRole(DEFAULT_ADMIN_ROLE)
checkVestingPool(pool)
{
_pools.push(
VestingPool({
timestamps: pool.timestamps,
ratiosPerHundredThousand: pool.ratiosPerHundredThousand
})
);
emit VestingPoolAdded(_pools.length - 1, _pools[_pools.length - 1]);
}
function updateVestingPool(uint256 poolIndex, VestingPool calldata pool)
external
onlyRole(DEFAULT_ADMIN_ROLE)
checkVestingPool(pool)
{
require(
poolIndex < _pools.length,
"PoolVestingable: Invalid poolIndex"
);
VestingPool storage editedPool = _pools[poolIndex];
editedPool.timestamps = pool.timestamps;
editedPool.ratiosPerHundredThousand = pool.ratiosPerHundredThousand;
emit VestingPoolUpdated(poolIndex, editedPool);
}
uint256[50] private __gap;
} | Initializer/ | function __PoolVestingable_init() internal onlyInitializing {
__Context_init_unchained();
__ERC165_init_unchained();
__AccessControl_init_unchained();
__PoolVestingable_init_unchained();
}
| 11,946,042 |
./partial_match/1/0x003fE85895030cE120E954B98Dc1d96a262a9E89/sources/DEGEN.sol | remove limits after token is stable | function removeLimits() external onlyOwner returns (bool) {
limitsInEffect = false;
return true;
}
| 2,749,660 |
pragma solidity 0.5.17;
import "@openzeppelin/contracts/ownership/Ownable.sol";
import "../interfaces/Comptroller.sol";
import "../interfaces/PriceOracle.sol";
import "../interfaces/CERC20.sol";
import "../interfaces/CEther.sol";
import "../Utils.sol";
contract CompoundOrder is Utils(address(0), address(0), address(0)), Ownable {
// Constants
uint256 internal constant NEGLIGIBLE_DEBT = 100; // we don't care about debts below 10^-4 USDC (0.1 cent)
uint256 internal constant MAX_REPAY_STEPS = 3; // Max number of times we attempt to repay remaining debt
uint256 internal constant DEFAULT_LIQUIDITY_SLIPPAGE = 10 ** 12; // 1e-6 slippage for redeeming liquidity when selling order
uint256 internal constant FALLBACK_LIQUIDITY_SLIPPAGE = 10 ** 15; // 0.1% slippage for redeeming liquidity when selling order
uint256 internal constant MAX_LIQUIDITY_SLIPPAGE = 10 ** 17; // 10% max slippage for redeeming liquidity when selling order
// Contract instances
Comptroller public COMPTROLLER; // The Compound comptroller
PriceOracle public ORACLE; // The Compound price oracle
CERC20 public CUSDC; // The Compound USDC market token
address public CETH_ADDR;
// Instance variables
uint256 public stake;
uint256 public collateralAmountInUSDC;
uint256 public loanAmountInUSDC;
uint256 public cycleNumber;
uint256 public buyTime; // Timestamp for order execution
uint256 public outputAmount; // Records the total output USDC after order is sold
address public compoundTokenAddr;
bool public isSold;
bool public orderType; // True for shorting, false for longing
bool internal initialized;
constructor() public {}
function init(
address _compoundTokenAddr,
uint256 _cycleNumber,
uint256 _stake,
uint256 _collateralAmountInUSDC,
uint256 _loanAmountInUSDC,
bool _orderType,
address _usdcAddr,
address payable _kyberAddr,
address _comptrollerAddr,
address _priceOracleAddr,
address _cUSDCAddr,
address _cETHAddr
) public {
require(!initialized);
initialized = true;
// Initialize details of order
require(_compoundTokenAddr != _cUSDCAddr);
require(_stake > 0 && _collateralAmountInUSDC > 0 && _loanAmountInUSDC > 0); // Validate inputs
stake = _stake;
collateralAmountInUSDC = _collateralAmountInUSDC;
loanAmountInUSDC = _loanAmountInUSDC;
cycleNumber = _cycleNumber;
compoundTokenAddr = _compoundTokenAddr;
orderType = _orderType;
COMPTROLLER = Comptroller(_comptrollerAddr);
ORACLE = PriceOracle(_priceOracleAddr);
CUSDC = CERC20(_cUSDCAddr);
CETH_ADDR = _cETHAddr;
USDC_ADDR = _usdcAddr;
KYBER_ADDR = _kyberAddr;
usdc = ERC20Detailed(_usdcAddr);
kyber = KyberNetwork(_kyberAddr);
// transfer ownership to msg.sender
_transferOwnership(msg.sender);
}
/**
* @notice Executes the Compound order
* @param _minPrice the minimum token price
* @param _maxPrice the maximum token price
*/
function executeOrder(uint256 _minPrice, uint256 _maxPrice) public;
/**
* @notice Sells the Compound order and returns assets to PeakDeFiFund
* @param _minPrice the minimum token price
* @param _maxPrice the maximum token price
*/
function sellOrder(uint256 _minPrice, uint256 _maxPrice) public returns (uint256 _inputAmount, uint256 _outputAmount);
/**
* @notice Repays the loans taken out to prevent the collateral ratio from dropping below threshold
* @param _repayAmountInUSDC the amount to repay, in USDC
*/
function repayLoan(uint256 _repayAmountInUSDC) public;
/**
* @notice Emergency method, which allow to transfer selected tokens to the fund address
* @param _tokenAddr address of withdrawn token
* @param _receiver address who should receive tokens
*/
function emergencyExitTokens(address _tokenAddr, address _receiver) public onlyOwner {
ERC20Detailed token = ERC20Detailed(_tokenAddr);
token.safeTransfer(_receiver, token.balanceOf(address(this)));
}
function getMarketCollateralFactor() public view returns (uint256);
function getCurrentCollateralInUSDC() public returns (uint256 _amount);
function getCurrentBorrowInUSDC() public returns (uint256 _amount);
function getCurrentCashInUSDC() public view returns (uint256 _amount);
/**
* @notice Calculates the current profit in USDC
* @return the profit amount
*/
function getCurrentProfitInUSDC() public returns (bool _isNegative, uint256 _amount) {
uint256 l;
uint256 r;
if (isSold) {
l = outputAmount;
r = collateralAmountInUSDC;
} else {
uint256 cash = getCurrentCashInUSDC();
uint256 supply = getCurrentCollateralInUSDC();
uint256 borrow = getCurrentBorrowInUSDC();
if (cash >= borrow) {
l = supply.add(cash);
r = borrow.add(collateralAmountInUSDC);
} else {
l = supply;
r = borrow.sub(cash).mul(PRECISION).div(getMarketCollateralFactor()).add(collateralAmountInUSDC);
}
}
if (l >= r) {
return (false, l.sub(r));
} else {
return (true, r.sub(l));
}
}
/**
* @notice Calculates the current collateral ratio on Compound, using 18 decimals
* @return the collateral ratio
*/
function getCurrentCollateralRatioInUSDC() public returns (uint256 _amount) {
uint256 supply = getCurrentCollateralInUSDC();
uint256 borrow = getCurrentBorrowInUSDC();
if (borrow == 0) {
return uint256(-1);
}
return supply.mul(PRECISION).div(borrow);
}
/**
* @notice Calculates the current liquidity (supply - collateral) on the Compound platform
* @return the liquidity
*/
function getCurrentLiquidityInUSDC() public returns (bool _isNegative, uint256 _amount) {
uint256 supply = getCurrentCollateralInUSDC();
uint256 borrow = getCurrentBorrowInUSDC().mul(PRECISION).div(getMarketCollateralFactor());
if (supply >= borrow) {
return (false, supply.sub(borrow));
} else {
return (true, borrow.sub(supply));
}
}
function __sellUSDCForToken(uint256 _usdcAmount) internal returns (uint256 _actualUSDCAmount, uint256 _actualTokenAmount) {
ERC20Detailed t = __underlyingToken(compoundTokenAddr);
(,, _actualTokenAmount, _actualUSDCAmount) = __kyberTrade(usdc, _usdcAmount, t); // Sell USDC for tokens on Kyber
require(_actualUSDCAmount > 0 && _actualTokenAmount > 0); // Validate return values
}
function __sellTokenForUSDC(uint256 _tokenAmount) internal returns (uint256 _actualUSDCAmount, uint256 _actualTokenAmount) {
ERC20Detailed t = __underlyingToken(compoundTokenAddr);
(,, _actualUSDCAmount, _actualTokenAmount) = __kyberTrade(t, _tokenAmount, usdc); // Sell tokens for USDC on Kyber
require(_actualUSDCAmount > 0 && _actualTokenAmount > 0); // Validate return values
}
// Convert a USDC amount to the amount of a given token that's of equal value
function __usdcToToken(address _cToken, uint256 _usdcAmount) internal view returns (uint256) {
ERC20Detailed t = __underlyingToken(_cToken);
return _usdcAmount.mul(PRECISION).div(10 ** getDecimals(usdc)).mul(10 ** getDecimals(t)).div(ORACLE.getUnderlyingPrice(_cToken).mul(10 ** getDecimals(t)).div(PRECISION));
}
// Convert a compound token amount to the amount of USDC that's of equal value
function __tokenToUSDC(address _cToken, uint256 _tokenAmount) internal view returns (uint256) {
return _tokenAmount.mul(ORACLE.getUnderlyingPrice(_cToken)).div(PRECISION).mul(10 ** getDecimals(usdc)).div(PRECISION);
}
function __underlyingToken(address _cToken) internal view returns (ERC20Detailed) {
if (_cToken == CETH_ADDR) {
// ETH
return ETH_TOKEN_ADDRESS;
}
CERC20 ct = CERC20(_cToken);
address underlyingToken = ct.underlying();
ERC20Detailed t = ERC20Detailed(underlyingToken);
return t;
}
function() external payable {}
}
pragma solidity ^0.5.0;
import "../GSN/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return _msgSender() == _owner;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
pragma solidity ^0.5.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
pragma solidity 0.5.17;
// Compound finance comptroller
interface Comptroller {
function enterMarkets(address[] calldata cTokens) external returns (uint[] memory);
function markets(address cToken) external view returns (bool isListed, uint256 collateralFactorMantissa);
}
pragma solidity 0.5.17;
// Compound finance's price oracle
interface PriceOracle {
// returns the price of the underlying token in USD, scaled by 10**(36 - underlyingPrecision)
function getUnderlyingPrice(address cToken) external view returns (uint);
}
pragma solidity 0.5.17;
// Compound finance ERC20 market interface
interface CERC20 {
function mint(uint mintAmount) 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 borrowBalanceCurrent(address account) external returns (uint);
function exchangeRateCurrent() external returns (uint);
function balanceOf(address account) external view returns (uint);
function decimals() external view returns (uint);
function underlying() external view returns (address);
}
pragma solidity 0.5.17;
// Compound finance Ether market interface
interface CEther {
function mint() external payable;
function redeemUnderlying(uint redeemAmount) external returns (uint);
function borrow(uint borrowAmount) external returns (uint);
function repayBorrow() external payable;
function borrowBalanceCurrent(address account) external returns (uint);
function exchangeRateCurrent() external returns (uint);
function balanceOf(address account) external view returns (uint);
function decimals() external view returns (uint);
}
pragma solidity 0.5.17;
import "@openzeppelin/contracts/token/ERC20/ERC20Detailed.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./interfaces/KyberNetwork.sol";
import "./interfaces/OneInchExchange.sol";
/**
* @title The smart contract for useful utility functions and constants.
* @author Zefram Lou (Zebang Liu)
*/
contract Utils {
using SafeMath for uint256;
using SafeERC20 for ERC20Detailed;
/**
* @notice Checks if `_token` is a valid token.
* @param _token the token's address
*/
modifier isValidToken(address _token) {
require(_token != address(0));
if (_token != address(ETH_TOKEN_ADDRESS)) {
require(isContract(_token));
}
_;
}
address public USDC_ADDR;
address payable public KYBER_ADDR;
address payable public ONEINCH_ADDR;
bytes public constant PERM_HINT = "PERM";
// The address Kyber Network uses to represent Ether
ERC20Detailed internal constant ETH_TOKEN_ADDRESS = ERC20Detailed(0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee);
ERC20Detailed internal usdc;
KyberNetwork internal kyber;
uint256 constant internal PRECISION = (10**18);
uint256 constant internal MAX_QTY = (10**28); // 10B tokens
uint256 constant internal ETH_DECIMALS = 18;
uint256 constant internal MAX_DECIMALS = 18;
constructor(
address _usdcAddr,
address payable _kyberAddr,
address payable _oneInchAddr
) public {
USDC_ADDR = _usdcAddr;
KYBER_ADDR = _kyberAddr;
ONEINCH_ADDR = _oneInchAddr;
usdc = ERC20Detailed(_usdcAddr);
kyber = KyberNetwork(_kyberAddr);
}
/**
* @notice Get the number of decimals of a token
* @param _token the token to be queried
* @return number of decimals
*/
function getDecimals(ERC20Detailed _token) internal view returns(uint256) {
if (address(_token) == address(ETH_TOKEN_ADDRESS)) {
return uint256(ETH_DECIMALS);
}
return uint256(_token.decimals());
}
/**
* @notice Get the token balance of an account
* @param _token the token to be queried
* @param _addr the account whose balance will be returned
* @return token balance of the account
*/
function getBalance(ERC20Detailed _token, address _addr) internal view returns(uint256) {
if (address(_token) == address(ETH_TOKEN_ADDRESS)) {
return uint256(_addr.balance);
}
return uint256(_token.balanceOf(_addr));
}
/**
* @notice Calculates the rate of a trade. The rate is the price of the source token in the dest token, in 18 decimals.
* Note: the rate is on the token level, not the wei level, so for example if 1 Atoken = 10 Btoken, then the rate
* from A to B is 10 * 10**18, regardless of how many decimals each token uses.
* @param srcAmount amount of source token
* @param destAmount amount of dest token
* @param srcDecimals decimals used by source token
* @param dstDecimals decimals used by dest token
*/
function calcRateFromQty(uint256 srcAmount, uint256 destAmount, uint256 srcDecimals, uint256 dstDecimals)
internal pure returns(uint)
{
require(srcAmount <= MAX_QTY);
require(destAmount <= MAX_QTY);
if (dstDecimals >= srcDecimals) {
require((dstDecimals - srcDecimals) <= MAX_DECIMALS);
return (destAmount * PRECISION / ((10 ** (dstDecimals - srcDecimals)) * srcAmount));
} else {
require((srcDecimals - dstDecimals) <= MAX_DECIMALS);
return (destAmount * PRECISION * (10 ** (srcDecimals - dstDecimals)) / srcAmount);
}
}
/**
* @notice Wrapper function for doing token conversion on Kyber Network
* @param _srcToken the token to convert from
* @param _srcAmount the amount of tokens to be converted
* @param _destToken the destination token
* @return _destPriceInSrc the price of the dest token, in terms of source tokens
* _srcPriceInDest the price of the source token, in terms of dest tokens
* _actualDestAmount actual amount of dest token traded
* _actualSrcAmount actual amount of src token traded
*/
function __kyberTrade(ERC20Detailed _srcToken, uint256 _srcAmount, ERC20Detailed _destToken)
internal
returns(
uint256 _destPriceInSrc,
uint256 _srcPriceInDest,
uint256 _actualDestAmount,
uint256 _actualSrcAmount
)
{
require(_srcToken != _destToken);
uint256 beforeSrcBalance = getBalance(_srcToken, address(this));
uint256 msgValue;
if (_srcToken != ETH_TOKEN_ADDRESS) {
msgValue = 0;
_srcToken.safeApprove(KYBER_ADDR, 0);
_srcToken.safeApprove(KYBER_ADDR, _srcAmount);
} else {
msgValue = _srcAmount;
}
_actualDestAmount = kyber.tradeWithHint.value(msgValue)(
_srcToken,
_srcAmount,
_destToken,
toPayableAddr(address(this)),
MAX_QTY,
1,
address(0),
PERM_HINT
);
_actualSrcAmount = beforeSrcBalance.sub(getBalance(_srcToken, address(this)));
require(_actualDestAmount > 0 && _actualSrcAmount > 0);
_destPriceInSrc = calcRateFromQty(_actualDestAmount, _actualSrcAmount, getDecimals(_destToken), getDecimals(_srcToken));
_srcPriceInDest = calcRateFromQty(_actualSrcAmount, _actualDestAmount, getDecimals(_srcToken), getDecimals(_destToken));
}
/**
* @notice Wrapper function for doing token conversion on 1inch
* @param _srcToken the token to convert from
* @param _srcAmount the amount of tokens to be converted
* @param _destToken the destination token
* @return _destPriceInSrc the price of the dest token, in terms of source tokens
* _srcPriceInDest the price of the source token, in terms of dest tokens
* _actualDestAmount actual amount of dest token traded
* _actualSrcAmount actual amount of src token traded
*/
function __oneInchTrade(ERC20Detailed _srcToken, uint256 _srcAmount, ERC20Detailed _destToken, bytes memory _calldata)
internal
returns(
uint256 _destPriceInSrc,
uint256 _srcPriceInDest,
uint256 _actualDestAmount,
uint256 _actualSrcAmount
)
{
require(_srcToken != _destToken);
uint256 beforeSrcBalance = getBalance(_srcToken, address(this));
uint256 beforeDestBalance = getBalance(_destToken, address(this));
// Note: _actualSrcAmount is being used as msgValue here, because otherwise we'd run into the stack too deep error
if (_srcToken != ETH_TOKEN_ADDRESS) {
_actualSrcAmount = 0;
OneInchExchange dex = OneInchExchange(ONEINCH_ADDR);
address approvalHandler = dex.spender();
_srcToken.safeApprove(approvalHandler, 0);
_srcToken.safeApprove(approvalHandler, _srcAmount);
} else {
_actualSrcAmount = _srcAmount;
}
// trade through 1inch proxy
(bool success,) = ONEINCH_ADDR.call.value(_actualSrcAmount)(_calldata);
require(success);
// calculate trade amounts and price
_actualDestAmount = getBalance(_destToken, address(this)).sub(beforeDestBalance);
_actualSrcAmount = beforeSrcBalance.sub(getBalance(_srcToken, address(this)));
require(_actualDestAmount > 0 && _actualSrcAmount > 0);
_destPriceInSrc = calcRateFromQty(_actualDestAmount, _actualSrcAmount, getDecimals(_destToken), getDecimals(_srcToken));
_srcPriceInDest = calcRateFromQty(_actualSrcAmount, _actualDestAmount, getDecimals(_srcToken), getDecimals(_destToken));
}
/**
* @notice Checks if an Ethereum account is a smart contract
* @param _addr the account to be checked
* @return True if the account is a smart contract, false otherwise
*/
function isContract(address _addr) internal view returns(bool) {
uint256 size;
if (_addr == address(0)) return false;
assembly {
size := extcodesize(_addr)
}
return size>0;
}
function toPayableAddr(address _addr) internal pure returns (address payable) {
return address(uint160(_addr));
}
}
pragma solidity ^0.5.0;
import "./IERC20.sol";
/**
* @dev Optional functions from the ERC20 standard.
*/
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for `name`, `symbol`, and `decimals`. All three of
* these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
}
pragma solidity ^0.5.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
pragma solidity ^0.5.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
pragma solidity ^0.5.5;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
pragma solidity 0.5.17;
import "@openzeppelin/contracts/token/ERC20/ERC20Detailed.sol";
/**
* @title The interface for the Kyber Network smart contract
* @author Zefram Lou (Zebang Liu)
*/
interface KyberNetwork {
function getExpectedRate(ERC20Detailed src, ERC20Detailed dest, uint srcQty) external view
returns (uint expectedRate, uint slippageRate);
function tradeWithHint(
ERC20Detailed src, uint srcAmount, ERC20Detailed dest, address payable destAddress, uint maxDestAmount,
uint minConversionRate, address walletId, bytes calldata hint) external payable returns(uint);
}
pragma solidity 0.5.17;
interface OneInchExchange {
function spender() external view returns (address);
}
pragma solidity 0.5.17;
import "./LongCERC20Order.sol";
import "./LongCEtherOrder.sol";
import "./ShortCERC20Order.sol";
import "./ShortCEtherOrder.sol";
import "../lib/CloneFactory.sol";
contract CompoundOrderFactory is CloneFactory {
address public SHORT_CERC20_LOGIC_CONTRACT;
address public SHORT_CEther_LOGIC_CONTRACT;
address public LONG_CERC20_LOGIC_CONTRACT;
address public LONG_CEther_LOGIC_CONTRACT;
address public USDC_ADDR;
address payable public KYBER_ADDR;
address public COMPTROLLER_ADDR;
address public ORACLE_ADDR;
address public CUSDC_ADDR;
address public CETH_ADDR;
constructor(
address _shortCERC20LogicContract,
address _shortCEtherLogicContract,
address _longCERC20LogicContract,
address _longCEtherLogicContract,
address _usdcAddr,
address payable _kyberAddr,
address _comptrollerAddr,
address _priceOracleAddr,
address _cUSDCAddr,
address _cETHAddr
) public {
SHORT_CERC20_LOGIC_CONTRACT = _shortCERC20LogicContract;
SHORT_CEther_LOGIC_CONTRACT = _shortCEtherLogicContract;
LONG_CERC20_LOGIC_CONTRACT = _longCERC20LogicContract;
LONG_CEther_LOGIC_CONTRACT = _longCEtherLogicContract;
USDC_ADDR = _usdcAddr;
KYBER_ADDR = _kyberAddr;
COMPTROLLER_ADDR = _comptrollerAddr;
ORACLE_ADDR = _priceOracleAddr;
CUSDC_ADDR = _cUSDCAddr;
CETH_ADDR = _cETHAddr;
}
function createOrder(
address _compoundTokenAddr,
uint256 _cycleNumber,
uint256 _stake,
uint256 _collateralAmountInUSDC,
uint256 _loanAmountInUSDC,
bool _orderType
) external returns (CompoundOrder) {
require(_compoundTokenAddr != address(0));
CompoundOrder order;
address payable clone;
if (_compoundTokenAddr != CETH_ADDR) {
if (_orderType) {
// Short CERC20 Order
clone = toPayableAddr(createClone(SHORT_CERC20_LOGIC_CONTRACT));
} else {
// Long CERC20 Order
clone = toPayableAddr(createClone(LONG_CERC20_LOGIC_CONTRACT));
}
} else {
if (_orderType) {
// Short CEther Order
clone = toPayableAddr(createClone(SHORT_CEther_LOGIC_CONTRACT));
} else {
// Long CEther Order
clone = toPayableAddr(createClone(LONG_CEther_LOGIC_CONTRACT));
}
}
order = CompoundOrder(clone);
order.init(_compoundTokenAddr, _cycleNumber, _stake, _collateralAmountInUSDC, _loanAmountInUSDC, _orderType,
USDC_ADDR, KYBER_ADDR, COMPTROLLER_ADDR, ORACLE_ADDR, CUSDC_ADDR, CETH_ADDR);
order.transferOwnership(msg.sender);
return order;
}
function getMarketCollateralFactor(address _compoundTokenAddr) external view returns (uint256) {
Comptroller troll = Comptroller(COMPTROLLER_ADDR);
(, uint256 factor) = troll.markets(_compoundTokenAddr);
return factor;
}
function tokenIsListed(address _compoundTokenAddr) external view returns (bool) {
Comptroller troll = Comptroller(COMPTROLLER_ADDR);
(bool isListed,) = troll.markets(_compoundTokenAddr);
return isListed;
}
function toPayableAddr(address _addr) internal pure returns (address payable) {
return address(uint160(_addr));
}
}
pragma solidity 0.5.17;
import "./CompoundOrder.sol";
contract LongCERC20Order is CompoundOrder {
modifier isValidPrice(uint256 _minPrice, uint256 _maxPrice) {
// Ensure token's price is between _minPrice and _maxPrice
uint256 tokenPrice = ORACLE.getUnderlyingPrice(compoundTokenAddr); // Get the longing token's price in USD
require(tokenPrice > 0); // Ensure asset exists on Compound
require(tokenPrice >= _minPrice && tokenPrice <= _maxPrice); // Ensure price is within range
_;
}
function executeOrder(uint256 _minPrice, uint256 _maxPrice)
public
onlyOwner
isValidToken(compoundTokenAddr)
isValidPrice(_minPrice, _maxPrice)
{
buyTime = now;
// Get funds in USDC from PeakDeFiFund
usdc.safeTransferFrom(owner(), address(this), collateralAmountInUSDC); // Transfer USDC from PeakDeFiFund
// Convert received USDC to longing token
(,uint256 actualTokenAmount) = __sellUSDCForToken(collateralAmountInUSDC);
// Enter Compound markets
CERC20 market = CERC20(compoundTokenAddr);
address[] memory markets = new address[](2);
markets[0] = compoundTokenAddr;
markets[1] = address(CUSDC);
uint[] memory errors = COMPTROLLER.enterMarkets(markets);
require(errors[0] == 0 && errors[1] == 0);
// Get loan from Compound in USDC
ERC20Detailed token = __underlyingToken(compoundTokenAddr);
token.safeApprove(compoundTokenAddr, 0); // Clear token allowance of Compound
token.safeApprove(compoundTokenAddr, actualTokenAmount); // Approve token transfer to Compound
require(market.mint(actualTokenAmount) == 0); // Transfer tokens into Compound as supply
token.safeApprove(compoundTokenAddr, 0); // Clear token allowance of Compound
require(CUSDC.borrow(loanAmountInUSDC) == 0);// Take out loan in USDC
(bool negLiquidity, ) = getCurrentLiquidityInUSDC();
require(!negLiquidity); // Ensure account liquidity is positive
// Convert borrowed USDC to longing token
__sellUSDCForToken(loanAmountInUSDC);
// Repay leftover USDC to avoid complications
if (usdc.balanceOf(address(this)) > 0) {
uint256 repayAmount = usdc.balanceOf(address(this));
usdc.safeApprove(address(CUSDC), 0);
usdc.safeApprove(address(CUSDC), repayAmount);
require(CUSDC.repayBorrow(repayAmount) == 0);
usdc.safeApprove(address(CUSDC), 0);
}
}
function sellOrder(uint256 _minPrice, uint256 _maxPrice)
public
onlyOwner
isValidPrice(_minPrice, _maxPrice)
returns (uint256 _inputAmount, uint256 _outputAmount)
{
require(buyTime > 0); // Ensure the order has been executed
require(isSold == false);
isSold = true;
// Siphon remaining collateral by repaying x USDC and getting back 1.5x USDC collateral
// Repeat to ensure debt is exhausted
CERC20 market = CERC20(compoundTokenAddr);
ERC20Detailed token = __underlyingToken(compoundTokenAddr);
for (uint256 i = 0; i < MAX_REPAY_STEPS; i++) {
uint256 currentDebt = getCurrentBorrowInUSDC();
if (currentDebt > NEGLIGIBLE_DEBT) {
// Determine amount to be repaid this step
uint256 currentBalance = getCurrentCashInUSDC();
uint256 repayAmount = 0; // amount to be repaid in USDC
if (currentDebt <= currentBalance) {
// Has enough money, repay all debt
repayAmount = currentDebt;
} else {
// Doesn't have enough money, repay whatever we can repay
repayAmount = currentBalance;
}
// Repay debt
repayLoan(repayAmount);
}
// Withdraw all available liquidity
(bool isNeg, uint256 liquidity) = getCurrentLiquidityInUSDC();
if (!isNeg) {
liquidity = __usdcToToken(compoundTokenAddr, liquidity);
uint256 errorCode = market.redeemUnderlying(liquidity.mul(PRECISION.sub(DEFAULT_LIQUIDITY_SLIPPAGE)).div(PRECISION));
if (errorCode != 0) {
// error
// try again with fallback slippage
errorCode = market.redeemUnderlying(liquidity.mul(PRECISION.sub(FALLBACK_LIQUIDITY_SLIPPAGE)).div(PRECISION));
if (errorCode != 0) {
// error
// try again with max slippage
market.redeemUnderlying(liquidity.mul(PRECISION.sub(MAX_LIQUIDITY_SLIPPAGE)).div(PRECISION));
}
}
}
if (currentDebt <= NEGLIGIBLE_DEBT) {
break;
}
}
// Sell all longing token to USDC
__sellTokenForUSDC(token.balanceOf(address(this)));
// Send USDC back to PeakDeFiFund and return
_inputAmount = collateralAmountInUSDC;
_outputAmount = usdc.balanceOf(address(this));
outputAmount = _outputAmount;
usdc.safeTransfer(owner(), usdc.balanceOf(address(this)));
uint256 leftoverTokens = token.balanceOf(address(this));
if (leftoverTokens > 0) {
token.safeTransfer(owner(), leftoverTokens); // Send back potential leftover tokens
}
}
// Allows manager to repay loan to avoid liquidation
function repayLoan(uint256 _repayAmountInUSDC) public onlyOwner {
require(buyTime > 0); // Ensure the order has been executed
// Convert longing token to USDC
uint256 repayAmountInToken = __usdcToToken(compoundTokenAddr, _repayAmountInUSDC);
(uint256 actualUSDCAmount,) = __sellTokenForUSDC(repayAmountInToken);
// Check if amount is greater than borrow balance
uint256 currentDebt = CUSDC.borrowBalanceCurrent(address(this));
if (actualUSDCAmount > currentDebt) {
actualUSDCAmount = currentDebt;
}
// Repay loan to Compound
usdc.safeApprove(address(CUSDC), 0);
usdc.safeApprove(address(CUSDC), actualUSDCAmount);
require(CUSDC.repayBorrow(actualUSDCAmount) == 0);
usdc.safeApprove(address(CUSDC), 0);
}
function getMarketCollateralFactor() public view returns (uint256) {
(, uint256 ratio) = COMPTROLLER.markets(address(compoundTokenAddr));
return ratio;
}
function getCurrentCollateralInUSDC() public returns (uint256 _amount) {
CERC20 market = CERC20(compoundTokenAddr);
uint256 supply = __tokenToUSDC(compoundTokenAddr, market.balanceOf(address(this)).mul(market.exchangeRateCurrent()).div(PRECISION));
return supply;
}
function getCurrentBorrowInUSDC() public returns (uint256 _amount) {
uint256 borrow = CUSDC.borrowBalanceCurrent(address(this));
return borrow;
}
function getCurrentCashInUSDC() public view returns (uint256 _amount) {
ERC20Detailed token = __underlyingToken(compoundTokenAddr);
uint256 cash = __tokenToUSDC(compoundTokenAddr, getBalance(token, address(this)));
return cash;
}
}
pragma solidity 0.5.17;
import "./CompoundOrder.sol";
contract LongCEtherOrder is CompoundOrder {
modifier isValidPrice(uint256 _minPrice, uint256 _maxPrice) {
// Ensure token's price is between _minPrice and _maxPrice
uint256 tokenPrice = ORACLE.getUnderlyingPrice(compoundTokenAddr); // Get the longing token's price in USD
require(tokenPrice > 0); // Ensure asset exists on Compound
require(tokenPrice >= _minPrice && tokenPrice <= _maxPrice); // Ensure price is within range
_;
}
function executeOrder(uint256 _minPrice, uint256 _maxPrice)
public
onlyOwner
isValidToken(compoundTokenAddr)
isValidPrice(_minPrice, _maxPrice)
{
buyTime = now;
// Get funds in USDC from PeakDeFiFund
usdc.safeTransferFrom(owner(), address(this), collateralAmountInUSDC); // Transfer USDC from PeakDeFiFund
// Convert received USDC to longing token
(,uint256 actualTokenAmount) = __sellUSDCForToken(collateralAmountInUSDC);
// Enter Compound markets
CEther market = CEther(compoundTokenAddr);
address[] memory markets = new address[](2);
markets[0] = compoundTokenAddr;
markets[1] = address(CUSDC);
uint[] memory errors = COMPTROLLER.enterMarkets(markets);
require(errors[0] == 0 && errors[1] == 0);
// Get loan from Compound in USDC
market.mint.value(actualTokenAmount)(); // Transfer tokens into Compound as supply
require(CUSDC.borrow(loanAmountInUSDC) == 0);// Take out loan in USDC
(bool negLiquidity, ) = getCurrentLiquidityInUSDC();
require(!negLiquidity); // Ensure account liquidity is positive
// Convert borrowed USDC to longing token
__sellUSDCForToken(loanAmountInUSDC);
// Repay leftover USDC to avoid complications
if (usdc.balanceOf(address(this)) > 0) {
uint256 repayAmount = usdc.balanceOf(address(this));
usdc.safeApprove(address(CUSDC), 0);
usdc.safeApprove(address(CUSDC), repayAmount);
require(CUSDC.repayBorrow(repayAmount) == 0);
usdc.safeApprove(address(CUSDC), 0);
}
}
function sellOrder(uint256 _minPrice, uint256 _maxPrice)
public
onlyOwner
isValidPrice(_minPrice, _maxPrice)
returns (uint256 _inputAmount, uint256 _outputAmount)
{
require(buyTime > 0); // Ensure the order has been executed
require(isSold == false);
isSold = true;
// Siphon remaining collateral by repaying x USDC and getting back 1.5x USDC collateral
// Repeat to ensure debt is exhausted
CEther market = CEther(compoundTokenAddr);
for (uint256 i = 0; i < MAX_REPAY_STEPS; i++) {
uint256 currentDebt = getCurrentBorrowInUSDC();
if (currentDebt > NEGLIGIBLE_DEBT) {
// Determine amount to be repaid this step
uint256 currentBalance = getCurrentCashInUSDC();
uint256 repayAmount = 0; // amount to be repaid in USDC
if (currentDebt <= currentBalance) {
// Has enough money, repay all debt
repayAmount = currentDebt;
} else {
// Doesn't have enough money, repay whatever we can repay
repayAmount = currentBalance;
}
// Repay debt
repayLoan(repayAmount);
}
// Withdraw all available liquidity
(bool isNeg, uint256 liquidity) = getCurrentLiquidityInUSDC();
if (!isNeg) {
liquidity = __usdcToToken(compoundTokenAddr, liquidity);
uint256 errorCode = market.redeemUnderlying(liquidity.mul(PRECISION.sub(DEFAULT_LIQUIDITY_SLIPPAGE)).div(PRECISION));
if (errorCode != 0) {
// error
// try again with fallback slippage
errorCode = market.redeemUnderlying(liquidity.mul(PRECISION.sub(FALLBACK_LIQUIDITY_SLIPPAGE)).div(PRECISION));
if (errorCode != 0) {
// error
// try again with max slippage
market.redeemUnderlying(liquidity.mul(PRECISION.sub(MAX_LIQUIDITY_SLIPPAGE)).div(PRECISION));
}
}
}
if (currentDebt <= NEGLIGIBLE_DEBT) {
break;
}
}
// Sell all longing token to USDC
__sellTokenForUSDC(address(this).balance);
// Send USDC back to PeakDeFiFund and return
_inputAmount = collateralAmountInUSDC;
_outputAmount = usdc.balanceOf(address(this));
outputAmount = _outputAmount;
usdc.safeTransfer(owner(), usdc.balanceOf(address(this)));
toPayableAddr(owner()).transfer(address(this).balance); // Send back potential leftover tokens
}
// Allows manager to repay loan to avoid liquidation
function repayLoan(uint256 _repayAmountInUSDC) public onlyOwner {
require(buyTime > 0); // Ensure the order has been executed
// Convert longing token to USDC
uint256 repayAmountInToken = __usdcToToken(compoundTokenAddr, _repayAmountInUSDC);
(uint256 actualUSDCAmount,) = __sellTokenForUSDC(repayAmountInToken);
// Check if amount is greater than borrow balance
uint256 currentDebt = CUSDC.borrowBalanceCurrent(address(this));
if (actualUSDCAmount > currentDebt) {
actualUSDCAmount = currentDebt;
}
// Repay loan to Compound
usdc.safeApprove(address(CUSDC), 0);
usdc.safeApprove(address(CUSDC), actualUSDCAmount);
require(CUSDC.repayBorrow(actualUSDCAmount) == 0);
usdc.safeApprove(address(CUSDC), 0);
}
function getMarketCollateralFactor() public view returns (uint256) {
(, uint256 ratio) = COMPTROLLER.markets(address(compoundTokenAddr));
return ratio;
}
function getCurrentCollateralInUSDC() public returns (uint256 _amount) {
CEther market = CEther(compoundTokenAddr);
uint256 supply = __tokenToUSDC(compoundTokenAddr, market.balanceOf(address(this)).mul(market.exchangeRateCurrent()).div(PRECISION));
return supply;
}
function getCurrentBorrowInUSDC() public returns (uint256 _amount) {
uint256 borrow = CUSDC.borrowBalanceCurrent(address(this));
return borrow;
}
function getCurrentCashInUSDC() public view returns (uint256 _amount) {
ERC20Detailed token = __underlyingToken(compoundTokenAddr);
uint256 cash = __tokenToUSDC(compoundTokenAddr, getBalance(token, address(this)));
return cash;
}
}
pragma solidity 0.5.17;
import "./CompoundOrder.sol";
contract ShortCERC20Order is CompoundOrder {
modifier isValidPrice(uint256 _minPrice, uint256 _maxPrice) {
// Ensure token's price is between _minPrice and _maxPrice
uint256 tokenPrice = ORACLE.getUnderlyingPrice(compoundTokenAddr); // Get the shorting token's price in USD
require(tokenPrice > 0); // Ensure asset exists on Compound
require(tokenPrice >= _minPrice && tokenPrice <= _maxPrice); // Ensure price is within range
_;
}
function executeOrder(uint256 _minPrice, uint256 _maxPrice)
public
onlyOwner
isValidToken(compoundTokenAddr)
isValidPrice(_minPrice, _maxPrice)
{
buyTime = now;
// Get funds in USDC from PeakDeFiFund
usdc.safeTransferFrom(owner(), address(this), collateralAmountInUSDC); // Transfer USDC from PeakDeFiFund
// Enter Compound markets
CERC20 market = CERC20(compoundTokenAddr);
address[] memory markets = new address[](2);
markets[0] = compoundTokenAddr;
markets[1] = address(CUSDC);
uint[] memory errors = COMPTROLLER.enterMarkets(markets);
require(errors[0] == 0 && errors[1] == 0);
// Get loan from Compound in tokenAddr
uint256 loanAmountInToken = __usdcToToken(compoundTokenAddr, loanAmountInUSDC);
usdc.safeApprove(address(CUSDC), 0); // Clear USDC allowance of Compound USDC market
usdc.safeApprove(address(CUSDC), collateralAmountInUSDC); // Approve USDC transfer to Compound USDC market
require(CUSDC.mint(collateralAmountInUSDC) == 0); // Transfer USDC into Compound as supply
usdc.safeApprove(address(CUSDC), 0);
require(market.borrow(loanAmountInToken) == 0);// Take out loan
(bool negLiquidity, ) = getCurrentLiquidityInUSDC();
require(!negLiquidity); // Ensure account liquidity is positive
// Convert loaned tokens to USDC
(uint256 actualUSDCAmount,) = __sellTokenForUSDC(loanAmountInToken);
loanAmountInUSDC = actualUSDCAmount; // Change loan amount to actual USDC received
// Repay leftover tokens to avoid complications
ERC20Detailed token = __underlyingToken(compoundTokenAddr);
if (token.balanceOf(address(this)) > 0) {
uint256 repayAmount = token.balanceOf(address(this));
token.safeApprove(compoundTokenAddr, 0);
token.safeApprove(compoundTokenAddr, repayAmount);
require(market.repayBorrow(repayAmount) == 0);
token.safeApprove(compoundTokenAddr, 0);
}
}
function sellOrder(uint256 _minPrice, uint256 _maxPrice)
public
onlyOwner
isValidPrice(_minPrice, _maxPrice)
returns (uint256 _inputAmount, uint256 _outputAmount)
{
require(buyTime > 0); // Ensure the order has been executed
require(isSold == false);
isSold = true;
// Siphon remaining collateral by repaying x USDC and getting back 1.5x USDC collateral
// Repeat to ensure debt is exhausted
for (uint256 i = 0; i < MAX_REPAY_STEPS; i++) {
uint256 currentDebt = getCurrentBorrowInUSDC();
if (currentDebt > NEGLIGIBLE_DEBT) {
// Determine amount to be repaid this step
uint256 currentBalance = getCurrentCashInUSDC();
uint256 repayAmount = 0; // amount to be repaid in USDC
if (currentDebt <= currentBalance) {
// Has enough money, repay all debt
repayAmount = currentDebt;
} else {
// Doesn't have enough money, repay whatever we can repay
repayAmount = currentBalance;
}
// Repay debt
repayLoan(repayAmount);
}
// Withdraw all available liquidity
(bool isNeg, uint256 liquidity) = getCurrentLiquidityInUSDC();
if (!isNeg) {
uint256 errorCode = CUSDC.redeemUnderlying(liquidity.mul(PRECISION.sub(DEFAULT_LIQUIDITY_SLIPPAGE)).div(PRECISION));
if (errorCode != 0) {
// error
// try again with fallback slippage
errorCode = CUSDC.redeemUnderlying(liquidity.mul(PRECISION.sub(FALLBACK_LIQUIDITY_SLIPPAGE)).div(PRECISION));
if (errorCode != 0) {
// error
// try again with max slippage
CUSDC.redeemUnderlying(liquidity.mul(PRECISION.sub(MAX_LIQUIDITY_SLIPPAGE)).div(PRECISION));
}
}
}
if (currentDebt <= NEGLIGIBLE_DEBT) {
break;
}
}
// Send USDC back to PeakDeFiFund and return
_inputAmount = collateralAmountInUSDC;
_outputAmount = usdc.balanceOf(address(this));
outputAmount = _outputAmount;
usdc.safeTransfer(owner(), usdc.balanceOf(address(this)));
}
// Allows manager to repay loan to avoid liquidation
function repayLoan(uint256 _repayAmountInUSDC) public onlyOwner {
require(buyTime > 0); // Ensure the order has been executed
// Convert USDC to shorting token
(,uint256 actualTokenAmount) = __sellUSDCForToken(_repayAmountInUSDC);
// Check if amount is greater than borrow balance
CERC20 market = CERC20(compoundTokenAddr);
uint256 currentDebt = market.borrowBalanceCurrent(address(this));
if (actualTokenAmount > currentDebt) {
actualTokenAmount = currentDebt;
}
// Repay loan to Compound
ERC20Detailed token = __underlyingToken(compoundTokenAddr);
token.safeApprove(compoundTokenAddr, 0);
token.safeApprove(compoundTokenAddr, actualTokenAmount);
require(market.repayBorrow(actualTokenAmount) == 0);
token.safeApprove(compoundTokenAddr, 0);
}
function getMarketCollateralFactor() public view returns (uint256) {
(, uint256 ratio) = COMPTROLLER.markets(address(CUSDC));
return ratio;
}
function getCurrentCollateralInUSDC() public returns (uint256 _amount) {
uint256 supply = CUSDC.balanceOf(address(this)).mul(CUSDC.exchangeRateCurrent()).div(PRECISION);
return supply;
}
function getCurrentBorrowInUSDC() public returns (uint256 _amount) {
CERC20 market = CERC20(compoundTokenAddr);
uint256 borrow = __tokenToUSDC(compoundTokenAddr, market.borrowBalanceCurrent(address(this)));
return borrow;
}
function getCurrentCashInUSDC() public view returns (uint256 _amount) {
uint256 cash = getBalance(usdc, address(this));
return cash;
}
}
pragma solidity 0.5.17;
import "./CompoundOrder.sol";
contract ShortCEtherOrder is CompoundOrder {
modifier isValidPrice(uint256 _minPrice, uint256 _maxPrice) {
// Ensure token's price is between _minPrice and _maxPrice
uint256 tokenPrice = ORACLE.getUnderlyingPrice(compoundTokenAddr); // Get the shorting token's price in USD
require(tokenPrice > 0); // Ensure asset exists on Compound
require(tokenPrice >= _minPrice && tokenPrice <= _maxPrice); // Ensure price is within range
_;
}
function executeOrder(uint256 _minPrice, uint256 _maxPrice)
public
onlyOwner
isValidToken(compoundTokenAddr)
isValidPrice(_minPrice, _maxPrice)
{
buyTime = now;
// Get funds in USDC from PeakDeFiFund
usdc.safeTransferFrom(owner(), address(this), collateralAmountInUSDC); // Transfer USDC from PeakDeFiFund
// Enter Compound markets
CEther market = CEther(compoundTokenAddr);
address[] memory markets = new address[](2);
markets[0] = compoundTokenAddr;
markets[1] = address(CUSDC);
uint[] memory errors = COMPTROLLER.enterMarkets(markets);
require(errors[0] == 0 && errors[1] == 0);
// Get loan from Compound in tokenAddr
uint256 loanAmountInToken = __usdcToToken(compoundTokenAddr, loanAmountInUSDC);
usdc.safeApprove(address(CUSDC), 0); // Clear USDC allowance of Compound USDC market
usdc.safeApprove(address(CUSDC), collateralAmountInUSDC); // Approve USDC transfer to Compound USDC market
require(CUSDC.mint(collateralAmountInUSDC) == 0); // Transfer USDC into Compound as supply
usdc.safeApprove(address(CUSDC), 0);
require(market.borrow(loanAmountInToken) == 0);// Take out loan
(bool negLiquidity, ) = getCurrentLiquidityInUSDC();
require(!negLiquidity); // Ensure account liquidity is positive
// Convert loaned tokens to USDC
(uint256 actualUSDCAmount,) = __sellTokenForUSDC(loanAmountInToken);
loanAmountInUSDC = actualUSDCAmount; // Change loan amount to actual USDC received
// Repay leftover tokens to avoid complications
if (address(this).balance > 0) {
uint256 repayAmount = address(this).balance;
market.repayBorrow.value(repayAmount)();
}
}
function sellOrder(uint256 _minPrice, uint256 _maxPrice)
public
onlyOwner
isValidPrice(_minPrice, _maxPrice)
returns (uint256 _inputAmount, uint256 _outputAmount)
{
require(buyTime > 0); // Ensure the order has been executed
require(isSold == false);
isSold = true;
// Siphon remaining collateral by repaying x USDC and getting back 1.5x USDC collateral
// Repeat to ensure debt is exhausted
for (uint256 i = 0; i < MAX_REPAY_STEPS; i = i++) {
uint256 currentDebt = getCurrentBorrowInUSDC();
if (currentDebt > NEGLIGIBLE_DEBT) {
// Determine amount to be repaid this step
uint256 currentBalance = getCurrentCashInUSDC();
uint256 repayAmount = 0; // amount to be repaid in USDC
if (currentDebt <= currentBalance) {
// Has enough money, repay all debt
repayAmount = currentDebt;
} else {
// Doesn't have enough money, repay whatever we can repay
repayAmount = currentBalance;
}
// Repay debt
repayLoan(repayAmount);
}
// Withdraw all available liquidity
(bool isNeg, uint256 liquidity) = getCurrentLiquidityInUSDC();
if (!isNeg) {
uint256 errorCode = CUSDC.redeemUnderlying(liquidity.mul(PRECISION.sub(DEFAULT_LIQUIDITY_SLIPPAGE)).div(PRECISION));
if (errorCode != 0) {
// error
// try again with fallback slippage
errorCode = CUSDC.redeemUnderlying(liquidity.mul(PRECISION.sub(FALLBACK_LIQUIDITY_SLIPPAGE)).div(PRECISION));
if (errorCode != 0) {
// error
// try again with max slippage
CUSDC.redeemUnderlying(liquidity.mul(PRECISION.sub(MAX_LIQUIDITY_SLIPPAGE)).div(PRECISION));
}
}
}
if (currentDebt <= NEGLIGIBLE_DEBT) {
break;
}
}
// Send USDC back to PeakDeFiFund and return
_inputAmount = collateralAmountInUSDC;
_outputAmount = usdc.balanceOf(address(this));
outputAmount = _outputAmount;
usdc.safeTransfer(owner(), usdc.balanceOf(address(this)));
}
// Allows manager to repay loan to avoid liquidation
function repayLoan(uint256 _repayAmountInUSDC) public onlyOwner {
require(buyTime > 0); // Ensure the order has been executed
// Convert USDC to shorting token
(,uint256 actualTokenAmount) = __sellUSDCForToken(_repayAmountInUSDC);
// Check if amount is greater than borrow balance
CEther market = CEther(compoundTokenAddr);
uint256 currentDebt = market.borrowBalanceCurrent(address(this));
if (actualTokenAmount > currentDebt) {
actualTokenAmount = currentDebt;
}
// Repay loan to Compound
market.repayBorrow.value(actualTokenAmount)();
}
function getMarketCollateralFactor() public view returns (uint256) {
(, uint256 ratio) = COMPTROLLER.markets(address(CUSDC));
return ratio;
}
function getCurrentCollateralInUSDC() public returns (uint256 _amount) {
uint256 supply = CUSDC.balanceOf(address(this)).mul(CUSDC.exchangeRateCurrent()).div(PRECISION);
return supply;
}
function getCurrentBorrowInUSDC() public returns (uint256 _amount) {
CEther market = CEther(compoundTokenAddr);
uint256 borrow = __tokenToUSDC(compoundTokenAddr, market.borrowBalanceCurrent(address(this)));
return borrow;
}
function getCurrentCashInUSDC() public view returns (uint256 _amount) {
uint256 cash = getBalance(usdc, address(this));
return cash;
}
}
pragma solidity 0.5.17;
/*
The MIT License (MIT)
Copyright (c) 2018 Murray Software, LLC.
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.
*/
//solhint-disable max-line-length
//solhint-disable no-inline-assembly
contract CloneFactory {
function createClone(address target) internal returns (address result) {
bytes20 targetBytes = bytes20(target);
assembly {
let clone := mload(0x40)
mstore(clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(clone, 0x14), targetBytes)
mstore(add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
result := create(0, clone, 0x37)
}
}
function isClone(address target, address query) internal view returns (bool result) {
bytes20 targetBytes = bytes20(target);
assembly {
let clone := mload(0x40)
mstore(clone, 0x363d3d373d3d3d363d7300000000000000000000000000000000000000000000)
mstore(add(clone, 0xa), targetBytes)
mstore(add(clone, 0x1e), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
let other := add(clone, 0x40)
extcodecopy(query, other, 0, 0x2d)
result := and(
eq(mload(clone), mload(other)),
eq(mload(add(clone, 0xd)), mload(add(other, 0xd)))
)
}
}
}
pragma solidity 0.5.17;
interface IMiniMeToken {
function balanceOf(address _owner) external view returns (uint256 balance);
function totalSupply() external view returns(uint);
function generateTokens(address _owner, uint _amount) external returns (bool);
function destroyTokens(address _owner, uint _amount) external returns (bool);
function totalSupplyAt(uint _blockNumber) external view returns(uint);
function balanceOfAt(address _holder, uint _blockNumber) external view returns (uint);
function transferOwnership(address newOwner) external;
}
pragma solidity ^0.5.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].
*
* _Since v2.5.0:_ this module is now much more gas efficient, given net gas
* metering changes introduced in the Istanbul hardfork.
*/
contract ReentrancyGuard {
bool private _notEntered;
function __initReentrancyGuard() 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;
}
}
pragma solidity 0.5.17;
contract Migrations {
address public owner;
uint public last_completed_migration;
modifier restricted() {
if (msg.sender == owner) _;
}
constructor() public {
owner = msg.sender;
}
function setCompleted(uint completed) public restricted {
last_completed_migration = completed;
}
function upgrade(address new_address) public restricted {
Migrations upgraded = Migrations(new_address);
upgraded.setCompleted(last_completed_migration);
}
}
pragma solidity 0.5.17;
// interface for contract_v6/UniswapOracle.sol
interface IUniswapOracle {
function update() external returns (bool success);
function consult(address token, uint256 amountIn)
external
view
returns (uint256 amountOut);
}
pragma solidity 0.5.17;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20Detailed.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20Capped.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol";
contract PeakToken is ERC20, ERC20Detailed, ERC20Capped, ERC20Burnable {
constructor(
string memory name,
string memory symbol,
uint8 decimals,
uint256 cap
) ERC20Detailed(name, symbol, decimals) ERC20Capped(cap) public {}
}
pragma solidity ^0.5.0;
import "../../GSN/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 {ERC20Mintable}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for `sender`'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Destroys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See {_burn} and {_approve}.
*/
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance"));
}
}
pragma solidity ^0.5.0;
import "./ERC20Mintable.sol";
/**
* @dev Extension of {ERC20Mintable} that adds a cap to the supply of tokens.
*/
contract ERC20Capped is ERC20Mintable {
uint256 private _cap;
/**
* @dev Sets the value of the `cap`. This value is immutable, it can only be
* set once during construction.
*/
constructor (uint256 cap) public {
require(cap > 0, "ERC20Capped: cap is 0");
_cap = cap;
}
/**
* @dev Returns the cap on the token's total supply.
*/
function cap() public view returns (uint256) {
return _cap;
}
/**
* @dev See {ERC20Mintable-mint}.
*
* Requirements:
*
* - `value` must not cause the total supply to go over the cap.
*/
function _mint(address account, uint256 value) internal {
require(totalSupply().add(value) <= _cap, "ERC20Capped: cap exceeded");
super._mint(account, value);
}
}
pragma solidity ^0.5.0;
import "./ERC20.sol";
import "../../access/roles/MinterRole.sol";
/**
* @dev Extension of {ERC20} that adds a set of accounts with the {MinterRole},
* which have permission to mint (create) new tokens as they see fit.
*
* At construction, the deployer of the contract is the only minter.
*/
contract ERC20Mintable is ERC20, MinterRole {
/**
* @dev See {ERC20-_mint}.
*
* Requirements:
*
* - the caller must have the {MinterRole}.
*/
function mint(address account, uint256 amount) public onlyMinter returns (bool) {
_mint(account, amount);
return true;
}
}
pragma solidity ^0.5.0;
import "../../GSN/Context.sol";
import "../Roles.sol";
contract MinterRole is Context {
using Roles for Roles.Role;
event MinterAdded(address indexed account);
event MinterRemoved(address indexed account);
Roles.Role private _minters;
constructor () internal {
_addMinter(_msgSender());
}
modifier onlyMinter() {
require(isMinter(_msgSender()), "MinterRole: caller does not have the Minter role");
_;
}
function isMinter(address account) public view returns (bool) {
return _minters.has(account);
}
function addMinter(address account) public onlyMinter {
_addMinter(account);
}
function renounceMinter() public {
_removeMinter(_msgSender());
}
function _addMinter(address account) internal {
_minters.add(account);
emit MinterAdded(account);
}
function _removeMinter(address account) internal {
_minters.remove(account);
emit MinterRemoved(account);
}
}
pragma solidity ^0.5.0;
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev Give an account access to this role.
*/
function add(Role storage role, address account) internal {
require(!has(role, account), "Roles: account already has role");
role.bearer[account] = true;
}
/**
* @dev Remove an account's access to this role.
*/
function remove(Role storage role, address account) internal {
require(has(role, account), "Roles: account does not have role");
role.bearer[account] = false;
}
/**
* @dev Check if an account has this role.
* @return bool
*/
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0), "Roles: account is the zero address");
return role.bearer[account];
}
}
pragma solidity ^0.5.0;
import "../../GSN/Context.sol";
import "./ERC20.sol";
/**
* @dev Extension of {ERC20} that allows token holders to destroy both their own
* tokens and those that they have an allowance for, in a way that can be
* recognized off-chain (via event analysis).
*/
contract ERC20Burnable is Context, ERC20 {
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public {
_burn(_msgSender(), amount);
}
/**
* @dev See {ERC20-_burnFrom}.
*/
function burnFrom(address account, uint256 amount) public {
_burnFrom(account, amount);
}
}
pragma solidity 0.5.17;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/access/roles/SignerRole.sol";
import "../staking/PeakStaking.sol";
import "../PeakToken.sol";
import "../IUniswapOracle.sol";
contract PeakReward is SignerRole {
using SafeMath for uint256;
using SafeERC20 for IERC20;
event Register(address user, address referrer);
event RankChange(address user, uint256 oldRank, uint256 newRank);
event PayCommission(
address referrer,
address recipient,
address token,
uint256 amount,
uint8 level
);
event ChangedCareerValue(address user, uint256 changeAmount, bool positive);
event ReceiveRankReward(address user, uint256 peakReward);
modifier regUser(address user) {
if (!isUser[user]) {
isUser[user] = true;
emit Register(user, address(0));
}
_;
}
uint256 public constant PEAK_MINT_CAP = 5 * 10**15; // 50 million PEAK
uint256 internal constant COMMISSION_RATE = 20 * (10**16); // 20%
uint256 internal constant PEAK_PRECISION = 10**8;
uint256 internal constant USDC_PRECISION = 10**6;
uint8 internal constant COMMISSION_LEVELS = 8;
mapping(address => address) public referrerOf;
mapping(address => bool) public isUser;
mapping(address => uint256) public careerValue; // AKA DSV
mapping(address => uint256) public rankOf;
mapping(uint256 => mapping(uint256 => uint256)) public rankReward; // (beforeRank, afterRank) => rewardInPeak
mapping(address => mapping(uint256 => uint256)) public downlineRanks; // (referrer, rank) => numReferredUsersWithRank
uint256[] public commissionPercentages;
uint256[] public commissionStakeRequirements;
uint256 public mintedPeakTokens;
address public marketPeakWallet;
PeakStaking public peakStaking;
PeakToken public peakToken;
address public stablecoin;
IUniswapOracle public oracle;
constructor(
address _marketPeakWallet,
address _peakStaking,
address _peakToken,
address _stablecoin,
address _oracle
) public {
// initialize commission percentages for each level
commissionPercentages.push(10 * (10**16)); // 10%
commissionPercentages.push(4 * (10**16)); // 4%
commissionPercentages.push(2 * (10**16)); // 2%
commissionPercentages.push(1 * (10**16)); // 1%
commissionPercentages.push(1 * (10**16)); // 1%
commissionPercentages.push(1 * (10**16)); // 1%
commissionPercentages.push(5 * (10**15)); // 0.5%
commissionPercentages.push(5 * (10**15)); // 0.5%
// initialize commission stake requirements for each level
commissionStakeRequirements.push(0);
commissionStakeRequirements.push(PEAK_PRECISION.mul(2000));
commissionStakeRequirements.push(PEAK_PRECISION.mul(4000));
commissionStakeRequirements.push(PEAK_PRECISION.mul(6000));
commissionStakeRequirements.push(PEAK_PRECISION.mul(7000));
commissionStakeRequirements.push(PEAK_PRECISION.mul(8000));
commissionStakeRequirements.push(PEAK_PRECISION.mul(9000));
commissionStakeRequirements.push(PEAK_PRECISION.mul(10000));
// initialize rank rewards
for (uint256 i = 0; i < 8; i = i.add(1)) {
uint256 rewardInUSDC = 0;
for (uint256 j = i.add(1); j <= 8; j = j.add(1)) {
if (j == 1) {
rewardInUSDC = rewardInUSDC.add(USDC_PRECISION.mul(100));
} else if (j == 2) {
rewardInUSDC = rewardInUSDC.add(USDC_PRECISION.mul(300));
} else if (j == 3) {
rewardInUSDC = rewardInUSDC.add(USDC_PRECISION.mul(600));
} else if (j == 4) {
rewardInUSDC = rewardInUSDC.add(USDC_PRECISION.mul(1200));
} else if (j == 5) {
rewardInUSDC = rewardInUSDC.add(USDC_PRECISION.mul(2400));
} else if (j == 6) {
rewardInUSDC = rewardInUSDC.add(USDC_PRECISION.mul(7500));
} else if (j == 7) {
rewardInUSDC = rewardInUSDC.add(USDC_PRECISION.mul(15000));
} else {
rewardInUSDC = rewardInUSDC.add(USDC_PRECISION.mul(50000));
}
rankReward[i][j] = rewardInUSDC;
}
}
marketPeakWallet = _marketPeakWallet;
peakStaking = PeakStaking(_peakStaking);
peakToken = PeakToken(_peakToken);
stablecoin = _stablecoin;
oracle = IUniswapOracle(_oracle);
}
/**
@notice Registers a group of referrals relationship.
@param users The array of users
@param referrers The group of referrers of `users`
*/
function multiRefer(address[] calldata users, address[] calldata referrers) external onlySigner {
require(users.length == referrers.length, "PeakReward: arrays length are not equal");
for (uint256 i = 0; i < users.length; i++) {
refer(users[i], referrers[i]);
}
}
/**
@notice Registers a referral relationship
@param user The user who is being referred
@param referrer The referrer of `user`
*/
function refer(address user, address referrer) public onlySigner {
require(!isUser[user], "PeakReward: referred is already a user");
require(user != referrer, "PeakReward: can't refer self");
require(
user != address(0) && referrer != address(0),
"PeakReward: 0 address"
);
isUser[user] = true;
isUser[referrer] = true;
referrerOf[user] = referrer;
downlineRanks[referrer][0] = downlineRanks[referrer][0].add(1);
emit Register(user, referrer);
}
function canRefer(address user, address referrer)
public
view
returns (bool)
{
return
!isUser[user] &&
user != referrer &&
user != address(0) &&
referrer != address(0);
}
/**
@notice Distributes commissions to a referrer and their referrers
@param referrer The referrer who will receive commission
@param commissionToken The ERC20 token that the commission is paid in
@param rawCommission The raw commission that will be distributed amongst referrers
@param returnLeftovers If true, leftover commission is returned to the sender. If false, leftovers will be paid to MarketPeak.
*/
function payCommission(
address referrer,
address commissionToken,
uint256 rawCommission,
bool returnLeftovers
) public regUser(referrer) onlySigner returns (uint256 leftoverAmount) {
// transfer the raw commission from `msg.sender`
IERC20 token = IERC20(commissionToken);
token.safeTransferFrom(msg.sender, address(this), rawCommission);
// payout commissions to referrers of different levels
address ptr = referrer;
uint256 commissionLeft = rawCommission;
uint8 i = 0;
while (ptr != address(0) && i < COMMISSION_LEVELS) {
if (_peakStakeOf(ptr) >= commissionStakeRequirements[i]) {
// referrer has enough stake, give commission
uint256 com = rawCommission.mul(commissionPercentages[i]).div(
COMMISSION_RATE
);
if (com > commissionLeft) {
com = commissionLeft;
}
token.safeTransfer(ptr, com);
commissionLeft = commissionLeft.sub(com);
if (commissionToken == address(peakToken)) {
incrementCareerValueInPeak(ptr, com);
} else if (commissionToken == stablecoin) {
incrementCareerValueInUsdc(ptr, com);
}
emit PayCommission(referrer, ptr, commissionToken, com, i);
}
ptr = referrerOf[ptr];
i += 1;
}
// handle leftovers
if (returnLeftovers) {
// return leftovers to `msg.sender`
token.safeTransfer(msg.sender, commissionLeft);
return commissionLeft;
} else {
// give leftovers to MarketPeak wallet
token.safeTransfer(marketPeakWallet, commissionLeft);
return 0;
}
}
/**
@notice Increments a user's career value
@param user The user
@param incCV The CV increase amount, in Usdc
*/
function incrementCareerValueInUsdc(address user, uint256 incCV)
public
regUser(user)
onlySigner
{
careerValue[user] = careerValue[user].add(incCV);
emit ChangedCareerValue(user, incCV, true);
}
/**
@notice Increments a user's career value
@param user The user
@param incCVInPeak The CV increase amount, in PEAK tokens
*/
function incrementCareerValueInPeak(address user, uint256 incCVInPeak)
public
regUser(user)
onlySigner
{
uint256 peakPriceInUsdc = _getPeakPriceInUsdc();
uint256 incCVInUsdc = incCVInPeak.mul(peakPriceInUsdc).div(
PEAK_PRECISION
);
careerValue[user] = careerValue[user].add(incCVInUsdc);
emit ChangedCareerValue(user, incCVInUsdc, true);
}
/**
@notice Returns a user's rank in the PeakDeFi system based only on career value
@param user The user whose rank will be queried
*/
function cvRankOf(address user) public view returns (uint256) {
uint256 cv = careerValue[user];
if (cv < USDC_PRECISION.mul(100)) {
return 0;
} else if (cv < USDC_PRECISION.mul(250)) {
return 1;
} else if (cv < USDC_PRECISION.mul(750)) {
return 2;
} else if (cv < USDC_PRECISION.mul(1500)) {
return 3;
} else if (cv < USDC_PRECISION.mul(3000)) {
return 4;
} else if (cv < USDC_PRECISION.mul(10000)) {
return 5;
} else if (cv < USDC_PRECISION.mul(50000)) {
return 6;
} else if (cv < USDC_PRECISION.mul(150000)) {
return 7;
} else {
return 8;
}
}
function rankUp(address user) external {
// verify rank up conditions
uint256 currentRank = rankOf[user];
uint256 cvRank = cvRankOf(user);
require(cvRank > currentRank, "PeakReward: career value is not enough!");
require(downlineRanks[user][currentRank] >= 2 || currentRank == 0, "PeakReward: downlines count and requirement not passed!");
// Target rank always should be +1 rank from current rank
uint256 targetRank = currentRank + 1;
// increase user rank
rankOf[user] = targetRank;
emit RankChange(user, currentRank, targetRank);
address referrer = referrerOf[user];
if (referrer != address(0)) {
downlineRanks[referrer][targetRank] = downlineRanks[referrer][targetRank]
.add(1);
downlineRanks[referrer][currentRank] = downlineRanks[referrer][currentRank]
.sub(1);
}
// give user rank reward
uint256 rewardInPeak = rankReward[currentRank][targetRank]
.mul(PEAK_PRECISION)
.div(_getPeakPriceInUsdc());
if (mintedPeakTokens.add(rewardInPeak) <= PEAK_MINT_CAP) {
// mint if under cap, do nothing if over cap
mintedPeakTokens = mintedPeakTokens.add(rewardInPeak);
peakToken.mint(user, rewardInPeak);
emit ReceiveRankReward(user, rewardInPeak);
}
}
function canRankUp(address user) external view returns (bool) {
uint256 currentRank = rankOf[user];
uint256 cvRank = cvRankOf(user);
return
(cvRank > currentRank) &&
(downlineRanks[user][currentRank] >= 2 || currentRank == 0);
}
/**
@notice Returns a user's current staked PEAK amount, scaled by `PEAK_PRECISION`.
@param user The user whose stake will be queried
*/
function _peakStakeOf(address user) internal view returns (uint256) {
return peakStaking.userStakeAmount(user);
}
/**
@notice Returns the price of PEAK token in Usdc, scaled by `USDC_PRECISION`.
*/
function _getPeakPriceInUsdc() internal returns (uint256) {
oracle.update();
uint256 priceInUSDC = oracle.consult(address(peakToken), PEAK_PRECISION);
if (priceInUSDC == 0) {
return USDC_PRECISION.mul(3).div(10);
}
return priceInUSDC;
}
}
pragma solidity ^0.5.0;
import "../../GSN/Context.sol";
import "../Roles.sol";
contract SignerRole is Context {
using Roles for Roles.Role;
event SignerAdded(address indexed account);
event SignerRemoved(address indexed account);
Roles.Role private _signers;
constructor () internal {
_addSigner(_msgSender());
}
modifier onlySigner() {
require(isSigner(_msgSender()), "SignerRole: caller does not have the Signer role");
_;
}
function isSigner(address account) public view returns (bool) {
return _signers.has(account);
}
function addSigner(address account) public onlySigner {
_addSigner(account);
}
function renounceSigner() public {
_removeSigner(_msgSender());
}
function _addSigner(address account) internal {
_signers.add(account);
emit SignerAdded(account);
}
function _removeSigner(address account) internal {
_signers.remove(account);
emit SignerRemoved(account);
}
}
pragma solidity 0.5.17;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../reward/PeakReward.sol";
import "../PeakToken.sol";
contract PeakStaking {
using SafeMath for uint256;
using SafeERC20 for PeakToken;
event CreateStake(
uint256 idx,
address user,
address referrer,
uint256 stakeAmount,
uint256 stakeTimeInDays,
uint256 interestAmount
);
event ReceiveStakeReward(uint256 idx, address user, uint256 rewardAmount);
event WithdrawReward(uint256 idx, address user, uint256 rewardAmount);
event WithdrawStake(uint256 idx, address user);
uint256 internal constant PRECISION = 10**18;
uint256 internal constant PEAK_PRECISION = 10**8;
uint256 internal constant INTEREST_SLOPE = 2 * (10**8); // Interest rate factor drops to 0 at 5B mintedPeakTokens
uint256 internal constant BIGGER_BONUS_DIVISOR = 10**15; // biggerBonus = stakeAmount / (10 million peak)
uint256 internal constant MAX_BIGGER_BONUS = 10**17; // biggerBonus <= 10%
uint256 internal constant DAILY_BASE_REWARD = 15 * (10**14); // dailyBaseReward = 0.0015
uint256 internal constant DAILY_GROWING_REWARD = 10**12; // dailyGrowingReward = 1e-6
uint256 internal constant MAX_STAKE_PERIOD = 1000; // Max staking time is 1000 days
uint256 internal constant MIN_STAKE_PERIOD = 10; // Min staking time is 10 days
uint256 internal constant DAY_IN_SECONDS = 86400;
uint256 internal constant COMMISSION_RATE = 20 * (10**16); // 20%
uint256 internal constant REFERRAL_STAKER_BONUS = 3 * (10**16); // 3%
uint256 internal constant YEAR_IN_DAYS = 365;
uint256 public constant PEAK_MINT_CAP = 7 * 10**16; // 700 million PEAK
struct Stake {
address staker;
uint256 stakeAmount;
uint256 interestAmount;
uint256 withdrawnInterestAmount;
uint256 stakeTimestamp;
uint256 stakeTimeInDays;
bool active;
}
Stake[] public stakeList;
mapping(address => uint256) public userStakeAmount;
uint256 public mintedPeakTokens;
bool public initialized;
PeakToken public peakToken;
PeakReward public peakReward;
constructor(address _peakToken) public {
peakToken = PeakToken(_peakToken);
}
function init(address _peakReward) public {
require(!initialized, "PeakStaking: Already initialized");
initialized = true;
peakReward = PeakReward(_peakReward);
}
function stake(
uint256 stakeAmount,
uint256 stakeTimeInDays,
address referrer
) public returns (uint256 stakeIdx) {
require(
stakeTimeInDays >= MIN_STAKE_PERIOD,
"PeakStaking: stakeTimeInDays < MIN_STAKE_PERIOD"
);
require(
stakeTimeInDays <= MAX_STAKE_PERIOD,
"PeakStaking: stakeTimeInDays > MAX_STAKE_PERIOD"
);
// record stake
uint256 interestAmount = getInterestAmount(
stakeAmount,
stakeTimeInDays
);
stakeIdx = stakeList.length;
stakeList.push(
Stake({
staker: msg.sender,
stakeAmount: stakeAmount,
interestAmount: interestAmount,
withdrawnInterestAmount: 0,
stakeTimestamp: now,
stakeTimeInDays: stakeTimeInDays,
active: true
})
);
mintedPeakTokens = mintedPeakTokens.add(interestAmount);
userStakeAmount[msg.sender] = userStakeAmount[msg.sender].add(
stakeAmount
);
// transfer PEAK from msg.sender
peakToken.safeTransferFrom(msg.sender, address(this), stakeAmount);
// mint PEAK interest
peakToken.mint(address(this), interestAmount);
// handle referral
if (peakReward.canRefer(msg.sender, referrer)) {
peakReward.refer(msg.sender, referrer);
}
address actualReferrer = peakReward.referrerOf(msg.sender);
if (actualReferrer != address(0)) {
// pay referral bonus to referrer
uint256 rawCommission = interestAmount.mul(COMMISSION_RATE).div(
PRECISION
);
peakToken.mint(address(this), rawCommission);
peakToken.safeApprove(address(peakReward), rawCommission);
uint256 leftoverAmount = peakReward.payCommission(
actualReferrer,
address(peakToken),
rawCommission,
true
);
peakToken.burn(leftoverAmount);
// pay referral bonus to staker
uint256 referralStakerBonus = interestAmount
.mul(REFERRAL_STAKER_BONUS)
.div(PRECISION);
peakToken.mint(msg.sender, referralStakerBonus);
mintedPeakTokens = mintedPeakTokens.add(
rawCommission.sub(leftoverAmount).add(referralStakerBonus)
);
emit ReceiveStakeReward(stakeIdx, msg.sender, referralStakerBonus);
}
require(mintedPeakTokens <= PEAK_MINT_CAP, "PeakStaking: reached cap");
emit CreateStake(
stakeIdx,
msg.sender,
actualReferrer,
stakeAmount,
stakeTimeInDays,
interestAmount
);
}
function withdraw(uint256 stakeIdx) public {
Stake storage stakeObj = stakeList[stakeIdx];
require(
stakeObj.staker == msg.sender,
"PeakStaking: Sender not staker"
);
require(stakeObj.active, "PeakStaking: Not active");
// calculate amount that can be withdrawn
uint256 stakeTimeInSeconds = stakeObj.stakeTimeInDays.mul(
DAY_IN_SECONDS
);
uint256 withdrawAmount;
if (now >= stakeObj.stakeTimestamp.add(stakeTimeInSeconds)) {
// matured, withdraw all
withdrawAmount = stakeObj
.stakeAmount
.add(stakeObj.interestAmount)
.sub(stakeObj.withdrawnInterestAmount);
stakeObj.active = false;
stakeObj.withdrawnInterestAmount = stakeObj.interestAmount;
userStakeAmount[msg.sender] = userStakeAmount[msg.sender].sub(
stakeObj.stakeAmount
);
emit WithdrawReward(
stakeIdx,
msg.sender,
stakeObj.interestAmount.sub(stakeObj.withdrawnInterestAmount)
);
emit WithdrawStake(stakeIdx, msg.sender);
} else {
// not mature, partial withdraw
withdrawAmount = stakeObj
.interestAmount
.mul(uint256(now).sub(stakeObj.stakeTimestamp))
.div(stakeTimeInSeconds)
.sub(stakeObj.withdrawnInterestAmount);
// record withdrawal
stakeObj.withdrawnInterestAmount = stakeObj
.withdrawnInterestAmount
.add(withdrawAmount);
emit WithdrawReward(stakeIdx, msg.sender, withdrawAmount);
}
// withdraw interest to sender
peakToken.safeTransfer(msg.sender, withdrawAmount);
}
function getInterestAmount(uint256 stakeAmount, uint256 stakeTimeInDays)
public
view
returns (uint256)
{
uint256 earlyFactor = _earlyFactor(mintedPeakTokens);
uint256 biggerBonus = stakeAmount.mul(PRECISION).div(
BIGGER_BONUS_DIVISOR
);
if (biggerBonus > MAX_BIGGER_BONUS) {
biggerBonus = MAX_BIGGER_BONUS;
}
// convert yearly bigger bonus to stake time
biggerBonus = biggerBonus.mul(stakeTimeInDays).div(YEAR_IN_DAYS);
uint256 longerBonus = _longerBonus(stakeTimeInDays);
uint256 interestRate = biggerBonus.add(longerBonus).mul(earlyFactor).div(
PRECISION
);
uint256 interestAmount = stakeAmount.mul(interestRate).div(PRECISION);
return interestAmount;
}
function _longerBonus(uint256 stakeTimeInDays)
internal
pure
returns (uint256)
{
return
DAILY_BASE_REWARD.mul(stakeTimeInDays).add(
DAILY_GROWING_REWARD
.mul(stakeTimeInDays)
.mul(stakeTimeInDays.add(1))
.div(2)
);
}
function _earlyFactor(uint256 _mintedPeakTokens)
internal
pure
returns (uint256)
{
uint256 tmp = INTEREST_SLOPE.mul(_mintedPeakTokens).div(PEAK_PRECISION);
if (tmp > PRECISION) {
return 0;
}
return PRECISION.sub(tmp);
}
}
pragma solidity 0.5.17;
import "./lib/CloneFactory.sol";
import "./tokens/minime/MiniMeToken.sol";
import "./PeakDeFiFund.sol";
import "./PeakDeFiProxy.sol";
import "@openzeppelin/contracts/utils/Address.sol";
contract PeakDeFiFactory is CloneFactory {
using Address for address;
event CreateFund(address fund);
event InitFund(address fund, address proxy);
address public usdcAddr;
address payable public kyberAddr;
address payable public oneInchAddr;
address payable public peakdefiFund;
address public peakdefiLogic;
address public peakdefiLogic2;
address public peakdefiLogic3;
address public peakRewardAddr;
address public peakStakingAddr;
MiniMeTokenFactory public minimeFactory;
mapping(address => address) public fundCreator;
constructor(
address _usdcAddr,
address payable _kyberAddr,
address payable _oneInchAddr,
address payable _peakdefiFund,
address _peakdefiLogic,
address _peakdefiLogic2,
address _peakdefiLogic3,
address _peakRewardAddr,
address _peakStakingAddr,
address _minimeFactoryAddr
) public {
usdcAddr = _usdcAddr;
kyberAddr = _kyberAddr;
oneInchAddr = _oneInchAddr;
peakdefiFund = _peakdefiFund;
peakdefiLogic = _peakdefiLogic;
peakdefiLogic2 = _peakdefiLogic2;
peakdefiLogic3 = _peakdefiLogic3;
peakRewardAddr = _peakRewardAddr;
peakStakingAddr = _peakStakingAddr;
minimeFactory = MiniMeTokenFactory(_minimeFactoryAddr);
}
function createFund() external returns (PeakDeFiFund) {
// create fund
PeakDeFiFund fund = PeakDeFiFund(createClone(peakdefiFund).toPayable());
fund.initOwner();
// give PeakReward signer rights to fund
PeakReward peakReward = PeakReward(peakRewardAddr);
peakReward.addSigner(address(fund));
fundCreator[address(fund)] = msg.sender;
emit CreateFund(address(fund));
return fund;
}
function initFund1(
PeakDeFiFund fund,
string calldata reptokenName,
string calldata reptokenSymbol,
string calldata sharesName,
string calldata sharesSymbol
) external {
require(
fundCreator[address(fund)] == msg.sender,
"PeakDeFiFactory: not creator"
);
// create tokens
MiniMeToken reptoken = minimeFactory.createCloneToken(
address(0),
0,
reptokenName,
18,
reptokenSymbol,
false
);
MiniMeToken shares = minimeFactory.createCloneToken(
address(0),
0,
sharesName,
18,
sharesSymbol,
true
);
MiniMeToken peakReferralToken = minimeFactory.createCloneToken(
address(0),
0,
"Peak Referral Token",
18,
"PRT",
false
);
// transfer token ownerships to fund
reptoken.transferOwnership(address(fund));
shares.transferOwnership(address(fund));
peakReferralToken.transferOwnership(address(fund));
fund.initInternalTokens(
address(reptoken),
address(shares),
address(peakReferralToken)
);
}
function initFund2(
PeakDeFiFund fund,
address payable _devFundingAccount,
uint256 _devFundingRate,
uint256[2] calldata _phaseLengths,
address _compoundFactoryAddr
) external {
require(
fundCreator[address(fund)] == msg.sender,
"PeakDeFiFactory: not creator"
);
fund.initParams(
_devFundingAccount,
_phaseLengths,
_devFundingRate,
address(0),
usdcAddr,
kyberAddr,
_compoundFactoryAddr,
peakdefiLogic,
peakdefiLogic2,
peakdefiLogic3,
1,
oneInchAddr,
peakRewardAddr,
peakStakingAddr
);
}
function initFund3(
PeakDeFiFund fund,
uint256 _newManagerRepToken,
uint256 _maxNewManagersPerCycle,
uint256 _reptokenPrice,
uint256 _peakManagerStakeRequired,
bool _isPermissioned
) external {
require(
fundCreator[address(fund)] == msg.sender,
"PeakDeFiFactory: not creator"
);
fund.initRegistration(
_newManagerRepToken,
_maxNewManagersPerCycle,
_reptokenPrice,
_peakManagerStakeRequired,
_isPermissioned
);
}
function initFund4(
PeakDeFiFund fund,
address[] calldata _kyberTokens,
address[] calldata _compoundTokens
) external {
require(
fundCreator[address(fund)] == msg.sender,
"PeakDeFiFactory: not creator"
);
fund.initTokenListings(_kyberTokens, _compoundTokens);
// deploy and set PeakDeFiProxy
PeakDeFiProxy proxy = new PeakDeFiProxy(address(fund));
fund.setProxy(address(proxy).toPayable());
// transfer fund ownership to msg.sender
fund.transferOwnership(msg.sender);
emit InitFund(address(fund), address(proxy));
}
}
pragma solidity 0.5.17;
/*
Copyright 2016, Jordi Baylina
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/// @title MiniMeToken Contract
/// @author Jordi Baylina
/// @dev This token contract's goal is to make it easy for anyone to clone this
/// token using the token distribution at a given block, this will allow DAO's
/// and DApps to upgrade their features in a decentralized manner without
/// affecting the original token
/// @dev It is ERC20 compliant, but still needs to under go further testing.
import "@openzeppelin/contracts/ownership/Ownable.sol";
import "./TokenController.sol";
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 _amount, address _token, bytes memory _data) public;
}
/// @dev The actual token contract, the default owner is the msg.sender
/// that deploys the contract, so usually this token will be deployed by a
/// token owner contract, which Giveth will call a "Campaign"
contract MiniMeToken is Ownable {
string public name; //The Token's name: e.g. DigixDAO Tokens
uint8 public decimals; //Number of decimals of the smallest unit
string public symbol; //An identifier: e.g. REP
string public version = "MMT_0.2"; //An arbitrary versioning scheme
/// @dev `Checkpoint` is the structure that attaches a block number to a
/// given value, the block number attached is the one that last changed the
/// value
struct Checkpoint {
// `fromBlock` is the block number that the value was generated from
uint128 fromBlock;
// `value` is the amount of tokens at a specific block number
uint128 value;
}
// `parentToken` is the Token address that was cloned to produce this token;
// it will be 0x0 for a token that was not cloned
MiniMeToken public parentToken;
// `parentSnapShotBlock` is the block number from the Parent Token that was
// used to determine the initial distribution of the Clone Token
uint public parentSnapShotBlock;
// `creationBlock` is the block number that the Clone Token was created
uint public creationBlock;
// `balances` is the map that tracks the balance of each address, in this
// contract when the balance changes the block number that the change
// occurred is also included in the map
mapping (address => Checkpoint[]) balances;
// `allowed` tracks any extra transfer rights as in all ERC20 tokens
mapping (address => mapping (address => uint256)) allowed;
// Tracks the history of the `totalSupply` of the token
Checkpoint[] totalSupplyHistory;
// Flag that determines if the token is transferable or not.
bool public transfersEnabled;
// The factory used to create new clone tokens
MiniMeTokenFactory public tokenFactory;
////////////////
// Constructor
////////////////
/// @notice Constructor to create a MiniMeToken
/// @param _tokenFactory The address of the MiniMeTokenFactory contract that
/// will create the Clone token contracts, the token factory needs to be
/// deployed first
/// @param _parentToken Address of the parent token, set to 0x0 if it is a
/// new token
/// @param _parentSnapShotBlock Block of the parent token that will
/// determine the initial distribution of the clone token, set to 0 if it
/// is a new token
/// @param _tokenName Name of the new token
/// @param _decimalUnits Number of decimals of the new token
/// @param _tokenSymbol Token Symbol for the new token
/// @param _transfersEnabled If true, tokens will be able to be transferred
constructor(
address _tokenFactory,
address payable _parentToken,
uint _parentSnapShotBlock,
string memory _tokenName,
uint8 _decimalUnits,
string memory _tokenSymbol,
bool _transfersEnabled
) public {
tokenFactory = MiniMeTokenFactory(_tokenFactory);
name = _tokenName; // Set the name
decimals = _decimalUnits; // Set the decimals
symbol = _tokenSymbol; // Set the symbol
parentToken = MiniMeToken(_parentToken);
parentSnapShotBlock = _parentSnapShotBlock;
transfersEnabled = _transfersEnabled;
creationBlock = block.number;
}
///////////////////
// ERC20 Methods
///////////////////
/// @notice Send `_amount` tokens to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _amount) public returns (bool success) {
require(transfersEnabled);
doTransfer(msg.sender, _to, _amount);
return true;
}
/// @notice Send `_amount` tokens to `_to` from `_from` on the condition it
/// is approved by `_from`
/// @param _from The address holding the tokens being transferred
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return True if the transfer was successful
function transferFrom(address _from, address _to, uint256 _amount
) public returns (bool success) {
// The owner of this contract can move tokens around at will,
// this is important to recognize! Confirm that you trust the
// owner of this contract, which in most situations should be
// another open source smart contract or 0x0
if (msg.sender != owner()) {
require(transfersEnabled);
// The standard ERC 20 transferFrom functionality
require(allowed[_from][msg.sender] >= _amount);
allowed[_from][msg.sender] -= _amount;
}
doTransfer(_from, _to, _amount);
return true;
}
/// @dev This is the actual transfer function in the token contract, it can
/// only be called by other functions in this contract.
/// @param _from The address holding the tokens being transferred
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return True if the transfer was successful
function doTransfer(address _from, address _to, uint _amount
) internal {
if (_amount == 0) {
emit Transfer(_from, _to, _amount); // Follow the spec to louch the event when transfer 0
return;
}
require(parentSnapShotBlock < block.number);
// Do not allow transfer to 0x0 or the token contract itself
require((_to != address(0)) && (_to != address(this)));
// If the amount being transfered is more than the balance of the
// account the transfer throws
uint previousBalanceFrom = balanceOfAt(_from, block.number);
require(previousBalanceFrom >= _amount);
// Alerts the token owner of the transfer
if (isContract(owner())) {
require(TokenController(owner()).onTransfer(_from, _to, _amount));
}
// First update the balance array with the new value for the address
// sending the tokens
updateValueAtNow(balances[_from], previousBalanceFrom - _amount);
// Then update the balance array with the new value for the address
// receiving the tokens
uint previousBalanceTo = balanceOfAt(_to, block.number);
require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow
updateValueAtNow(balances[_to], previousBalanceTo + _amount);
// An event to make the transfer easy to find on the blockchain
emit Transfer(_from, _to, _amount);
}
/// @param _owner The address that's balance is being requested
/// @return The balance of `_owner` at the current block
function balanceOf(address _owner) public view returns (uint256 balance) {
return balanceOfAt(_owner, block.number);
}
/// @notice `msg.sender` approves `_spender` to spend `_amount` tokens on
/// its behalf. This is a modified version of the ERC20 approve function
/// to be a little bit safer
/// @param _spender The address of the account able to transfer the tokens
/// @param _amount The amount of tokens to be approved for transfer
/// @return True if the approval was successful
function approve(address _spender, uint256 _amount) public returns (bool success) {
require(transfersEnabled);
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender,0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
require((_amount == 0) || (allowed[msg.sender][_spender] == 0));
// Alerts the token owner of the approve function call
if (isContract(owner())) {
require(TokenController(owner()).onApprove(msg.sender, _spender, _amount));
}
allowed[msg.sender][_spender] = _amount;
emit Approval(msg.sender, _spender, _amount);
return true;
}
/// @dev This function makes it easy to read the `allowed[]` map
/// @param _owner The address of the account that owns the token
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens of _owner that _spender is allowed
/// to spend
function allowance(address _owner, address _spender
) public view returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/// @notice `msg.sender` approves `_spender` to send `_amount` tokens on
/// its behalf, and then a function is triggered in the contract that is
/// being approved, `_spender`. This allows users to use their tokens to
/// interact with contracts in one function call instead of two
/// @param _spender The address of the contract able to transfer the tokens
/// @param _amount The amount of tokens to be approved for transfer
/// @return True if the function call was successful
function approveAndCall(address _spender, uint256 _amount, bytes memory _extraData
) public returns (bool success) {
require(approve(_spender, _amount));
ApproveAndCallFallBack(_spender).receiveApproval(
msg.sender,
_amount,
address(this),
_extraData
);
return true;
}
/// @dev This function makes it easy to get the total number of tokens
/// @return The total number of tokens
function totalSupply() public view returns (uint) {
return totalSupplyAt(block.number);
}
////////////////
// Query balance and totalSupply in History
////////////////
/// @dev Queries the balance of `_owner` at a specific `_blockNumber`
/// @param _owner The address from which the balance will be retrieved
/// @param _blockNumber The block number when the balance is queried
/// @return The balance at `_blockNumber`
function balanceOfAt(address _owner, uint _blockNumber) public view
returns (uint) {
// These next few lines are used when the balance of the token is
// requested before a check point was ever created for this token, it
// requires that the `parentToken.balanceOfAt` be queried at the
// genesis block for that token as this contains initial balance of
// this token
if ((balances[_owner].length == 0)
|| (balances[_owner][0].fromBlock > _blockNumber)) {
if (address(parentToken) != address(0)) {
return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock));
} else {
// Has no parent
return 0;
}
// This will return the expected balance during normal situations
} else {
return getValueAt(balances[_owner], _blockNumber);
}
}
/// @notice Total amount of tokens at a specific `_blockNumber`.
/// @param _blockNumber The block number when the totalSupply is queried
/// @return The total amount of tokens at `_blockNumber`
function totalSupplyAt(uint _blockNumber) public view returns(uint) {
// These next few lines are used when the totalSupply of the token is
// requested before a check point was ever created for this token, it
// requires that the `parentToken.totalSupplyAt` be queried at the
// genesis block for this token as that contains totalSupply of this
// token at this block number.
if ((totalSupplyHistory.length == 0)
|| (totalSupplyHistory[0].fromBlock > _blockNumber)) {
if (address(parentToken) != address(0)) {
return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock));
} else {
return 0;
}
// This will return the expected totalSupply during normal situations
} else {
return getValueAt(totalSupplyHistory, _blockNumber);
}
}
////////////////
// Clone Token Method
////////////////
/// @notice Creates a new clone token with the initial distribution being
/// this token at `_snapshotBlock`
/// @param _cloneTokenName Name of the clone token
/// @param _cloneDecimalUnits Number of decimals of the smallest unit
/// @param _cloneTokenSymbol Symbol of the clone token
/// @param _snapshotBlock Block when the distribution of the parent token is
/// copied to set the initial distribution of the new clone token;
/// if the block is zero than the actual block, the current block is used
/// @param _transfersEnabled True if transfers are allowed in the clone
/// @return The address of the new MiniMeToken Contract
function createCloneToken(
string memory _cloneTokenName,
uint8 _cloneDecimalUnits,
string memory _cloneTokenSymbol,
uint _snapshotBlock,
bool _transfersEnabled
) public returns(address) {
uint snapshotBlock = _snapshotBlock;
if (snapshotBlock == 0) snapshotBlock = block.number;
MiniMeToken cloneToken = tokenFactory.createCloneToken(
address(this),
snapshotBlock,
_cloneTokenName,
_cloneDecimalUnits,
_cloneTokenSymbol,
_transfersEnabled
);
cloneToken.transferOwnership(msg.sender);
// An event to make the token easy to find on the blockchain
emit NewCloneToken(address(cloneToken), snapshotBlock);
return address(cloneToken);
}
////////////////
// Generate and destroy tokens
////////////////
/// @notice Generates `_amount` tokens that are assigned to `_owner`
/// @param _owner The address that will be assigned the new tokens
/// @param _amount The quantity of tokens generated
/// @return True if the tokens are generated correctly
function generateTokens(address _owner, uint _amount
) public onlyOwner returns (bool) {
uint curTotalSupply = totalSupply();
require(curTotalSupply + _amount >= curTotalSupply); // Check for overflow
uint previousBalanceTo = balanceOf(_owner);
require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow
updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount);
updateValueAtNow(balances[_owner], previousBalanceTo + _amount);
emit Transfer(address(0), _owner, _amount);
return true;
}
/// @notice Burns `_amount` tokens from `_owner`
/// @param _owner The address that will lose the tokens
/// @param _amount The quantity of tokens to burn
/// @return True if the tokens are burned correctly
function destroyTokens(address _owner, uint _amount
) onlyOwner public returns (bool) {
uint curTotalSupply = totalSupply();
require(curTotalSupply >= _amount);
uint previousBalanceFrom = balanceOf(_owner);
require(previousBalanceFrom >= _amount);
updateValueAtNow(totalSupplyHistory, curTotalSupply - _amount);
updateValueAtNow(balances[_owner], previousBalanceFrom - _amount);
emit Transfer(_owner, address(0), _amount);
return true;
}
////////////////
// Enable tokens transfers
////////////////
/// @notice Enables token holders to transfer their tokens freely if true
/// @param _transfersEnabled True if transfers are allowed in the clone
function enableTransfers(bool _transfersEnabled) public onlyOwner {
transfersEnabled = _transfersEnabled;
}
////////////////
// Internal helper functions to query and set a value in a snapshot array
////////////////
/// @dev `getValueAt` retrieves the number of tokens at a given block number
/// @param checkpoints The history of values being queried
/// @param _block The block number to retrieve the value at
/// @return The number of tokens being queried
function getValueAt(Checkpoint[] storage checkpoints, uint _block
) view internal returns (uint) {
if (checkpoints.length == 0) return 0;
// Shortcut for the actual value
if (_block >= checkpoints[checkpoints.length-1].fromBlock)
return checkpoints[checkpoints.length-1].value;
if (_block < checkpoints[0].fromBlock) return 0;
// Binary search of the value in the array
uint min = 0;
uint max = checkpoints.length-1;
while (max > min) {
uint mid = (max + min + 1)/ 2;
if (checkpoints[mid].fromBlock<=_block) {
min = mid;
} else {
max = mid-1;
}
}
return checkpoints[min].value;
}
/// @dev `updateValueAtNow` used to update the `balances` map and the
/// `totalSupplyHistory`
/// @param checkpoints The history of data being updated
/// @param _value The new number of tokens
function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value
) internal {
if ((checkpoints.length == 0)
|| (checkpoints[checkpoints.length -1].fromBlock < block.number)) {
Checkpoint storage newCheckPoint = checkpoints[ checkpoints.length++ ];
newCheckPoint.fromBlock = uint128(block.number);
newCheckPoint.value = uint128(_value);
} else {
Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length-1];
oldCheckPoint.value = uint128(_value);
}
}
/// @dev Internal function to determine if an address is a contract
/// @param _addr The address being queried
/// @return True if `_addr` is a contract
function isContract(address _addr) view internal returns(bool) {
uint size;
if (_addr == address(0)) return false;
assembly {
size := extcodesize(_addr)
}
return size>0;
}
/// @dev Helper function to return a min betwen the two uints
function min(uint a, uint b) pure internal returns (uint) {
return a < b ? a : b;
}
/// @notice The fallback function: If the contract's owner has not been
/// set to 0, then the `proxyPayment` method is called which relays the
/// ether and creates tokens as described in the token owner contract
function () external payable {
require(isContract(owner()));
require(TokenController(owner()).proxyPayment.value(msg.value)(msg.sender));
}
//////////
// Safety Methods
//////////
/// @notice This method can be used by the owner to extract mistakenly
/// sent tokens to this contract.
/// @param _token The address of the token contract that you want to recover
/// set to 0 in case you want to extract ether.
function claimTokens(address payable _token) public onlyOwner {
if (_token == address(0)) {
address(uint160(owner())).transfer(address(this).balance);
return;
}
MiniMeToken token = MiniMeToken(_token);
uint balance = token.balanceOf(address(this));
require(token.transfer(owner(), balance));
emit ClaimedTokens(_token, owner(), balance);
}
////////////////
// Events
////////////////
event ClaimedTokens(address indexed _token, address indexed _owner, uint _amount);
event Transfer(address indexed _from, address indexed _to, uint256 _amount);
event NewCloneToken(address indexed _cloneToken, uint _snapshotBlock);
event Approval(
address indexed _owner,
address indexed _spender,
uint256 _amount
);
}
////////////////
// MiniMeTokenFactory
////////////////
/// @dev This contract is used to generate clone contracts from a contract.
/// In solidity this is the way to create a contract from a contract of the
/// same class
contract MiniMeTokenFactory {
event CreatedToken(string symbol, address addr);
/// @notice Update the DApp by creating a new token with new functionalities
/// the msg.sender becomes the owner of this clone token
/// @param _parentToken Address of the token being cloned
/// @param _snapshotBlock Block of the parent token that will
/// determine the initial distribution of the clone token
/// @param _tokenName Name of the new token
/// @param _decimalUnits Number of decimals of the new token
/// @param _tokenSymbol Token Symbol for the new token
/// @param _transfersEnabled If true, tokens will be able to be transferred
/// @return The address of the new token contract
function createCloneToken(
address payable _parentToken,
uint _snapshotBlock,
string memory _tokenName,
uint8 _decimalUnits,
string memory _tokenSymbol,
bool _transfersEnabled
) public returns (MiniMeToken) {
MiniMeToken newToken = new MiniMeToken(
address(this),
_parentToken,
_snapshotBlock,
_tokenName,
_decimalUnits,
_tokenSymbol,
_transfersEnabled
);
newToken.transferOwnership(msg.sender);
emit CreatedToken(_tokenSymbol, address(newToken));
return newToken;
}
}
pragma solidity 0.5.17;
/// @dev The token controller contract must implement these functions
contract TokenController {
/// @notice Called when `_owner` sends ether to the MiniMe Token contract
/// @param _owner The address that sent the ether to create tokens
/// @return True if the ether is accepted, false if it throws
function proxyPayment(address _owner) public payable returns(bool);
/// @notice Notifies the controller about a token transfer allowing the
/// controller to react if desired
/// @param _from The origin of the transfer
/// @param _to The destination of the transfer
/// @param _amount The amount of the transfer
/// @return False if the controller does not authorize the transfer
function onTransfer(address _from, address _to, uint _amount) public returns(bool);
/// @notice Notifies the controller about an approval allowing the
/// controller to react if desired
/// @param _owner The address that calls `approve()`
/// @param _spender The spender in the `approve()` call
/// @param _amount The amount in the `approve()` call
/// @return False if the controller does not authorize the approval
function onApprove(address _owner, address _spender, uint _amount) public
returns(bool);
}
pragma solidity 0.5.17;
import "./PeakDeFiStorage.sol";
import "./derivatives/CompoundOrderFactory.sol";
/**
* @title The main smart contract of the PeakDeFi hedge fund.
* @author Zefram Lou (Zebang Liu)
*/
contract PeakDeFiFund is
PeakDeFiStorage,
Utils(address(0), address(0), address(0)),
TokenController
{
/**
* @notice Passes if the fund is ready for migrating to the next version
*/
modifier readyForUpgradeMigration {
require(hasFinalizedNextVersion == true);
require(
now >
startTimeOfCyclePhase.add(
phaseLengths[uint256(CyclePhase.Intermission)]
)
);
_;
}
/**
* Meta functions
*/
function initParams(
address payable _devFundingAccount,
uint256[2] calldata _phaseLengths,
uint256 _devFundingRate,
address payable _previousVersion,
address _usdcAddr,
address payable _kyberAddr,
address _compoundFactoryAddr,
address _peakdefiLogic,
address _peakdefiLogic2,
address _peakdefiLogic3,
uint256 _startCycleNumber,
address payable _oneInchAddr,
address _peakRewardAddr,
address _peakStakingAddr
) external {
require(proxyAddr == address(0));
devFundingAccount = _devFundingAccount;
phaseLengths = _phaseLengths;
devFundingRate = _devFundingRate;
cyclePhase = CyclePhase.Intermission;
compoundFactoryAddr = _compoundFactoryAddr;
peakdefiLogic = _peakdefiLogic;
peakdefiLogic2 = _peakdefiLogic2;
peakdefiLogic3 = _peakdefiLogic3;
previousVersion = _previousVersion;
cycleNumber = _startCycleNumber;
peakReward = PeakReward(_peakRewardAddr);
peakStaking = PeakStaking(_peakStakingAddr);
USDC_ADDR = _usdcAddr;
KYBER_ADDR = _kyberAddr;
ONEINCH_ADDR = _oneInchAddr;
usdc = ERC20Detailed(_usdcAddr);
kyber = KyberNetwork(_kyberAddr);
__initReentrancyGuard();
}
function initOwner() external {
require(proxyAddr == address(0));
_transferOwnership(msg.sender);
}
function initInternalTokens(
address payable _repAddr,
address payable _sTokenAddr,
address payable _peakReferralTokenAddr
) external onlyOwner {
require(controlTokenAddr == address(0));
require(_repAddr != address(0));
controlTokenAddr = _repAddr;
shareTokenAddr = _sTokenAddr;
cToken = IMiniMeToken(_repAddr);
sToken = IMiniMeToken(_sTokenAddr);
peakReferralToken = IMiniMeToken(_peakReferralTokenAddr);
}
function initRegistration(
uint256 _newManagerRepToken,
uint256 _maxNewManagersPerCycle,
uint256 _reptokenPrice,
uint256 _peakManagerStakeRequired,
bool _isPermissioned
) external onlyOwner {
require(_newManagerRepToken > 0 && newManagerRepToken == 0);
newManagerRepToken = _newManagerRepToken;
maxNewManagersPerCycle = _maxNewManagersPerCycle;
reptokenPrice = _reptokenPrice;
peakManagerStakeRequired = _peakManagerStakeRequired;
isPermissioned = _isPermissioned;
}
function initTokenListings(
address[] calldata _kyberTokens,
address[] calldata _compoundTokens
) external onlyOwner {
// May only initialize once
require(!hasInitializedTokenListings);
hasInitializedTokenListings = true;
uint256 i;
for (i = 0; i < _kyberTokens.length; i++) {
isKyberToken[_kyberTokens[i]] = true;
}
CompoundOrderFactory factory = CompoundOrderFactory(compoundFactoryAddr);
for (i = 0; i < _compoundTokens.length; i++) {
require(factory.tokenIsListed(_compoundTokens[i]));
isCompoundToken[_compoundTokens[i]] = true;
}
}
/**
* @notice Used during deployment to set the PeakDeFiProxy contract address.
* @param _proxyAddr the proxy's address
*/
function setProxy(address payable _proxyAddr) external onlyOwner {
require(_proxyAddr != address(0));
require(proxyAddr == address(0));
proxyAddr = _proxyAddr;
proxy = PeakDeFiProxyInterface(_proxyAddr);
}
/**
* Upgrading functions
*/
/**
* @notice Allows the developer to propose a candidate smart contract for the fund to upgrade to.
* The developer may change the candidate during the Intermission phase.
* @param _candidate the address of the candidate smart contract
* @return True if successfully changed candidate, false otherwise.
*/
function developerInitiateUpgrade(address payable _candidate)
public
returns (bool _success)
{
(bool success, bytes memory result) = peakdefiLogic3.delegatecall(
abi.encodeWithSelector(
this.developerInitiateUpgrade.selector,
_candidate
)
);
if (!success) {
return false;
}
return abi.decode(result, (bool));
}
/**
* @notice Transfers ownership of RepToken & Share token contracts to the next version. Also updates PeakDeFiFund's
* address in PeakDeFiProxy.
*/
function migrateOwnedContractsToNextVersion()
public
nonReentrant
readyForUpgradeMigration
{
cToken.transferOwnership(nextVersion);
sToken.transferOwnership(nextVersion);
peakReferralToken.transferOwnership(nextVersion);
proxy.updatePeakDeFiFundAddress();
}
/**
* @notice Transfers assets to the next version.
* @param _assetAddress the address of the asset to be transferred. Use ETH_TOKEN_ADDRESS to transfer Ether.
*/
function transferAssetToNextVersion(address _assetAddress)
public
nonReentrant
readyForUpgradeMigration
isValidToken(_assetAddress)
{
if (_assetAddress == address(ETH_TOKEN_ADDRESS)) {
nextVersion.transfer(address(this).balance);
} else {
ERC20Detailed token = ERC20Detailed(_assetAddress);
token.safeTransfer(nextVersion, token.balanceOf(address(this)));
}
}
/**
* Getters
*/
/**
* @notice Returns the length of the user's investments array.
* @return length of the user's investments array
*/
function investmentsCount(address _userAddr)
public
view
returns (uint256 _count)
{
return userInvestments[_userAddr].length;
}
/**
* @notice Returns the length of the user's compound orders array.
* @return length of the user's compound orders array
*/
function compoundOrdersCount(address _userAddr)
public
view
returns (uint256 _count)
{
return userCompoundOrders[_userAddr].length;
}
/**
* @notice Returns the phaseLengths array.
* @return the phaseLengths array
*/
function getPhaseLengths()
public
view
returns (uint256[2] memory _phaseLengths)
{
return phaseLengths;
}
/**
* @notice Returns the commission balance of `_manager`
* @return the commission balance and the received penalty, denoted in USDC
*/
function commissionBalanceOf(address _manager)
public
returns (uint256 _commission, uint256 _penalty)
{
(bool success, bytes memory result) = peakdefiLogic3.delegatecall(
abi.encodeWithSelector(this.commissionBalanceOf.selector, _manager)
);
if (!success) {
return (0, 0);
}
return abi.decode(result, (uint256, uint256));
}
/**
* @notice Returns the commission amount received by `_manager` in the `_cycle`th cycle
* @return the commission amount and the received penalty, denoted in USDC
*/
function commissionOfAt(address _manager, uint256 _cycle)
public
returns (uint256 _commission, uint256 _penalty)
{
(bool success, bytes memory result) = peakdefiLogic3.delegatecall(
abi.encodeWithSelector(
this.commissionOfAt.selector,
_manager,
_cycle
)
);
if (!success) {
return (0, 0);
}
return abi.decode(result, (uint256, uint256));
}
/**
* Parameter setters
*/
/**
* @notice Changes the address to which the developer fees will be sent. Only callable by owner.
* @param _newAddr the new developer fee address
*/
function changeDeveloperFeeAccount(address payable _newAddr)
public
onlyOwner
{
require(_newAddr != address(0) && _newAddr != address(this));
devFundingAccount = _newAddr;
}
/**
* @notice Changes the proportion of fund balance sent to the developers each cycle. May only decrease. Only callable by owner.
* @param _newProp the new proportion, fixed point decimal
*/
function changeDeveloperFeeRate(uint256 _newProp) public onlyOwner {
require(_newProp < PRECISION);
require(_newProp < devFundingRate);
devFundingRate = _newProp;
}
/**
* @notice Allows managers to invest in a token. Only callable by owner.
* @param _token address of the token to be listed
*/
function listKyberToken(address _token) public onlyOwner {
isKyberToken[_token] = true;
}
/**
* @notice Allows managers to invest in a Compound token. Only callable by owner.
* @param _token address of the Compound token to be listed
*/
function listCompoundToken(address _token) public onlyOwner {
CompoundOrderFactory factory = CompoundOrderFactory(
compoundFactoryAddr
);
require(factory.tokenIsListed(_token));
isCompoundToken[_token] = true;
}
/**
* @notice Moves the fund to the next phase in the investment cycle.
*/
function nextPhase() public {
(bool success, ) = peakdefiLogic3.delegatecall(
abi.encodeWithSelector(this.nextPhase.selector)
);
if (!success) {
revert();
}
}
/**
* Manager registration
*/
/**
* @notice Registers `msg.sender` as a manager, using USDC as payment. The more one pays, the more RepToken one gets.
* There's a max RepToken amount that can be bought, and excess payment will be sent back to sender.
*/
function registerWithUSDC() public {
(bool success, ) = peakdefiLogic2.delegatecall(
abi.encodeWithSelector(this.registerWithUSDC.selector)
);
if (!success) {
revert();
}
}
/**
* @notice Registers `msg.sender` as a manager, using ETH as payment. The more one pays, the more RepToken one gets.
* There's a max RepToken amount that can be bought, and excess payment will be sent back to sender.
*/
function registerWithETH() public payable {
(bool success, ) = peakdefiLogic2.delegatecall(
abi.encodeWithSelector(this.registerWithETH.selector)
);
if (!success) {
revert();
}
}
/**
* @notice Registers `msg.sender` as a manager, using tokens as payment. The more one pays, the more RepToken one gets.
* There's a max RepToken amount that can be bought, and excess payment will be sent back to sender.
* @param _token the token to be used for payment
* @param _donationInTokens the amount of tokens to be used for registration, should use the token's native decimals
*/
function registerWithToken(address _token, uint256 _donationInTokens)
public
{
(bool success, ) = peakdefiLogic2.delegatecall(
abi.encodeWithSelector(
this.registerWithToken.selector,
_token,
_donationInTokens
)
);
if (!success) {
revert();
}
}
/**
* Intermission phase functions
*/
/**
* @notice Deposit Ether into the fund. Ether will be converted into USDC.
*/
function depositEther(address _referrer) public payable {
(bool success, ) = peakdefiLogic2.delegatecall(
abi.encodeWithSelector(this.depositEther.selector, _referrer)
);
if (!success) {
revert();
}
}
function depositEtherAdvanced(
bool _useKyber,
bytes calldata _calldata,
address _referrer
) external payable {
(bool success, ) = peakdefiLogic2.delegatecall(
abi.encodeWithSelector(
this.depositEtherAdvanced.selector,
_useKyber,
_calldata,
_referrer
)
);
if (!success) {
revert();
}
}
/**
* @notice Deposit USDC Stablecoin into the fund.
* @param _usdcAmount The amount of USDC to be deposited. May be different from actual deposited amount.
*/
function depositUSDC(uint256 _usdcAmount, address _referrer) public {
(bool success, ) = peakdefiLogic2.delegatecall(
abi.encodeWithSelector(
this.depositUSDC.selector,
_usdcAmount,
_referrer
)
);
if (!success) {
revert();
}
}
/**
* @notice Deposit ERC20 tokens into the fund. Tokens will be converted into USDC.
* @param _tokenAddr the address of the token to be deposited
* @param _tokenAmount The amount of tokens to be deposited. May be different from actual deposited amount.
*/
function depositToken(
address _tokenAddr,
uint256 _tokenAmount,
address _referrer
) public {
(bool success, ) = peakdefiLogic2.delegatecall(
abi.encodeWithSelector(
this.depositToken.selector,
_tokenAddr,
_tokenAmount,
_referrer
)
);
if (!success) {
revert();
}
}
function depositTokenAdvanced(
address _tokenAddr,
uint256 _tokenAmount,
bool _useKyber,
bytes calldata _calldata,
address _referrer
) external {
(bool success, ) = peakdefiLogic2.delegatecall(
abi.encodeWithSelector(
this.depositTokenAdvanced.selector,
_tokenAddr,
_tokenAmount,
_useKyber,
_calldata,
_referrer
)
);
if (!success) {
revert();
}
}
/**
* @notice Withdraws Ether by burning Shares.
* @param _amountInUSDC Amount of funds to be withdrawn expressed in USDC. Fixed-point decimal. May be different from actual amount.
*/
function withdrawEther(uint256 _amountInUSDC) external {
(bool success, ) = peakdefiLogic2.delegatecall(
abi.encodeWithSelector(this.withdrawEther.selector, _amountInUSDC)
);
if (!success) {
revert();
}
}
function withdrawEtherAdvanced(
uint256 _amountInUSDC,
bool _useKyber,
bytes calldata _calldata
) external {
(bool success, ) = peakdefiLogic2.delegatecall(
abi.encodeWithSelector(
this.withdrawEtherAdvanced.selector,
_amountInUSDC,
_useKyber,
_calldata
)
);
if (!success) {
revert();
}
}
/**
* @notice Withdraws Ether by burning Shares.
* @param _amountInUSDC Amount of funds to be withdrawn expressed in USDC. Fixed-point decimal. May be different from actual amount.
*/
function withdrawUSDC(uint256 _amountInUSDC) public {
(bool success, ) = peakdefiLogic2.delegatecall(
abi.encodeWithSelector(this.withdrawUSDC.selector, _amountInUSDC)
);
if (!success) {
revert();
}
}
/**
* @notice Withdraws funds by burning Shares, and converts the funds into the specified token using Kyber Network.
* @param _tokenAddr the address of the token to be withdrawn into the caller's account
* @param _amountInUSDC The amount of funds to be withdrawn expressed in USDC. Fixed-point decimal. May be different from actual amount.
*/
function withdrawToken(address _tokenAddr, uint256 _amountInUSDC) external {
(bool success, ) = peakdefiLogic2.delegatecall(
abi.encodeWithSelector(
this.withdrawToken.selector,
_tokenAddr,
_amountInUSDC
)
);
if (!success) {
revert();
}
}
function withdrawTokenAdvanced(
address _tokenAddr,
uint256 _amountInUSDC,
bool _useKyber,
bytes calldata _calldata
) external {
(bool success, ) = peakdefiLogic2.delegatecall(
abi.encodeWithSelector(
this.withdrawTokenAdvanced.selector,
_tokenAddr,
_amountInUSDC,
_useKyber,
_calldata
)
);
if (!success) {
revert();
}
}
/**
* @notice Redeems commission.
*/
function redeemCommission(bool _inShares) public {
(bool success, ) = peakdefiLogic3.delegatecall(
abi.encodeWithSelector(this.redeemCommission.selector, _inShares)
);
if (!success) {
revert();
}
}
/**
* @notice Redeems commission for a particular cycle.
* @param _inShares true to redeem in PeakDeFi Shares, false to redeem in USDC
* @param _cycle the cycle for which the commission will be redeemed.
* Commissions for a cycle will be redeemed during the Intermission phase of the next cycle, so _cycle must < cycleNumber.
*/
function redeemCommissionForCycle(bool _inShares, uint256 _cycle) public {
(bool success, ) = peakdefiLogic3.delegatecall(
abi.encodeWithSelector(
this.redeemCommissionForCycle.selector,
_inShares,
_cycle
)
);
if (!success) {
revert();
}
}
/**
* @notice Sells tokens left over due to manager not selling or KyberNetwork not having enough volume. Callable by anyone. Money goes to developer.
* @param _tokenAddr address of the token to be sold
* @param _calldata the 1inch trade call data
*/
function sellLeftoverToken(address _tokenAddr, bytes calldata _calldata)
external
{
(bool success, ) = peakdefiLogic2.delegatecall(
abi.encodeWithSelector(
this.sellLeftoverToken.selector,
_tokenAddr,
_calldata
)
);
if (!success) {
revert();
}
}
/**
* @notice Sells CompoundOrder left over due to manager not selling or KyberNetwork not having enough volume. Callable by anyone. Money goes to developer.
* @param _orderAddress address of the CompoundOrder to be sold
*/
function sellLeftoverCompoundOrder(address payable _orderAddress) public {
(bool success, ) = peakdefiLogic2.delegatecall(
abi.encodeWithSelector(
this.sellLeftoverCompoundOrder.selector,
_orderAddress
)
);
if (!success) {
revert();
}
}
/**
* @notice Burns the RepToken balance of a manager who has been inactive for a certain number of cycles
* @param _deadman the manager whose RepToken balance will be burned
*/
function burnDeadman(address _deadman) public {
(bool success, ) = peakdefiLogic.delegatecall(
abi.encodeWithSelector(this.burnDeadman.selector, _deadman)
);
if (!success) {
revert();
}
}
/**
* Manage phase functions
*/
function createInvestmentWithSignature(
address _tokenAddress,
uint256 _stake,
uint256 _maxPrice,
bytes calldata _calldata,
bool _useKyber,
address _manager,
uint256 _salt,
bytes calldata _signature
) external {
(bool success, ) = peakdefiLogic.delegatecall(
abi.encodeWithSelector(
this.createInvestmentWithSignature.selector,
_tokenAddress,
_stake,
_maxPrice,
_calldata,
_useKyber,
_manager,
_salt,
_signature
)
);
if (!success) {
revert();
}
}
function sellInvestmentWithSignature(
uint256 _investmentId,
uint256 _tokenAmount,
uint256 _minPrice,
uint256 _maxPrice,
bytes calldata _calldata,
bool _useKyber,
address _manager,
uint256 _salt,
bytes calldata _signature
) external {
(bool success, ) = peakdefiLogic.delegatecall(
abi.encodeWithSelector(
this.sellInvestmentWithSignature.selector,
_investmentId,
_tokenAmount,
_minPrice,
_maxPrice,
_calldata,
_useKyber,
_manager,
_salt,
_signature
)
);
if (!success) {
revert();
}
}
function createCompoundOrderWithSignature(
bool _orderType,
address _tokenAddress,
uint256 _stake,
uint256 _minPrice,
uint256 _maxPrice,
address _manager,
uint256 _salt,
bytes calldata _signature
) external {
(bool success, ) = peakdefiLogic.delegatecall(
abi.encodeWithSelector(
this.createCompoundOrderWithSignature.selector,
_orderType,
_tokenAddress,
_stake,
_minPrice,
_maxPrice,
_manager,
_salt,
_signature
)
);
if (!success) {
revert();
}
}
function sellCompoundOrderWithSignature(
uint256 _orderId,
uint256 _minPrice,
uint256 _maxPrice,
address _manager,
uint256 _salt,
bytes calldata _signature
) external {
(bool success, ) = peakdefiLogic.delegatecall(
abi.encodeWithSelector(
this.sellCompoundOrderWithSignature.selector,
_orderId,
_minPrice,
_maxPrice,
_manager,
_salt,
_signature
)
);
if (!success) {
revert();
}
}
function repayCompoundOrderWithSignature(
uint256 _orderId,
uint256 _repayAmountInUSDC,
address _manager,
uint256 _salt,
bytes calldata _signature
) external {
(bool success, ) = peakdefiLogic.delegatecall(
abi.encodeWithSelector(
this.repayCompoundOrderWithSignature.selector,
_orderId,
_repayAmountInUSDC,
_manager,
_salt,
_signature
)
);
if (!success) {
revert();
}
}
/**
* @notice Creates a new investment for an ERC20 token.
* @param _tokenAddress address of the ERC20 token contract
* @param _stake amount of RepTokens to be staked in support of the investment
* @param _maxPrice the maximum price for the trade
*/
function createInvestment(
address _tokenAddress,
uint256 _stake,
uint256 _maxPrice
) public {
(bool success, ) = peakdefiLogic.delegatecall(
abi.encodeWithSelector(
this.createInvestment.selector,
_tokenAddress,
_stake,
_maxPrice
)
);
if (!success) {
revert();
}
}
/**
* @notice Creates a new investment for an ERC20 token.
* @param _tokenAddress address of the ERC20 token contract
* @param _stake amount of RepTokens to be staked in support of the investment
* @param _maxPrice the maximum price for the trade
* @param _calldata calldata for 1inch trading
* @param _useKyber true for Kyber Network, false for 1inch
*/
function createInvestmentV2(
address _sender,
address _tokenAddress,
uint256 _stake,
uint256 _maxPrice,
bytes memory _calldata,
bool _useKyber
) public {
(bool success, ) = peakdefiLogic.delegatecall(
abi.encodeWithSelector(
this.createInvestmentV2.selector,
_sender,
_tokenAddress,
_stake,
_maxPrice,
_calldata,
_useKyber
)
);
if (!success) {
revert();
}
}
/**
* @notice Called by user to sell the assets an investment invested in. Returns the staked RepToken plus rewards/penalties to the user.
* The user can sell only part of the investment by changing _tokenAmount.
* @dev When selling only part of an investment, the old investment would be "fully" sold and a new investment would be created with
* the original buy price and however much tokens that are not sold.
* @param _investmentId the ID of the investment
* @param _tokenAmount the amount of tokens to be sold.
* @param _minPrice the minimum price for the trade
*/
function sellInvestmentAsset(
uint256 _investmentId,
uint256 _tokenAmount,
uint256 _minPrice
) public {
(bool success, ) = peakdefiLogic.delegatecall(
abi.encodeWithSelector(
this.sellInvestmentAsset.selector,
_investmentId,
_tokenAmount,
_minPrice
)
);
if (!success) {
revert();
}
}
/**
* @notice Called by user to sell the assets an investment invested in. Returns the staked RepToken plus rewards/penalties to the user.
* The user can sell only part of the investment by changing _tokenAmount.
* @dev When selling only part of an investment, the old investment would be "fully" sold and a new investment would be created with
* the original buy price and however much tokens that are not sold.
* @param _investmentId the ID of the investment
* @param _tokenAmount the amount of tokens to be sold.
* @param _minPrice the minimum price for the trade
*/
function sellInvestmentAssetV2(
address _sender,
uint256 _investmentId,
uint256 _tokenAmount,
uint256 _minPrice,
bytes memory _calldata,
bool _useKyber
) public {
(bool success, ) = peakdefiLogic.delegatecall(
abi.encodeWithSelector(
this.sellInvestmentAssetV2.selector,
_sender,
_investmentId,
_tokenAmount,
_minPrice,
_calldata,
_useKyber
)
);
if (!success) {
revert();
}
}
/**
* @notice Creates a new Compound order to either short or leverage long a token.
* @param _orderType true for a short order, false for a levarage long order
* @param _tokenAddress address of the Compound token to be traded
* @param _stake amount of RepTokens to be staked
* @param _minPrice the minimum token price for the trade
* @param _maxPrice the maximum token price for the trade
*/
function createCompoundOrder(
address _sender,
bool _orderType,
address _tokenAddress,
uint256 _stake,
uint256 _minPrice,
uint256 _maxPrice
) public {
(bool success, ) = peakdefiLogic.delegatecall(
abi.encodeWithSelector(
this.createCompoundOrder.selector,
_sender,
_orderType,
_tokenAddress,
_stake,
_minPrice,
_maxPrice
)
);
if (!success) {
revert();
}
}
/**
* @notice Sells a compound order
* @param _orderId the ID of the order to be sold (index in userCompoundOrders[msg.sender])
* @param _minPrice the minimum token price for the trade
* @param _maxPrice the maximum token price for the trade
*/
function sellCompoundOrder(
address _sender,
uint256 _orderId,
uint256 _minPrice,
uint256 _maxPrice
) public {
(bool success, ) = peakdefiLogic.delegatecall(
abi.encodeWithSelector(
this.sellCompoundOrder.selector,
_sender,
_orderId,
_minPrice,
_maxPrice
)
);
if (!success) {
revert();
}
}
/**
* @notice Repys debt for a Compound order to prevent the collateral ratio from dropping below threshold.
* @param _orderId the ID of the Compound order
* @param _repayAmountInUSDC amount of USDC to use for repaying debt
*/
function repayCompoundOrder(
address _sender,
uint256 _orderId,
uint256 _repayAmountInUSDC
) public {
(bool success, ) = peakdefiLogic.delegatecall(
abi.encodeWithSelector(
this.repayCompoundOrder.selector,
_sender,
_orderId,
_repayAmountInUSDC
)
);
if (!success) {
revert();
}
}
/**
* @notice Emergency exit the tokens from order contract during intermission stage
* @param _sender the address of trader, who created the order
* @param _orderId the ID of the Compound order
* @param _tokenAddr the address of token which should be transferred
* @param _receiver the address of receiver
*/
function emergencyExitCompoundTokens(
address _sender,
uint256 _orderId,
address _tokenAddr,
address _receiver
) public onlyOwner {
(bool success, ) = peakdefiLogic.delegatecall(
abi.encodeWithSelector(
this.emergencyExitCompoundTokens.selector,
_sender,
_orderId,
_tokenAddr,
_receiver
)
);
if (!success) {
revert();
}
}
/**
* Internal use functions
*/
// MiniMe TokenController functions, not used right now
/**
* @notice Called when `_owner` sends ether to the MiniMe Token contract
* @return True if the ether is accepted, false if it throws
*/
function proxyPayment(
address /*_owner*/
) public payable returns (bool) {
return false;
}
/**
* @notice Notifies the controller about a token transfer allowing the
* controller to react if desired
* @return False if the controller does not authorize the transfer
*/
function onTransfer(
address, /*_from*/
address, /*_to*/
uint256 /*_amount*/
) public returns (bool) {
return true;
}
/**
* @notice Notifies the controller about an approval allowing the
* controller to react if desired
* @return False if the controller does not authorize the approval
*/
function onApprove(
address, /*_owner*/
address, /*_spender*/
uint256 /*_amount*/
) public returns (bool) {
return true;
}
function() external payable {}
/**
PeakDeFi
*/
/**
* @notice Returns the commission balance of `_referrer`
* @return the commission balance and the received penalty, denoted in USDC
*/
function peakReferralCommissionBalanceOf(address _referrer)
public
returns (uint256 _commission)
{
(bool success, bytes memory result) = peakdefiLogic3.delegatecall(
abi.encodeWithSelector(
this.peakReferralCommissionBalanceOf.selector,
_referrer
)
);
if (!success) {
return 0;
}
return abi.decode(result, (uint256));
}
/**
* @notice Returns the commission amount received by `_referrer` in the `_cycle`th cycle
* @return the commission amount and the received penalty, denoted in USDC
*/
function peakReferralCommissionOfAt(address _referrer, uint256 _cycle)
public
returns (uint256 _commission)
{
(bool success, bytes memory result) = peakdefiLogic3.delegatecall(
abi.encodeWithSelector(
this.peakReferralCommissionOfAt.selector,
_referrer,
_cycle
)
);
if (!success) {
return 0;
}
return abi.decode(result, (uint256));
}
/**
* @notice Redeems commission.
*/
function peakReferralRedeemCommission() public {
(bool success, ) = peakdefiLogic3.delegatecall(
abi.encodeWithSelector(this.peakReferralRedeemCommission.selector)
);
if (!success) {
revert();
}
}
/**
* @notice Redeems commission for a particular cycle.
* @param _cycle the cycle for which the commission will be redeemed.
* Commissions for a cycle will be redeemed during the Intermission phase of the next cycle, so _cycle must < cycleNumber.
*/
function peakReferralRedeemCommissionForCycle(uint256 _cycle) public {
(bool success, ) = peakdefiLogic3.delegatecall(
abi.encodeWithSelector(
this.peakReferralRedeemCommissionForCycle.selector,
_cycle
)
);
if (!success) {
revert();
}
}
/**
* @notice Changes the required PEAK stake of a new manager. Only callable by owner.
* @param _newValue the new value
*/
function peakChangeManagerStakeRequired(uint256 _newValue)
public
onlyOwner
{
peakManagerStakeRequired = _newValue;
}
}
pragma solidity 0.5.17;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/ownership/Ownable.sol";
import "./lib/ReentrancyGuard.sol";
import "./interfaces/IMiniMeToken.sol";
import "./tokens/minime/TokenController.sol";
import "./Utils.sol";
import "./PeakDeFiProxyInterface.sol";
import "./peak/reward/PeakReward.sol";
import "./peak/staking/PeakStaking.sol";
/**
* @title The storage layout of PeakDeFiFund
* @author Zefram Lou (Zebang Liu)
*/
contract PeakDeFiStorage is Ownable, ReentrancyGuard {
using SafeMath for uint256;
enum CyclePhase {Intermission, Manage}
enum VoteDirection {Empty, For, Against}
enum Subchunk {Propose, Vote}
struct Investment {
address tokenAddress;
uint256 cycleNumber;
uint256 stake;
uint256 tokenAmount;
uint256 buyPrice; // token buy price in 18 decimals in USDC
uint256 sellPrice; // token sell price in 18 decimals in USDC
uint256 buyTime;
uint256 buyCostInUSDC;
bool isSold;
}
// Fund parameters
uint256 public constant COMMISSION_RATE = 15 * (10**16); // The proportion of profits that gets distributed to RepToken holders every cycle.
uint256 public constant ASSET_FEE_RATE = 1 * (10**15); // The proportion of fund balance that gets distributed to RepToken holders every cycle.
uint256 public constant NEXT_PHASE_REWARD = 1 * (10**18); // Amount of RepToken rewarded to the user who calls nextPhase().
uint256 public constant COLLATERAL_RATIO_MODIFIER = 75 * (10**16); // Modifies Compound's collateral ratio, gets 2:1 from 1.5:1 ratio
uint256 public constant MIN_RISK_TIME = 3 days; // Mininum risk taken to get full commissions is 9 days * reptokenBalance
uint256 public constant INACTIVE_THRESHOLD = 2; // Number of inactive cycles after which a manager's RepToken balance can be burned
uint256 public constant ROI_PUNISH_THRESHOLD = 1 * (10**17); // ROI worse than 10% will see punishment in stake
uint256 public constant ROI_BURN_THRESHOLD = 25 * (10**16); // ROI worse than 25% will see their stake all burned
uint256 public constant ROI_PUNISH_SLOPE = 6; // repROI = -(6 * absROI - 0.5)
uint256 public constant ROI_PUNISH_NEG_BIAS = 5 * (10**17); // repROI = -(6 * absROI - 0.5)
uint256 public constant PEAK_COMMISSION_RATE = 20 * (10**16); // The proportion of profits that gets distributed to PeakDeFi referrers every cycle.
// Instance variables
// Checks if the token listing initialization has been completed.
bool public hasInitializedTokenListings;
// Checks if the fund has been initialized
bool public isInitialized;
// Address of the RepToken token contract.
address public controlTokenAddr;
// Address of the share token contract.
address public shareTokenAddr;
// Address of the PeakDeFiProxy contract.
address payable public proxyAddr;
// Address of the CompoundOrderFactory contract.
address public compoundFactoryAddr;
// Address of the PeakDeFiLogic contract.
address public peakdefiLogic;
address public peakdefiLogic2;
address public peakdefiLogic3;
// Address to which the development team funding will be sent.
address payable public devFundingAccount;
// Address of the previous version of PeakDeFiFund.
address payable public previousVersion;
// The number of the current investment cycle.
uint256 public cycleNumber;
// The amount of funds held by the fund.
uint256 public totalFundsInUSDC;
// The total funds at the beginning of the current management phase
uint256 public totalFundsAtManagePhaseStart;
// The start time for the current investment cycle phase, in seconds since Unix epoch.
uint256 public startTimeOfCyclePhase;
// The proportion of PeakDeFi Shares total supply to mint and use for funding the development team. Fixed point decimal.
uint256 public devFundingRate;
// Total amount of commission unclaimed by managers
uint256 public totalCommissionLeft;
// Stores the lengths of each cycle phase in seconds.
uint256[2] public phaseLengths;
// The number of managers onboarded during the current cycle
uint256 public managersOnboardedThisCycle;
// The amount of RepToken tokens a new manager receves
uint256 public newManagerRepToken;
// The max number of new managers that can be onboarded in one cycle
uint256 public maxNewManagersPerCycle;
// The price of RepToken in USDC
uint256 public reptokenPrice;
// The last cycle where a user redeemed all of their remaining commission.
mapping(address => uint256) internal _lastCommissionRedemption;
// Marks whether a manager has redeemed their commission for a certain cycle
mapping(address => mapping(uint256 => bool))
internal _hasRedeemedCommissionForCycle;
// The stake-time measured risk that a manager has taken in a cycle
mapping(address => mapping(uint256 => uint256)) internal _riskTakenInCycle;
// In case a manager joined the fund during the current cycle, set the fallback base stake for risk threshold calculation
mapping(address => uint256) internal _baseRiskStakeFallback;
// List of investments of a manager in the current cycle.
mapping(address => Investment[]) public userInvestments;
// List of short/long orders of a manager in the current cycle.
mapping(address => address payable[]) public userCompoundOrders;
// Total commission to be paid for work done in a certain cycle (will be redeemed in the next cycle's Intermission)
mapping(uint256 => uint256) internal _totalCommissionOfCycle;
// The block number at which the Manage phase ended for a given cycle
mapping(uint256 => uint256) internal _managePhaseEndBlock;
// The last cycle where a manager made an investment
mapping(address => uint256) internal _lastActiveCycle;
// Checks if an address points to a whitelisted Kyber token.
mapping(address => bool) public isKyberToken;
// Checks if an address points to a whitelisted Compound token. Returns false for cUSDC and other stablecoin CompoundTokens.
mapping(address => bool) public isCompoundToken;
// The current cycle phase.
CyclePhase public cyclePhase;
// Upgrade governance related variables
bool public hasFinalizedNextVersion; // Denotes if the address of the next smart contract version has been finalized
address payable public nextVersion; // Address of the next version of PeakDeFiFund.
// Contract instances
IMiniMeToken internal cToken;
IMiniMeToken internal sToken;
PeakDeFiProxyInterface internal proxy;
// PeakDeFi
uint256 public peakReferralTotalCommissionLeft;
uint256 public peakManagerStakeRequired;
mapping(uint256 => uint256) internal _peakReferralTotalCommissionOfCycle;
mapping(address => uint256) internal _peakReferralLastCommissionRedemption;
mapping(address => mapping(uint256 => bool))
internal _peakReferralHasRedeemedCommissionForCycle;
IMiniMeToken public peakReferralToken;
PeakReward public peakReward;
PeakStaking public peakStaking;
bool public isPermissioned;
mapping(address => mapping(uint256 => bool)) public hasUsedSalt;
// Events
event ChangedPhase(
uint256 indexed _cycleNumber,
uint256 indexed _newPhase,
uint256 _timestamp,
uint256 _totalFundsInUSDC
);
event Deposit(
uint256 indexed _cycleNumber,
address indexed _sender,
address _tokenAddress,
uint256 _tokenAmount,
uint256 _usdcAmount,
uint256 _timestamp
);
event Withdraw(
uint256 indexed _cycleNumber,
address indexed _sender,
address _tokenAddress,
uint256 _tokenAmount,
uint256 _usdcAmount,
uint256 _timestamp
);
event CreatedInvestment(
uint256 indexed _cycleNumber,
address indexed _sender,
uint256 _id,
address _tokenAddress,
uint256 _stakeInWeis,
uint256 _buyPrice,
uint256 _costUSDCAmount,
uint256 _tokenAmount
);
event SoldInvestment(
uint256 indexed _cycleNumber,
address indexed _sender,
uint256 _id,
address _tokenAddress,
uint256 _receivedRepToken,
uint256 _sellPrice,
uint256 _earnedUSDCAmount
);
event CreatedCompoundOrder(
uint256 indexed _cycleNumber,
address indexed _sender,
uint256 _id,
address _order,
bool _orderType,
address _tokenAddress,
uint256 _stakeInWeis,
uint256 _costUSDCAmount
);
event SoldCompoundOrder(
uint256 indexed _cycleNumber,
address indexed _sender,
uint256 _id,
address _order,
bool _orderType,
address _tokenAddress,
uint256 _receivedRepToken,
uint256 _earnedUSDCAmount
);
event RepaidCompoundOrder(
uint256 indexed _cycleNumber,
address indexed _sender,
uint256 _id,
address _order,
uint256 _repaidUSDCAmount
);
event CommissionPaid(
uint256 indexed _cycleNumber,
address indexed _sender,
uint256 _commission
);
event TotalCommissionPaid(
uint256 indexed _cycleNumber,
uint256 _totalCommissionInUSDC
);
event Register(
address indexed _manager,
uint256 _donationInUSDC,
uint256 _reptokenReceived
);
event BurnDeadman(address indexed _manager, uint256 _reptokenBurned);
event DeveloperInitiatedUpgrade(
uint256 indexed _cycleNumber,
address _candidate
);
event FinalizedNextVersion(
uint256 indexed _cycleNumber,
address _nextVersion
);
event PeakReferralCommissionPaid(
uint256 indexed _cycleNumber,
address indexed _sender,
uint256 _commission
);
event PeakReferralTotalCommissionPaid(
uint256 indexed _cycleNumber,
uint256 _totalCommissionInUSDC
);
/*
Helper functions shared by both PeakDeFiLogic & PeakDeFiFund
*/
function lastCommissionRedemption(address _manager)
public
view
returns (uint256)
{
if (_lastCommissionRedemption[_manager] == 0) {
return
previousVersion == address(0)
? 0
: PeakDeFiStorage(previousVersion).lastCommissionRedemption(
_manager
);
}
return _lastCommissionRedemption[_manager];
}
function hasRedeemedCommissionForCycle(address _manager, uint256 _cycle)
public
view
returns (bool)
{
if (_hasRedeemedCommissionForCycle[_manager][_cycle] == false) {
return
previousVersion == address(0)
? false
: PeakDeFiStorage(previousVersion)
.hasRedeemedCommissionForCycle(_manager, _cycle);
}
return _hasRedeemedCommissionForCycle[_manager][_cycle];
}
function riskTakenInCycle(address _manager, uint256 _cycle)
public
view
returns (uint256)
{
if (_riskTakenInCycle[_manager][_cycle] == 0) {
return
previousVersion == address(0)
? 0
: PeakDeFiStorage(previousVersion).riskTakenInCycle(
_manager,
_cycle
);
}
return _riskTakenInCycle[_manager][_cycle];
}
function baseRiskStakeFallback(address _manager)
public
view
returns (uint256)
{
if (_baseRiskStakeFallback[_manager] == 0) {
return
previousVersion == address(0)
? 0
: PeakDeFiStorage(previousVersion).baseRiskStakeFallback(
_manager
);
}
return _baseRiskStakeFallback[_manager];
}
function totalCommissionOfCycle(uint256 _cycle)
public
view
returns (uint256)
{
if (_totalCommissionOfCycle[_cycle] == 0) {
return
previousVersion == address(0)
? 0
: PeakDeFiStorage(previousVersion).totalCommissionOfCycle(
_cycle
);
}
return _totalCommissionOfCycle[_cycle];
}
function managePhaseEndBlock(uint256 _cycle) public view returns (uint256) {
if (_managePhaseEndBlock[_cycle] == 0) {
return
previousVersion == address(0)
? 0
: PeakDeFiStorage(previousVersion).managePhaseEndBlock(
_cycle
);
}
return _managePhaseEndBlock[_cycle];
}
function lastActiveCycle(address _manager) public view returns (uint256) {
if (_lastActiveCycle[_manager] == 0) {
return
previousVersion == address(0)
? 0
: PeakDeFiStorage(previousVersion).lastActiveCycle(_manager);
}
return _lastActiveCycle[_manager];
}
/**
PeakDeFi
*/
function peakReferralLastCommissionRedemption(address _manager)
public
view
returns (uint256)
{
if (_peakReferralLastCommissionRedemption[_manager] == 0) {
return
previousVersion == address(0)
? 0
: PeakDeFiStorage(previousVersion)
.peakReferralLastCommissionRedemption(_manager);
}
return _peakReferralLastCommissionRedemption[_manager];
}
function peakReferralHasRedeemedCommissionForCycle(
address _manager,
uint256 _cycle
) public view returns (bool) {
if (
_peakReferralHasRedeemedCommissionForCycle[_manager][_cycle] ==
false
) {
return
previousVersion == address(0)
? false
: PeakDeFiStorage(previousVersion)
.peakReferralHasRedeemedCommissionForCycle(
_manager,
_cycle
);
}
return _peakReferralHasRedeemedCommissionForCycle[_manager][_cycle];
}
function peakReferralTotalCommissionOfCycle(uint256 _cycle)
public
view
returns (uint256)
{
if (_peakReferralTotalCommissionOfCycle[_cycle] == 0) {
return
previousVersion == address(0)
? 0
: PeakDeFiStorage(previousVersion)
.peakReferralTotalCommissionOfCycle(_cycle);
}
return _peakReferralTotalCommissionOfCycle[_cycle];
}
}
pragma solidity 0.5.17;
interface PeakDeFiProxyInterface {
function peakdefiFundAddress() external view returns (address payable);
function updatePeakDeFiFundAddress() external;
}
pragma solidity 0.5.17;
import "./PeakDeFiFund.sol";
contract PeakDeFiProxy {
address payable public peakdefiFundAddress;
event UpdatedFundAddress(address payable _newFundAddr);
constructor(address payable _fundAddr) public {
peakdefiFundAddress = _fundAddr;
emit UpdatedFundAddress(_fundAddr);
}
function updatePeakDeFiFundAddress() public {
require(msg.sender == peakdefiFundAddress, "Sender not PeakDeFiFund");
address payable nextVersion = PeakDeFiFund(peakdefiFundAddress)
.nextVersion();
require(nextVersion != address(0), "Next version can't be empty");
peakdefiFundAddress = nextVersion;
emit UpdatedFundAddress(peakdefiFundAddress);
}
}
pragma solidity 0.5.17;
import "@openzeppelin/contracts/cryptography/ECDSA.sol";
import "./PeakDeFiStorage.sol";
import "./derivatives/CompoundOrderFactory.sol";
/**
* @title Part of the functions for PeakDeFiFund
* @author Zefram Lou (Zebang Liu)
*/
contract PeakDeFiLogic is
PeakDeFiStorage,
Utils(address(0), address(0), address(0))
{
/**
* @notice Executes function only during the given cycle phase.
* @param phase the cycle phase during which the function may be called
*/
modifier during(CyclePhase phase) {
require(cyclePhase == phase);
if (cyclePhase == CyclePhase.Intermission) {
require(isInitialized);
}
_;
}
/**
* @notice Returns the length of the user's investments array.
* @return length of the user's investments array
*/
function investmentsCount(address _userAddr)
public
view
returns (uint256 _count)
{
return userInvestments[_userAddr].length;
}
/**
* @notice Burns the RepToken balance of a manager who has been inactive for a certain number of cycles
* @param _deadman the manager whose RepToken balance will be burned
*/
function burnDeadman(address _deadman)
public
nonReentrant
during(CyclePhase.Intermission)
{
require(_deadman != address(this));
require(
cycleNumber.sub(lastActiveCycle(_deadman)) > INACTIVE_THRESHOLD
);
uint256 balance = cToken.balanceOf(_deadman);
require(cToken.destroyTokens(_deadman, balance));
emit BurnDeadman(_deadman, balance);
}
/**
* @notice Creates a new investment for an ERC20 token. Backwards compatible.
* @param _tokenAddress address of the ERC20 token contract
* @param _stake amount of RepTokens to be staked in support of the investment
* @param _maxPrice the maximum price for the trade
*/
function createInvestment(
address _tokenAddress,
uint256 _stake,
uint256 _maxPrice
) public {
bytes memory nil;
createInvestmentV2(
msg.sender,
_tokenAddress,
_stake,
_maxPrice,
nil,
true
);
}
function createInvestmentWithSignature(
address _tokenAddress,
uint256 _stake,
uint256 _maxPrice,
bytes calldata _calldata,
bool _useKyber,
address _manager,
uint256 _salt,
bytes calldata _signature
) external {
require(!hasUsedSalt[_manager][_salt]);
bytes32 naiveHash = keccak256(
abi.encodeWithSelector(
this.createInvestmentWithSignature.selector,
abi.encode(
_tokenAddress,
_stake,
_maxPrice,
_calldata,
_useKyber
),
"|END|",
_salt,
address(this)
)
);
bytes32 msgHash = ECDSA.toEthSignedMessageHash(naiveHash);
address recoveredAddress = ECDSA.recover(msgHash, _signature);
require(recoveredAddress == _manager);
// Signature valid, record use of salt
hasUsedSalt[_manager][_salt] = true;
this.createInvestmentV2(
_manager,
_tokenAddress,
_stake,
_maxPrice,
_calldata,
_useKyber
);
}
/**
* @notice Called by user to sell the assets an investment invested in. Returns the staked RepToken plus rewards/penalties to the user.
* The user can sell only part of the investment by changing _tokenAmount. Backwards compatible.
* @dev When selling only part of an investment, the old investment would be "fully" sold and a new investment would be created with
* the original buy price and however much tokens that are not sold.
* @param _investmentId the ID of the investment
* @param _tokenAmount the amount of tokens to be sold.
* @param _minPrice the minimum price for the trade
*/
function sellInvestmentAsset(
uint256 _investmentId,
uint256 _tokenAmount,
uint256 _minPrice
) public {
bytes memory nil;
sellInvestmentAssetV2(
msg.sender,
_investmentId,
_tokenAmount,
_minPrice,
nil,
true
);
}
function sellInvestmentWithSignature(
uint256 _investmentId,
uint256 _tokenAmount,
uint256 _minPrice,
bytes calldata _calldata,
bool _useKyber,
address _manager,
uint256 _salt,
bytes calldata _signature
) external {
require(!hasUsedSalt[_manager][_salt]);
bytes32 naiveHash = keccak256(
abi.encodeWithSelector(
this.sellInvestmentWithSignature.selector,
abi.encode(
_investmentId,
_tokenAmount,
_minPrice,
_calldata,
_useKyber
),
"|END|",
_salt,
address(this)
)
);
bytes32 msgHash = ECDSA.toEthSignedMessageHash(naiveHash);
address recoveredAddress = ECDSA.recover(msgHash, _signature);
require(recoveredAddress == _manager);
// Signature valid, record use of salt
hasUsedSalt[_manager][_salt] = true;
this.sellInvestmentAssetV2(
_manager,
_investmentId,
_tokenAmount,
_minPrice,
_calldata,
_useKyber
);
}
/**
* @notice Creates a new investment for an ERC20 token.
* @param _tokenAddress address of the ERC20 token contract
* @param _stake amount of RepTokens to be staked in support of the investment
* @param _maxPrice the maximum price for the trade
* @param _calldata calldata for 1inch trading
* @param _useKyber true for Kyber Network, false for 1inch
*/
function createInvestmentV2(
address _sender,
address _tokenAddress,
uint256 _stake,
uint256 _maxPrice,
bytes memory _calldata,
bool _useKyber
)
public
during(CyclePhase.Manage)
nonReentrant
isValidToken(_tokenAddress)
{
require(msg.sender == _sender || msg.sender == address(this));
require(_stake > 0);
require(isKyberToken[_tokenAddress]);
// Verify user peak stake
uint256 peakStake = peakStaking.userStakeAmount(_sender);
require(peakStake >= peakManagerStakeRequired);
// Collect stake
require(cToken.generateTokens(address(this), _stake));
require(cToken.destroyTokens(_sender, _stake));
// Add investment to list
userInvestments[_sender].push(
Investment({
tokenAddress: _tokenAddress,
cycleNumber: cycleNumber,
stake: _stake,
tokenAmount: 0,
buyPrice: 0,
sellPrice: 0,
buyTime: now,
buyCostInUSDC: 0,
isSold: false
})
);
// Invest
uint256 investmentId = investmentsCount(_sender).sub(1);
__handleInvestment(
_sender,
investmentId,
0,
_maxPrice,
true,
_calldata,
_useKyber
);
// Update last active cycle
_lastActiveCycle[_sender] = cycleNumber;
// Emit event
__emitCreatedInvestmentEvent(_sender, investmentId);
}
/**
* @notice Called by user to sell the assets an investment invested in. Returns the staked RepToken plus rewards/penalties to the user.
* The user can sell only part of the investment by changing _tokenAmount.
* @dev When selling only part of an investment, the old investment would be "fully" sold and a new investment would be created with
* the original buy price and however much tokens that are not sold.
* @param _investmentId the ID of the investment
* @param _tokenAmount the amount of tokens to be sold.
* @param _minPrice the minimum price for the trade
*/
function sellInvestmentAssetV2(
address _sender,
uint256 _investmentId,
uint256 _tokenAmount,
uint256 _minPrice,
bytes memory _calldata,
bool _useKyber
) public nonReentrant during(CyclePhase.Manage) {
require(msg.sender == _sender || msg.sender == address(this));
Investment storage investment = userInvestments[_sender][_investmentId];
require(
investment.buyPrice > 0 &&
investment.cycleNumber == cycleNumber &&
!investment.isSold
);
require(_tokenAmount > 0 && _tokenAmount <= investment.tokenAmount);
// Create new investment for leftover tokens
bool isPartialSell = false;
uint256 stakeOfSoldTokens = investment.stake.mul(_tokenAmount).div(
investment.tokenAmount
);
if (_tokenAmount != investment.tokenAmount) {
isPartialSell = true;
__createInvestmentForLeftovers(
_sender,
_investmentId,
_tokenAmount
);
__emitCreatedInvestmentEvent(
_sender,
investmentsCount(_sender).sub(1)
);
}
// Update investment info
investment.isSold = true;
// Sell asset
(
uint256 actualDestAmount,
uint256 actualSrcAmount
) = __handleInvestment(
_sender,
_investmentId,
_minPrice,
uint256(-1),
false,
_calldata,
_useKyber
);
__sellInvestmentUpdate(
_sender,
_investmentId,
stakeOfSoldTokens,
actualDestAmount
);
}
function __sellInvestmentUpdate(
address _sender,
uint256 _investmentId,
uint256 stakeOfSoldTokens,
uint256 actualDestAmount
) internal {
Investment storage investment = userInvestments[_sender][_investmentId];
// Return staked RepToken
uint256 receiveRepTokenAmount = getReceiveRepTokenAmount(
stakeOfSoldTokens,
investment.sellPrice,
investment.buyPrice
);
__returnStake(receiveRepTokenAmount, stakeOfSoldTokens);
// Record risk taken in investment
__recordRisk(_sender, investment.stake, investment.buyTime);
// Update total funds
totalFundsInUSDC = totalFundsInUSDC.sub(investment.buyCostInUSDC).add(
actualDestAmount
);
// Emit event
__emitSoldInvestmentEvent(
_sender,
_investmentId,
receiveRepTokenAmount,
actualDestAmount
);
}
function __emitSoldInvestmentEvent(
address _sender,
uint256 _investmentId,
uint256 _receiveRepTokenAmount,
uint256 _actualDestAmount
) internal {
Investment storage investment = userInvestments[_sender][_investmentId];
emit SoldInvestment(
cycleNumber,
_sender,
_investmentId,
investment.tokenAddress,
_receiveRepTokenAmount,
investment.sellPrice,
_actualDestAmount
);
}
function __createInvestmentForLeftovers(
address _sender,
uint256 _investmentId,
uint256 _tokenAmount
) internal {
Investment storage investment = userInvestments[_sender][_investmentId];
uint256 stakeOfSoldTokens = investment.stake.mul(_tokenAmount).div(
investment.tokenAmount
);
// calculate the part of original USDC cost attributed to the sold tokens
uint256 soldBuyCostInUSDC = investment
.buyCostInUSDC
.mul(_tokenAmount)
.div(investment.tokenAmount);
userInvestments[_sender].push(
Investment({
tokenAddress: investment.tokenAddress,
cycleNumber: cycleNumber,
stake: investment.stake.sub(stakeOfSoldTokens),
tokenAmount: investment.tokenAmount.sub(_tokenAmount),
buyPrice: investment.buyPrice,
sellPrice: 0,
buyTime: investment.buyTime,
buyCostInUSDC: investment.buyCostInUSDC.sub(soldBuyCostInUSDC),
isSold: false
})
);
// update the investment object being sold
investment.tokenAmount = _tokenAmount;
investment.stake = stakeOfSoldTokens;
investment.buyCostInUSDC = soldBuyCostInUSDC;
}
function __emitCreatedInvestmentEvent(address _sender, uint256 _id)
internal
{
Investment storage investment = userInvestments[_sender][_id];
emit CreatedInvestment(
cycleNumber,
_sender,
_id,
investment.tokenAddress,
investment.stake,
investment.buyPrice,
investment.buyCostInUSDC,
investment.tokenAmount
);
}
function createCompoundOrderWithSignature(
bool _orderType,
address _tokenAddress,
uint256 _stake,
uint256 _minPrice,
uint256 _maxPrice,
address _manager,
uint256 _salt,
bytes calldata _signature
) external {
require(!hasUsedSalt[_manager][_salt]);
bytes32 naiveHash = keccak256(
abi.encodeWithSelector(
this.createCompoundOrderWithSignature.selector,
abi.encode(
_orderType,
_tokenAddress,
_stake,
_minPrice,
_maxPrice
),
"|END|",
_salt,
address(this)
)
);
bytes32 msgHash = ECDSA.toEthSignedMessageHash(naiveHash);
address recoveredAddress = ECDSA.recover(msgHash, _signature);
require(recoveredAddress == _manager);
// Signature valid, record use of salt
hasUsedSalt[_manager][_salt] = true;
this.createCompoundOrder(
_manager,
_orderType,
_tokenAddress,
_stake,
_minPrice,
_maxPrice
);
}
function sellCompoundOrderWithSignature(
uint256 _orderId,
uint256 _minPrice,
uint256 _maxPrice,
address _manager,
uint256 _salt,
bytes calldata _signature
) external {
require(!hasUsedSalt[_manager][_salt]);
bytes32 naiveHash = keccak256(
abi.encodeWithSelector(
this.sellCompoundOrderWithSignature.selector,
abi.encode(_orderId, _minPrice, _maxPrice),
"|END|",
_salt,
address(this)
)
);
bytes32 msgHash = ECDSA.toEthSignedMessageHash(naiveHash);
address recoveredAddress = ECDSA.recover(msgHash, _signature);
require(recoveredAddress == _manager);
// Signature valid, record use of salt
hasUsedSalt[_manager][_salt] = true;
this.sellCompoundOrder(_manager, _orderId, _minPrice, _maxPrice);
}
function repayCompoundOrderWithSignature(
uint256 _orderId,
uint256 _repayAmountInUSDC,
address _manager,
uint256 _salt,
bytes calldata _signature
) external {
require(!hasUsedSalt[_manager][_salt]);
bytes32 naiveHash = keccak256(
abi.encodeWithSelector(
this.repayCompoundOrderWithSignature.selector,
abi.encode(_orderId, _repayAmountInUSDC),
"|END|",
_salt,
address(this)
)
);
bytes32 msgHash = ECDSA.toEthSignedMessageHash(naiveHash);
address recoveredAddress = ECDSA.recover(msgHash, _signature);
require(recoveredAddress == _manager);
// Signature valid, record use of salt
hasUsedSalt[_manager][_salt] = true;
this.repayCompoundOrder(_manager, _orderId, _repayAmountInUSDC);
}
/**
* @notice Creates a new Compound order to either short or leverage long a token.
* @param _orderType true for a short order, false for a levarage long order
* @param _tokenAddress address of the Compound token to be traded
* @param _stake amount of RepTokens to be staked
* @param _minPrice the minimum token price for the trade
* @param _maxPrice the maximum token price for the trade
*/
function createCompoundOrder(
address _sender,
bool _orderType,
address _tokenAddress,
uint256 _stake,
uint256 _minPrice,
uint256 _maxPrice
)
public
during(CyclePhase.Manage)
nonReentrant
isValidToken(_tokenAddress)
{
require(msg.sender == _sender || msg.sender == address(this));
require(_minPrice <= _maxPrice);
require(_stake > 0);
require(isCompoundToken[_tokenAddress]);
// Verify user peak stake
uint256 peakStake = peakStaking.userStakeAmount(_sender);
require(peakStake >= peakManagerStakeRequired);
// Collect stake
require(cToken.generateTokens(address(this), _stake));
require(cToken.destroyTokens(_sender, _stake));
// Create compound order and execute
uint256 collateralAmountInUSDC = totalFundsInUSDC.mul(_stake).div(
cToken.totalSupply()
);
CompoundOrder order = __createCompoundOrder(
_orderType,
_tokenAddress,
_stake,
collateralAmountInUSDC
);
usdc.safeApprove(address(order), 0);
usdc.safeApprove(address(order), collateralAmountInUSDC);
order.executeOrder(_minPrice, _maxPrice);
// Add order to list
userCompoundOrders[_sender].push(address(order));
// Update last active cycle
_lastActiveCycle[_sender] = cycleNumber;
__emitCreatedCompoundOrderEvent(
_sender,
address(order),
_orderType,
_tokenAddress,
_stake,
collateralAmountInUSDC
);
}
function __emitCreatedCompoundOrderEvent(
address _sender,
address order,
bool _orderType,
address _tokenAddress,
uint256 _stake,
uint256 collateralAmountInUSDC
) internal {
// Emit event
emit CreatedCompoundOrder(
cycleNumber,
_sender,
userCompoundOrders[_sender].length - 1,
address(order),
_orderType,
_tokenAddress,
_stake,
collateralAmountInUSDC
);
}
/**
* @notice Sells a compound order
* @param _orderId the ID of the order to be sold (index in userCompoundOrders[msg.sender])
* @param _minPrice the minimum token price for the trade
* @param _maxPrice the maximum token price for the trade
*/
function sellCompoundOrder(
address _sender,
uint256 _orderId,
uint256 _minPrice,
uint256 _maxPrice
) public during(CyclePhase.Manage) nonReentrant {
require(msg.sender == _sender || msg.sender == address(this));
// Load order info
require(userCompoundOrders[_sender][_orderId] != address(0));
CompoundOrder order = CompoundOrder(
userCompoundOrders[_sender][_orderId]
);
require(order.isSold() == false && order.cycleNumber() == cycleNumber);
// Sell order
(uint256 inputAmount, uint256 outputAmount) = order.sellOrder(
_minPrice,
_maxPrice
);
// Return staked RepToken
uint256 stake = order.stake();
uint256 receiveRepTokenAmount = getReceiveRepTokenAmount(
stake,
outputAmount,
inputAmount
);
__returnStake(receiveRepTokenAmount, stake);
// Record risk taken
__recordRisk(_sender, stake, order.buyTime());
// Update total funds
totalFundsInUSDC = totalFundsInUSDC.sub(inputAmount).add(outputAmount);
// Emit event
emit SoldCompoundOrder(
cycleNumber,
_sender,
userCompoundOrders[_sender].length - 1,
address(order),
order.orderType(),
order.compoundTokenAddr(),
receiveRepTokenAmount,
outputAmount
);
}
/**
* @notice Repys debt for a Compound order to prevent the collateral ratio from dropping below threshold.
* @param _orderId the ID of the Compound order
* @param _repayAmountInUSDC amount of USDC to use for repaying debt
*/
function repayCompoundOrder(
address _sender,
uint256 _orderId,
uint256 _repayAmountInUSDC
) public during(CyclePhase.Manage) nonReentrant {
require(msg.sender == _sender || msg.sender == address(this));
// Load order info
require(userCompoundOrders[_sender][_orderId] != address(0));
CompoundOrder order = CompoundOrder(
userCompoundOrders[_sender][_orderId]
);
require(order.isSold() == false && order.cycleNumber() == cycleNumber);
// Repay loan
order.repayLoan(_repayAmountInUSDC);
// Emit event
emit RepaidCompoundOrder(
cycleNumber,
_sender,
userCompoundOrders[_sender].length - 1,
address(order),
_repayAmountInUSDC
);
}
function emergencyExitCompoundTokens(
address _sender,
uint256 _orderId,
address _tokenAddr,
address _receiver
) public during(CyclePhase.Intermission) nonReentrant {
CompoundOrder order = CompoundOrder(userCompoundOrders[_sender][_orderId]);
order.emergencyExitTokens(_tokenAddr, _receiver);
}
function getReceiveRepTokenAmount(
uint256 stake,
uint256 output,
uint256 input
) public pure returns (uint256 _amount) {
if (output >= input) {
// positive ROI, simply return stake * (1 + ROI)
return stake.mul(output).div(input);
} else {
// negative ROI
uint256 absROI = input.sub(output).mul(PRECISION).div(input);
if (absROI <= ROI_PUNISH_THRESHOLD) {
// ROI better than -10%, no punishment
return stake.mul(output).div(input);
} else if (
absROI > ROI_PUNISH_THRESHOLD && absROI < ROI_BURN_THRESHOLD
) {
// ROI between -10% and -25%, punish
// return stake * (1 + roiWithPunishment) = stake * (1 + (-(6 * absROI - 0.5)))
return
stake
.mul(
PRECISION.sub(
ROI_PUNISH_SLOPE.mul(absROI).sub(
ROI_PUNISH_NEG_BIAS
)
)
)
.div(PRECISION);
} else {
// ROI greater than 25%, burn all stake
return 0;
}
}
}
/**
* @notice Handles and investment by doing the necessary trades using __kyberTrade() or Fulcrum trading
* @param _investmentId the ID of the investment to be handled
* @param _minPrice the minimum price for the trade
* @param _maxPrice the maximum price for the trade
* @param _buy whether to buy or sell the given investment
* @param _calldata calldata for 1inch trading
* @param _useKyber true for Kyber Network, false for 1inch
*/
function __handleInvestment(
address _sender,
uint256 _investmentId,
uint256 _minPrice,
uint256 _maxPrice,
bool _buy,
bytes memory _calldata,
bool _useKyber
) internal returns (uint256 _actualDestAmount, uint256 _actualSrcAmount) {
Investment storage investment = userInvestments[_sender][_investmentId];
address token = investment.tokenAddress;
// Basic trading
uint256 dInS; // price of dest token denominated in src token
uint256 sInD; // price of src token denominated in dest token
if (_buy) {
if (_useKyber) {
(
dInS,
sInD,
_actualDestAmount,
_actualSrcAmount
) = __kyberTrade(
usdc,
totalFundsInUSDC.mul(investment.stake).div(
cToken.totalSupply()
),
ERC20Detailed(token)
);
} else {
// 1inch trading
(
dInS,
sInD,
_actualDestAmount,
_actualSrcAmount
) = __oneInchTrade(
usdc,
totalFundsInUSDC.mul(investment.stake).div(
cToken.totalSupply()
),
ERC20Detailed(token),
_calldata
);
}
require(_minPrice <= dInS && dInS <= _maxPrice);
investment.buyPrice = dInS;
investment.tokenAmount = _actualDestAmount;
investment.buyCostInUSDC = _actualSrcAmount;
} else {
if (_useKyber) {
(
dInS,
sInD,
_actualDestAmount,
_actualSrcAmount
) = __kyberTrade(
ERC20Detailed(token),
investment.tokenAmount,
usdc
);
} else {
(
dInS,
sInD,
_actualDestAmount,
_actualSrcAmount
) = __oneInchTrade(
ERC20Detailed(token),
investment.tokenAmount,
usdc,
_calldata
);
}
require(_minPrice <= sInD && sInD <= _maxPrice);
investment.sellPrice = sInD;
}
}
/**
* @notice Separated from createCompoundOrder() to avoid stack too deep error
*/
function __createCompoundOrder(
bool _orderType, // True for shorting, false for longing
address _tokenAddress,
uint256 _stake,
uint256 _collateralAmountInUSDC
) internal returns (CompoundOrder) {
CompoundOrderFactory factory = CompoundOrderFactory(
compoundFactoryAddr
);
uint256 loanAmountInUSDC = _collateralAmountInUSDC
.mul(COLLATERAL_RATIO_MODIFIER)
.div(PRECISION)
.mul(factory.getMarketCollateralFactor(_tokenAddress))
.div(PRECISION);
CompoundOrder order = factory.createOrder(
_tokenAddress,
cycleNumber,
_stake,
_collateralAmountInUSDC,
loanAmountInUSDC,
_orderType
);
return order;
}
/**
* @notice Returns stake to manager after investment is sold, including reward/penalty based on performance
*/
function __returnStake(uint256 _receiveRepTokenAmount, uint256 _stake)
internal
{
require(cToken.destroyTokens(address(this), _stake));
require(cToken.generateTokens(msg.sender, _receiveRepTokenAmount));
}
/**
* @notice Records risk taken in a trade based on stake and time of investment
*/
function __recordRisk(
address _sender,
uint256 _stake,
uint256 _buyTime
) internal {
_riskTakenInCycle[_sender][cycleNumber] = riskTakenInCycle(
_sender,
cycleNumber
)
.add(_stake.mul(now.sub(_buyTime)));
}
}
pragma solidity ^0.5.0;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* NOTE: This call _does not revert_ if the signature is invalid, or
* if the signer is otherwise unable to be retrieved. In those scenarios,
* the zero address is returned.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
// Check the signature length
if (signature.length != 65) {
return (address(0));
}
// Divide the signature in r, s and v variables
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solhint-disable-next-line no-inline-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return address(0);
}
if (v != 27 && v != 28) {
return address(0);
}
// If the signature is valid (and not malleable), return the signer address
return ecrecover(hash, v, r, s);
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* replicates the behavior of the
* https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`]
* JSON-RPC method.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
}
pragma solidity 0.5.17;
import "./PeakDeFiStorage.sol";
import "./derivatives/CompoundOrderFactory.sol";
import "@nomiclabs/buidler/console.sol";
/**
* @title Part of the functions for PeakDeFiFund
* @author Zefram Lou (Zebang Liu)
*/
contract PeakDeFiLogic2 is
PeakDeFiStorage,
Utils(address(0), address(0), address(0))
{
/**
* @notice Passes if the fund has not finalized the next smart contract to upgrade to
*/
modifier notReadyForUpgrade {
require(hasFinalizedNextVersion == false);
_;
}
/**
* @notice Executes function only during the given cycle phase.
* @param phase the cycle phase during which the function may be called
*/
modifier during(CyclePhase phase) {
require(cyclePhase == phase);
if (cyclePhase == CyclePhase.Intermission) {
require(isInitialized);
}
_;
}
/**
* Deposit & Withdraw
*/
function depositEther(address _referrer) public payable {
bytes memory nil;
depositEtherAdvanced(true, nil, _referrer);
}
/**
* @notice Deposit Ether into the fund. Ether will be converted into USDC.
* @param _useKyber true for Kyber Network, false for 1inch
* @param _calldata calldata for 1inch trading
* @param _referrer the referrer's address
*/
function depositEtherAdvanced(
bool _useKyber,
bytes memory _calldata,
address _referrer
) public payable nonReentrant notReadyForUpgrade {
// Buy USDC with ETH
uint256 actualUSDCDeposited;
uint256 actualETHDeposited;
if (_useKyber) {
(, , actualUSDCDeposited, actualETHDeposited) = __kyberTrade(
ETH_TOKEN_ADDRESS,
msg.value,
usdc
);
} else {
(, , actualUSDCDeposited, actualETHDeposited) = __oneInchTrade(
ETH_TOKEN_ADDRESS,
msg.value,
usdc,
_calldata
);
}
// Send back leftover ETH
uint256 leftOverETH = msg.value.sub(actualETHDeposited);
if (leftOverETH > 0) {
msg.sender.transfer(leftOverETH);
}
// Register investment
__deposit(actualUSDCDeposited, _referrer);
// Emit event
emit Deposit(
cycleNumber,
msg.sender,
address(ETH_TOKEN_ADDRESS),
actualETHDeposited,
actualUSDCDeposited,
now
);
}
/**
* @notice Deposit USDC Stablecoin into the fund.
* @param _usdcAmount The amount of USDC to be deposited. May be different from actual deposited amount.
* @param _referrer the referrer's address
*/
function depositUSDC(uint256 _usdcAmount, address _referrer)
public
nonReentrant
notReadyForUpgrade
{
usdc.safeTransferFrom(msg.sender, address(this), _usdcAmount);
// Register investment
__deposit(_usdcAmount, _referrer);
// Emit event
emit Deposit(
cycleNumber,
msg.sender,
USDC_ADDR,
_usdcAmount,
_usdcAmount,
now
);
}
function depositToken(
address _tokenAddr,
uint256 _tokenAmount,
address _referrer
) public {
bytes memory nil;
depositTokenAdvanced(_tokenAddr, _tokenAmount, true, nil, _referrer);
}
/**
* @notice Deposit ERC20 tokens into the fund. Tokens will be converted into USDC.
* @param _tokenAddr the address of the token to be deposited
* @param _tokenAmount The amount of tokens to be deposited. May be different from actual deposited amount.
* @param _useKyber true for Kyber Network, false for 1inch
* @param _calldata calldata for 1inch trading
* @param _referrer the referrer's address
*/
function depositTokenAdvanced(
address _tokenAddr,
uint256 _tokenAmount,
bool _useKyber,
bytes memory _calldata,
address _referrer
) public nonReentrant notReadyForUpgrade isValidToken(_tokenAddr) {
require(
_tokenAddr != USDC_ADDR && _tokenAddr != address(ETH_TOKEN_ADDRESS)
);
ERC20Detailed token = ERC20Detailed(_tokenAddr);
token.safeTransferFrom(msg.sender, address(this), _tokenAmount);
// Convert token into USDC
uint256 actualUSDCDeposited;
uint256 actualTokenDeposited;
if (_useKyber) {
(, , actualUSDCDeposited, actualTokenDeposited) = __kyberTrade(
token,
_tokenAmount,
usdc
);
} else {
(, , actualUSDCDeposited, actualTokenDeposited) = __oneInchTrade(
token,
_tokenAmount,
usdc,
_calldata
);
}
// Give back leftover tokens
uint256 leftOverTokens = _tokenAmount.sub(actualTokenDeposited);
if (leftOverTokens > 0) {
token.safeTransfer(msg.sender, leftOverTokens);
}
// Register investment
__deposit(actualUSDCDeposited, _referrer);
// Emit event
emit Deposit(
cycleNumber,
msg.sender,
_tokenAddr,
actualTokenDeposited,
actualUSDCDeposited,
now
);
}
function withdrawEther(uint256 _amountInUSDC) external {
bytes memory nil;
withdrawEtherAdvanced(_amountInUSDC, true, nil);
}
/**
* @notice Withdraws Ether by burning Shares.
* @param _amountInUSDC Amount of funds to be withdrawn expressed in USDC. Fixed-point decimal. May be different from actual amount.
* @param _useKyber true for Kyber Network, false for 1inch
* @param _calldata calldata for 1inch trading
*/
function withdrawEtherAdvanced(
uint256 _amountInUSDC,
bool _useKyber,
bytes memory _calldata
) public nonReentrant during(CyclePhase.Intermission) {
// Buy ETH
uint256 actualETHWithdrawn;
uint256 actualUSDCWithdrawn;
if (_useKyber) {
(, , actualETHWithdrawn, actualUSDCWithdrawn) = __kyberTrade(
usdc,
_amountInUSDC,
ETH_TOKEN_ADDRESS
);
} else {
(, , actualETHWithdrawn, actualUSDCWithdrawn) = __oneInchTrade(
usdc,
_amountInUSDC,
ETH_TOKEN_ADDRESS,
_calldata
);
}
__withdraw(actualUSDCWithdrawn);
// Transfer Ether to user
msg.sender.transfer(actualETHWithdrawn);
// Emit event
emit Withdraw(
cycleNumber,
msg.sender,
address(ETH_TOKEN_ADDRESS),
actualETHWithdrawn,
actualUSDCWithdrawn,
now
);
}
/**
* @notice Withdraws Ether by burning Shares.
* @param _amountInUSDC Amount of funds to be withdrawn expressed in USDC. Fixed-point decimal. May be different from actual amount.
*/
function withdrawUSDC(uint256 _amountInUSDC)
external
nonReentrant
during(CyclePhase.Intermission)
{
__withdraw(_amountInUSDC);
// Transfer USDC to user
usdc.safeTransfer(msg.sender, _amountInUSDC);
// Emit event
emit Withdraw(
cycleNumber,
msg.sender,
USDC_ADDR,
_amountInUSDC,
_amountInUSDC,
now
);
}
function withdrawToken(address _tokenAddr, uint256 _amountInUSDC) external {
bytes memory nil;
withdrawTokenAdvanced(_tokenAddr, _amountInUSDC, true, nil);
}
/**
* @notice Withdraws funds by burning Shares, and converts the funds into the specified token using Kyber Network.
* @param _tokenAddr the address of the token to be withdrawn into the caller's account
* @param _amountInUSDC The amount of funds to be withdrawn expressed in USDC. Fixed-point decimal. May be different from actual amount.
* @param _useKyber true for Kyber Network, false for 1inch
* @param _calldata calldata for 1inch trading
*/
function withdrawTokenAdvanced(
address _tokenAddr,
uint256 _amountInUSDC,
bool _useKyber,
bytes memory _calldata
)
public
during(CyclePhase.Intermission)
nonReentrant
isValidToken(_tokenAddr)
{
require(
_tokenAddr != USDC_ADDR && _tokenAddr != address(ETH_TOKEN_ADDRESS)
);
ERC20Detailed token = ERC20Detailed(_tokenAddr);
// Convert USDC into desired tokens
uint256 actualTokenWithdrawn;
uint256 actualUSDCWithdrawn;
if (_useKyber) {
(, , actualTokenWithdrawn, actualUSDCWithdrawn) = __kyberTrade(
usdc,
_amountInUSDC,
token
);
} else {
(, , actualTokenWithdrawn, actualUSDCWithdrawn) = __oneInchTrade(
usdc,
_amountInUSDC,
token,
_calldata
);
}
__withdraw(actualUSDCWithdrawn);
// Transfer tokens to user
token.safeTransfer(msg.sender, actualTokenWithdrawn);
// Emit event
emit Withdraw(
cycleNumber,
msg.sender,
_tokenAddr,
actualTokenWithdrawn,
actualUSDCWithdrawn,
now
);
}
/**
* Manager registration
*/
/**
* @notice Registers `msg.sender` as a manager, using USDC as payment. The more one pays, the more RepToken one gets.
* There's a max RepToken amount that can be bought, and excess payment will be sent back to sender.
*/
function registerWithUSDC()
public
during(CyclePhase.Intermission)
nonReentrant
{
require(!isPermissioned);
require(managersOnboardedThisCycle < maxNewManagersPerCycle);
managersOnboardedThisCycle = managersOnboardedThisCycle.add(1);
uint256 peakStake = peakStaking.userStakeAmount(msg.sender);
require(peakStake >= peakManagerStakeRequired);
uint256 donationInUSDC = newManagerRepToken.mul(reptokenPrice).div(PRECISION);
usdc.safeTransferFrom(msg.sender, address(this), donationInUSDC);
__register(donationInUSDC);
}
/**
* @notice Registers `msg.sender` as a manager, using ETH as payment. The more one pays, the more RepToken one gets.
* There's a max RepToken amount that can be bought, and excess payment will be sent back to sender.
*/
function registerWithETH()
public
payable
during(CyclePhase.Intermission)
nonReentrant
{
require(!isPermissioned);
require(managersOnboardedThisCycle < maxNewManagersPerCycle);
managersOnboardedThisCycle = managersOnboardedThisCycle.add(1);
uint256 peakStake = peakStaking.userStakeAmount(msg.sender);
require(peakStake >= peakManagerStakeRequired);
uint256 receivedUSDC;
// trade ETH for USDC
(, , receivedUSDC, ) = __kyberTrade(ETH_TOKEN_ADDRESS, msg.value, usdc);
// if USDC value is greater than the amount required, return excess USDC to msg.sender
uint256 donationInUSDC = newManagerRepToken.mul(reptokenPrice).div(PRECISION);
if (receivedUSDC > donationInUSDC) {
usdc.safeTransfer(msg.sender, receivedUSDC.sub(donationInUSDC));
receivedUSDC = donationInUSDC;
}
// register new manager
__register(receivedUSDC);
}
/**
* @notice Registers `msg.sender` as a manager, using tokens as payment. The more one pays, the more RepToken one gets.
* There's a max RepToken amount that can be bought, and excess payment will be sent back to sender.
* @param _token the token to be used for payment
* @param _donationInTokens the amount of tokens to be used for registration, should use the token's native decimals
*/
function registerWithToken(address _token, uint256 _donationInTokens)
public
during(CyclePhase.Intermission)
nonReentrant
{
require(!isPermissioned);
require(managersOnboardedThisCycle < maxNewManagersPerCycle);
managersOnboardedThisCycle = managersOnboardedThisCycle.add(1);
uint256 peakStake = peakStaking.userStakeAmount(msg.sender);
require(peakStake >= peakManagerStakeRequired);
require(
_token != address(0) &&
_token != address(ETH_TOKEN_ADDRESS) &&
_token != USDC_ADDR
);
ERC20Detailed token = ERC20Detailed(_token);
require(token.totalSupply() > 0);
token.safeTransferFrom(msg.sender, address(this), _donationInTokens);
uint256 receivedUSDC;
(, , receivedUSDC, ) = __kyberTrade(token, _donationInTokens, usdc);
// if USDC value is greater than the amount required, return excess USDC to msg.sender
uint256 donationInUSDC = newManagerRepToken.mul(reptokenPrice).div(PRECISION);
if (receivedUSDC > donationInUSDC) {
usdc.safeTransfer(msg.sender, receivedUSDC.sub(donationInUSDC));
receivedUSDC = donationInUSDC;
}
// register new manager
__register(receivedUSDC);
}
function peakAdminRegisterManager(address _manager, uint256 _reptokenAmount)
public
during(CyclePhase.Intermission)
nonReentrant
onlyOwner
{
require(isPermissioned);
// mint REP for msg.sender
require(cToken.generateTokens(_manager, _reptokenAmount));
// Set risk fallback base stake
_baseRiskStakeFallback[_manager] = _baseRiskStakeFallback[_manager].add(
_reptokenAmount
);
// Set last active cycle for msg.sender to be the current cycle
_lastActiveCycle[_manager] = cycleNumber;
// emit events
emit Register(_manager, 0, _reptokenAmount);
}
/**
* @notice Sells tokens left over due to manager not selling or KyberNetwork not having enough volume. Callable by anyone. Money goes to developer.
* @param _tokenAddr address of the token to be sold
* @param _calldata the 1inch trade call data
*/
function sellLeftoverToken(address _tokenAddr, bytes calldata _calldata)
external
during(CyclePhase.Intermission)
nonReentrant
isValidToken(_tokenAddr)
{
ERC20Detailed token = ERC20Detailed(_tokenAddr);
(, , uint256 actualUSDCReceived, ) = __oneInchTrade(
token,
getBalance(token, address(this)),
usdc,
_calldata
);
totalFundsInUSDC = totalFundsInUSDC.add(actualUSDCReceived);
}
/**
* @notice Sells CompoundOrder left over due to manager not selling or KyberNetwork not having enough volume. Callable by anyone. Money goes to developer.
* @param _orderAddress address of the CompoundOrder to be sold
*/
function sellLeftoverCompoundOrder(address payable _orderAddress)
public
during(CyclePhase.Intermission)
nonReentrant
{
// Load order info
require(_orderAddress != address(0));
CompoundOrder order = CompoundOrder(_orderAddress);
require(order.isSold() == false && order.cycleNumber() < cycleNumber);
// Sell short order
// Not using outputAmount returned by order.sellOrder() because _orderAddress could point to a malicious contract
uint256 beforeUSDCBalance = usdc.balanceOf(address(this));
order.sellOrder(0, MAX_QTY);
uint256 actualUSDCReceived = usdc.balanceOf(address(this)).sub(
beforeUSDCBalance
);
totalFundsInUSDC = totalFundsInUSDC.add(actualUSDCReceived);
}
/**
* @notice Registers `msg.sender` as a manager.
* @param _donationInUSDC the amount of USDC to be used for registration
*/
function __register(uint256 _donationInUSDC) internal {
require(
cToken.balanceOf(msg.sender) == 0 &&
userInvestments[msg.sender].length == 0 &&
userCompoundOrders[msg.sender].length == 0
); // each address can only join once
// mint REP for msg.sender
uint256 repAmount = _donationInUSDC.mul(PRECISION).div(reptokenPrice);
require(cToken.generateTokens(msg.sender, repAmount));
// Set risk fallback base stake
_baseRiskStakeFallback[msg.sender] = repAmount;
// Set last active cycle for msg.sender to be the current cycle
_lastActiveCycle[msg.sender] = cycleNumber;
// keep USDC in the fund
totalFundsInUSDC = totalFundsInUSDC.add(_donationInUSDC);
// emit events
emit Register(msg.sender, _donationInUSDC, repAmount);
}
/**
* @notice Handles deposits by minting PeakDeFi Shares & updating total funds.
* @param _depositUSDCAmount The amount of the deposit in USDC
* @param _referrer The deposit referrer
*/
function __deposit(uint256 _depositUSDCAmount, address _referrer) internal {
// Register investment and give shares
uint256 shareAmount;
if (sToken.totalSupply() == 0 || totalFundsInUSDC == 0) {
uint256 usdcDecimals = getDecimals(usdc);
shareAmount = _depositUSDCAmount.mul(PRECISION).div(10**usdcDecimals);
} else {
shareAmount = _depositUSDCAmount.mul(sToken.totalSupply()).div(
totalFundsInUSDC
);
}
require(sToken.generateTokens(msg.sender, shareAmount));
totalFundsInUSDC = totalFundsInUSDC.add(_depositUSDCAmount);
totalFundsAtManagePhaseStart = totalFundsAtManagePhaseStart.add(
_depositUSDCAmount
);
// Handle peakReferralToken
if (peakReward.canRefer(msg.sender, _referrer)) {
peakReward.refer(msg.sender, _referrer);
}
address actualReferrer = peakReward.referrerOf(msg.sender);
if (actualReferrer != address(0)) {
require(
peakReferralToken.generateTokens(actualReferrer, shareAmount)
);
}
}
/**
* @notice Handles deposits by burning PeakDeFi Shares & updating total funds.
* @param _withdrawUSDCAmount The amount of the withdrawal in USDC
*/
function __withdraw(uint256 _withdrawUSDCAmount) internal {
// Burn Shares
uint256 shareAmount = _withdrawUSDCAmount.mul(sToken.totalSupply()).div(
totalFundsInUSDC
);
require(sToken.destroyTokens(msg.sender, shareAmount));
totalFundsInUSDC = totalFundsInUSDC.sub(_withdrawUSDCAmount);
// Handle peakReferralToken
address actualReferrer = peakReward.referrerOf(msg.sender);
if (actualReferrer != address(0)) {
uint256 balance = peakReferralToken.balanceOf(actualReferrer);
uint256 burnReferralTokenAmount = shareAmount > balance
? balance
: shareAmount;
require(
peakReferralToken.destroyTokens(
actualReferrer,
burnReferralTokenAmount
)
);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >= 0.4.22 <0.8.0;
library console {
address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67);
function _sendLogPayload(bytes memory payload) private view {
uint256 payloadLength = payload.length;
address consoleAddress = CONSOLE_ADDRESS;
assembly {
let payloadStart := add(payload, 32)
let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0)
}
}
function log() internal view {
_sendLogPayload(abi.encodeWithSignature("log()"));
}
function logInt(int p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(int)", p0));
}
function logUint(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function logString(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function logBool(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function logAddress(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function logBytes(bytes memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes)", p0));
}
function logByte(byte p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(byte)", p0));
}
function logBytes1(bytes1 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0));
}
function logBytes2(bytes2 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0));
}
function logBytes3(bytes3 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0));
}
function logBytes4(bytes4 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0));
}
function logBytes5(bytes5 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0));
}
function logBytes6(bytes6 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0));
}
function logBytes7(bytes7 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0));
}
function logBytes8(bytes8 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0));
}
function logBytes9(bytes9 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0));
}
function logBytes10(bytes10 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0));
}
function logBytes11(bytes11 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0));
}
function logBytes12(bytes12 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0));
}
function logBytes13(bytes13 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0));
}
function logBytes14(bytes14 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0));
}
function logBytes15(bytes15 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0));
}
function logBytes16(bytes16 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0));
}
function logBytes17(bytes17 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0));
}
function logBytes18(bytes18 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0));
}
function logBytes19(bytes19 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0));
}
function logBytes20(bytes20 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0));
}
function logBytes21(bytes21 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0));
}
function logBytes22(bytes22 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0));
}
function logBytes23(bytes23 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0));
}
function logBytes24(bytes24 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0));
}
function logBytes25(bytes25 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0));
}
function logBytes26(bytes26 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0));
}
function logBytes27(bytes27 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0));
}
function logBytes28(bytes28 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0));
}
function logBytes29(bytes29 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0));
}
function logBytes30(bytes30 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0));
}
function logBytes31(bytes31 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0));
}
function logBytes32(bytes32 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0));
}
function log(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function log(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function log(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function log(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function log(uint p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1));
}
function log(uint p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1));
}
function log(uint p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1));
}
function log(uint p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1));
}
function log(string memory p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1));
}
function log(string memory p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1));
}
function log(string memory p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1));
}
function log(string memory p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1));
}
function log(bool p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1));
}
function log(bool p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1));
}
function log(bool p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1));
}
function log(bool p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1));
}
function log(address p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1));
}
function log(address p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1));
}
function log(address p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1));
}
function log(address p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1));
}
function log(uint p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2));
}
function log(uint p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2));
}
function log(uint p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2));
}
function log(uint p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2));
}
function log(uint p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2));
}
function log(uint p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2));
}
function log(uint p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2));
}
function log(uint p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2));
}
function log(uint p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2));
}
function log(uint p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2));
}
function log(uint p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2));
}
function log(uint p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2));
}
function log(uint p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2));
}
function log(uint p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2));
}
function log(uint p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2));
}
function log(uint p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2));
}
function log(string memory p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2));
}
function log(string memory p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2));
}
function log(string memory p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2));
}
function log(string memory p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2));
}
function log(string memory p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2));
}
function log(string memory p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2));
}
function log(string memory p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2));
}
function log(string memory p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2));
}
function log(string memory p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2));
}
function log(string memory p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2));
}
function log(string memory p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2));
}
function log(string memory p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2));
}
function log(string memory p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2));
}
function log(string memory p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2));
}
function log(string memory p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2));
}
function log(string memory p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2));
}
function log(bool p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2));
}
function log(bool p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2));
}
function log(bool p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2));
}
function log(bool p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2));
}
function log(bool p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2));
}
function log(bool p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2));
}
function log(bool p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2));
}
function log(bool p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2));
}
function log(bool p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2));
}
function log(bool p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2));
}
function log(bool p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2));
}
function log(bool p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2));
}
function log(bool p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2));
}
function log(bool p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2));
}
function log(bool p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2));
}
function log(bool p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2));
}
function log(address p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2));
}
function log(address p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2));
}
function log(address p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2));
}
function log(address p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2));
}
function log(address p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2));
}
function log(address p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2));
}
function log(address p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2));
}
function log(address p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2));
}
function log(address p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2));
}
function log(address p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2));
}
function log(address p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2));
}
function log(address p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2));
}
function log(address p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2));
}
function log(address p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2));
}
function log(address p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2));
}
function log(address p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2));
}
function log(uint p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3));
}
}
pragma solidity 0.5.17;
import "./PeakDeFiStorage.sol";
contract PeakDeFiLogic3 is
PeakDeFiStorage,
Utils(address(0), address(0), address(0))
{
/**
* @notice Passes if the fund has not finalized the next smart contract to upgrade to
*/
modifier notReadyForUpgrade {
require(hasFinalizedNextVersion == false);
_;
}
/**
* @notice Executes function only during the given cycle phase.
* @param phase the cycle phase during which the function may be called
*/
modifier during(CyclePhase phase) {
require(cyclePhase == phase);
if (cyclePhase == CyclePhase.Intermission) {
require(isInitialized);
}
_;
}
/**
* Next phase transition handler
* @notice Moves the fund to the next phase in the investment cycle.
*/
function nextPhase() public nonReentrant {
require(
now >= startTimeOfCyclePhase.add(phaseLengths[uint256(cyclePhase)])
);
if (isInitialized == false) {
// first cycle of this smart contract deployment
// check whether ready for starting cycle
isInitialized = true;
require(proxyAddr != address(0)); // has initialized proxy
require(proxy.peakdefiFundAddress() == address(this)); // upgrade complete
require(hasInitializedTokenListings); // has initialized token listings
// execute initialization function
__init();
require(
previousVersion == address(0) ||
(previousVersion != address(0) &&
getBalance(usdc, address(this)) > 0)
); // has transfered assets from previous version
} else {
// normal phase changing
if (cyclePhase == CyclePhase.Intermission) {
require(hasFinalizedNextVersion == false); // Shouldn't progress to next phase if upgrading
// Update total funds at management phase's beginning
totalFundsAtManagePhaseStart = totalFundsInUSDC;
// reset number of managers onboarded
managersOnboardedThisCycle = 0;
} else if (cyclePhase == CyclePhase.Manage) {
// Burn any RepToken left in PeakDeFiFund's account
require(
cToken.destroyTokens(
address(this),
cToken.balanceOf(address(this))
)
);
// Pay out commissions and fees
uint256 profit = 0;
uint256 usdcBalanceAtManagePhaseStart
= totalFundsAtManagePhaseStart.add(totalCommissionLeft);
if (
getBalance(usdc, address(this)) >
usdcBalanceAtManagePhaseStart
) {
profit = getBalance(usdc, address(this)).sub(
usdcBalanceAtManagePhaseStart
);
}
totalFundsInUSDC = getBalance(usdc, address(this))
.sub(totalCommissionLeft)
.sub(peakReferralTotalCommissionLeft);
// Calculate manager commissions
uint256 commissionThisCycle = COMMISSION_RATE
.mul(profit)
.add(ASSET_FEE_RATE.mul(totalFundsInUSDC))
.div(PRECISION);
_totalCommissionOfCycle[cycleNumber] = totalCommissionOfCycle(
cycleNumber
)
.add(commissionThisCycle); // account for penalties
totalCommissionLeft = totalCommissionLeft.add(
commissionThisCycle
);
// Calculate referrer commissions
uint256 peakReferralCommissionThisCycle = PEAK_COMMISSION_RATE
.mul(profit)
.mul(peakReferralToken.totalSupply())
.div(sToken.totalSupply())
.div(PRECISION);
_peakReferralTotalCommissionOfCycle[cycleNumber] = peakReferralTotalCommissionOfCycle(
cycleNumber
)
.add(peakReferralCommissionThisCycle);
peakReferralTotalCommissionLeft = peakReferralTotalCommissionLeft
.add(peakReferralCommissionThisCycle);
totalFundsInUSDC = getBalance(usdc, address(this))
.sub(totalCommissionLeft)
.sub(peakReferralTotalCommissionLeft);
// Give the developer PeakDeFi shares inflation funding
uint256 devFunding = devFundingRate
.mul(sToken.totalSupply())
.div(PRECISION);
require(sToken.generateTokens(devFundingAccount, devFunding));
// Emit event
emit TotalCommissionPaid(
cycleNumber,
totalCommissionOfCycle(cycleNumber)
);
emit PeakReferralTotalCommissionPaid(
cycleNumber,
peakReferralTotalCommissionOfCycle(cycleNumber)
);
_managePhaseEndBlock[cycleNumber] = block.number;
// Clear/update upgrade related data
if (nextVersion == address(this)) {
// The developer proposed a candidate, but the managers decide to not upgrade at all
// Reset upgrade process
delete nextVersion;
delete hasFinalizedNextVersion;
}
if (nextVersion != address(0)) {
hasFinalizedNextVersion = true;
emit FinalizedNextVersion(cycleNumber, nextVersion);
}
// Start new cycle
cycleNumber = cycleNumber.add(1);
}
cyclePhase = CyclePhase(addmod(uint256(cyclePhase), 1, 2));
}
startTimeOfCyclePhase = now;
// Reward caller if they're a manager
if (cToken.balanceOf(msg.sender) > 0) {
require(cToken.generateTokens(msg.sender, NEXT_PHASE_REWARD));
}
emit ChangedPhase(
cycleNumber,
uint256(cyclePhase),
now,
totalFundsInUSDC
);
}
/**
* @notice Initializes several important variables after smart contract upgrade
*/
function __init() internal {
_managePhaseEndBlock[cycleNumber.sub(1)] = block.number;
// load values from previous version
totalCommissionLeft = previousVersion == address(0)
? 0
: PeakDeFiStorage(previousVersion).totalCommissionLeft();
totalFundsInUSDC = getBalance(usdc, address(this)).sub(
totalCommissionLeft
);
}
/**
* Upgrading functions
*/
/**
* @notice Allows the developer to propose a candidate smart contract for the fund to upgrade to.
* The developer may change the candidate during the Intermission phase.
* @param _candidate the address of the candidate smart contract
* @return True if successfully changed candidate, false otherwise.
*/
function developerInitiateUpgrade(address payable _candidate)
public
onlyOwner
notReadyForUpgrade
during(CyclePhase.Intermission)
nonReentrant
returns (bool _success)
{
if (_candidate == address(0) || _candidate == address(this)) {
return false;
}
nextVersion = _candidate;
emit DeveloperInitiatedUpgrade(cycleNumber, _candidate);
return true;
}
/**
Commission functions
*/
/**
* @notice Returns the commission balance of `_manager`
* @return the commission balance and the received penalty, denoted in USDC
*/
function commissionBalanceOf(address _manager)
public
view
returns (uint256 _commission, uint256 _penalty)
{
if (lastCommissionRedemption(_manager) >= cycleNumber) {
return (0, 0);
}
uint256 cycle = lastCommissionRedemption(_manager) > 0
? lastCommissionRedemption(_manager)
: 1;
uint256 cycleCommission;
uint256 cyclePenalty;
for (; cycle < cycleNumber; cycle++) {
(cycleCommission, cyclePenalty) = commissionOfAt(_manager, cycle);
_commission = _commission.add(cycleCommission);
_penalty = _penalty.add(cyclePenalty);
}
}
/**
* @notice Returns the commission amount received by `_manager` in the `_cycle`th cycle
* @return the commission amount and the received penalty, denoted in USDC
*/
function commissionOfAt(address _manager, uint256 _cycle)
public
view
returns (uint256 _commission, uint256 _penalty)
{
if (hasRedeemedCommissionForCycle(_manager, _cycle)) {
return (0, 0);
}
// take risk into account
uint256 baseRepTokenBalance = cToken.balanceOfAt(
_manager,
managePhaseEndBlock(_cycle.sub(1))
);
uint256 baseStake = baseRepTokenBalance == 0
? baseRiskStakeFallback(_manager)
: baseRepTokenBalance;
if (baseRepTokenBalance == 0 && baseRiskStakeFallback(_manager) == 0) {
return (0, 0);
}
uint256 riskTakenProportion = riskTakenInCycle(_manager, _cycle)
.mul(PRECISION)
.div(baseStake.mul(MIN_RISK_TIME)); // risk / threshold
riskTakenProportion = riskTakenProportion > PRECISION
? PRECISION
: riskTakenProportion; // max proportion is 1
uint256 fullCommission = totalCommissionOfCycle(_cycle)
.mul(cToken.balanceOfAt(_manager, managePhaseEndBlock(_cycle)))
.div(cToken.totalSupplyAt(managePhaseEndBlock(_cycle)));
_commission = fullCommission.mul(riskTakenProportion).div(PRECISION);
_penalty = fullCommission.sub(_commission);
}
/**
* @notice Redeems commission.
*/
function redeemCommission(bool _inShares)
public
during(CyclePhase.Intermission)
nonReentrant
{
uint256 commission = __redeemCommission();
if (_inShares) {
// Deposit commission into fund
__deposit(commission);
// Emit deposit event
emit Deposit(
cycleNumber,
msg.sender,
USDC_ADDR,
commission,
commission,
now
);
} else {
// Transfer the commission in USDC
usdc.safeTransfer(msg.sender, commission);
}
}
/**
* @notice Redeems commission for a particular cycle.
* @param _inShares true to redeem in PeakDeFi Shares, false to redeem in USDC
* @param _cycle the cycle for which the commission will be redeemed.
* Commissions for a cycle will be redeemed during the Intermission phase of the next cycle, so _cycle must < cycleNumber.
*/
function redeemCommissionForCycle(bool _inShares, uint256 _cycle)
public
during(CyclePhase.Intermission)
nonReentrant
{
require(_cycle < cycleNumber);
uint256 commission = __redeemCommissionForCycle(_cycle);
if (_inShares) {
// Deposit commission into fund
__deposit(commission);
// Emit deposit event
emit Deposit(
cycleNumber,
msg.sender,
USDC_ADDR,
commission,
commission,
now
);
} else {
// Transfer the commission in USDC
usdc.safeTransfer(msg.sender, commission);
}
}
/**
* @notice Redeems the commission for all previous cycles. Updates the related variables.
* @return the amount of commission to be redeemed
*/
function __redeemCommission() internal returns (uint256 _commission) {
require(lastCommissionRedemption(msg.sender) < cycleNumber);
uint256 penalty; // penalty received for not taking enough risk
(_commission, penalty) = commissionBalanceOf(msg.sender);
// record the redemption to prevent double-redemption
for (
uint256 i = lastCommissionRedemption(msg.sender);
i < cycleNumber;
i++
) {
_hasRedeemedCommissionForCycle[msg.sender][i] = true;
}
_lastCommissionRedemption[msg.sender] = cycleNumber;
// record the decrease in commission pool
totalCommissionLeft = totalCommissionLeft.sub(_commission);
// include commission penalty to this cycle's total commission pool
_totalCommissionOfCycle[cycleNumber] = totalCommissionOfCycle(
cycleNumber
)
.add(penalty);
// clear investment arrays to save space
delete userInvestments[msg.sender];
delete userCompoundOrders[msg.sender];
emit CommissionPaid(cycleNumber, msg.sender, _commission);
}
/**
* @notice Redeems commission for a particular cycle. Updates the related variables.
* @param _cycle the cycle for which the commission will be redeemed
* @return the amount of commission to be redeemed
*/
function __redeemCommissionForCycle(uint256 _cycle)
internal
returns (uint256 _commission)
{
require(!hasRedeemedCommissionForCycle(msg.sender, _cycle));
uint256 penalty; // penalty received for not taking enough risk
(_commission, penalty) = commissionOfAt(msg.sender, _cycle);
_hasRedeemedCommissionForCycle[msg.sender][_cycle] = true;
// record the decrease in commission pool
totalCommissionLeft = totalCommissionLeft.sub(_commission);
// include commission penalty to this cycle's total commission pool
_totalCommissionOfCycle[cycleNumber] = totalCommissionOfCycle(
cycleNumber
)
.add(penalty);
// clear investment arrays to save space
delete userInvestments[msg.sender];
delete userCompoundOrders[msg.sender];
emit CommissionPaid(_cycle, msg.sender, _commission);
}
/**
* @notice Handles deposits by minting PeakDeFi Shares & updating total funds.
* @param _depositUSDCAmount The amount of the deposit in USDC
*/
function __deposit(uint256 _depositUSDCAmount) internal {
// Register investment and give shares
if (sToken.totalSupply() == 0 || totalFundsInUSDC == 0) {
require(sToken.generateTokens(msg.sender, _depositUSDCAmount));
} else {
require(
sToken.generateTokens(
msg.sender,
_depositUSDCAmount.mul(sToken.totalSupply()).div(
totalFundsInUSDC
)
)
);
}
totalFundsInUSDC = totalFundsInUSDC.add(_depositUSDCAmount);
}
/**
PeakDeFi
*/
/**
* @notice Returns the commission balance of `_referrer`
* @return the commission balance, denoted in USDC
*/
function peakReferralCommissionBalanceOf(address _referrer)
public
view
returns (uint256 _commission)
{
if (peakReferralLastCommissionRedemption(_referrer) >= cycleNumber) {
return (0);
}
uint256 cycle = peakReferralLastCommissionRedemption(_referrer) > 0
? peakReferralLastCommissionRedemption(_referrer)
: 1;
uint256 cycleCommission;
for (; cycle < cycleNumber; cycle++) {
(cycleCommission) = peakReferralCommissionOfAt(_referrer, cycle);
_commission = _commission.add(cycleCommission);
}
}
/**
* @notice Returns the commission amount received by `_referrer` in the `_cycle`th cycle
* @return the commission amount, denoted in USDC
*/
function peakReferralCommissionOfAt(address _referrer, uint256 _cycle)
public
view
returns (uint256 _commission)
{
_commission = peakReferralTotalCommissionOfCycle(_cycle)
.mul(
peakReferralToken.balanceOfAt(
_referrer,
managePhaseEndBlock(_cycle)
)
)
.div(peakReferralToken.totalSupplyAt(managePhaseEndBlock(_cycle)));
}
/**
* @notice Redeems commission.
*/
function peakReferralRedeemCommission()
public
during(CyclePhase.Intermission)
nonReentrant
{
uint256 commission = __peakReferralRedeemCommission();
// Transfer the commission in USDC
usdc.safeApprove(address(peakReward), commission);
peakReward.payCommission(msg.sender, address(usdc), commission, false);
}
/**
* @notice Redeems commission for a particular cycle.
* @param _cycle the cycle for which the commission will be redeemed.
* Commissions for a cycle will be redeemed during the Intermission phase of the next cycle, so _cycle must < cycleNumber.
*/
function peakReferralRedeemCommissionForCycle(uint256 _cycle)
public
during(CyclePhase.Intermission)
nonReentrant
{
require(_cycle < cycleNumber);
uint256 commission = __peakReferralRedeemCommissionForCycle(_cycle);
// Transfer the commission in USDC
usdc.safeApprove(address(peakReward), commission);
peakReward.payCommission(msg.sender, address(usdc), commission, false);
}
/**
* @notice Redeems the commission for all previous cycles. Updates the related variables.
* @return the amount of commission to be redeemed
*/
function __peakReferralRedeemCommission()
internal
returns (uint256 _commission)
{
require(peakReferralLastCommissionRedemption(msg.sender) < cycleNumber);
_commission = peakReferralCommissionBalanceOf(msg.sender);
// record the redemption to prevent double-redemption
for (
uint256 i = peakReferralLastCommissionRedemption(msg.sender);
i < cycleNumber;
i++
) {
_peakReferralHasRedeemedCommissionForCycle[msg.sender][i] = true;
}
_peakReferralLastCommissionRedemption[msg.sender] = cycleNumber;
// record the decrease in commission pool
peakReferralTotalCommissionLeft = peakReferralTotalCommissionLeft.sub(
_commission
);
emit PeakReferralCommissionPaid(cycleNumber, msg.sender, _commission);
}
/**
* @notice Redeems commission for a particular cycle. Updates the related variables.
* @param _cycle the cycle for which the commission will be redeemed
* @return the amount of commission to be redeemed
*/
function __peakReferralRedeemCommissionForCycle(uint256 _cycle)
internal
returns (uint256 _commission)
{
require(!peakReferralHasRedeemedCommissionForCycle(msg.sender, _cycle));
_commission = peakReferralCommissionOfAt(msg.sender, _cycle);
_peakReferralHasRedeemedCommissionForCycle[msg.sender][_cycle] = true;
// record the decrease in commission pool
peakReferralTotalCommissionLeft = peakReferralTotalCommissionLeft.sub(
_commission
);
emit PeakReferralCommissionPaid(_cycle, msg.sender, _commission);
}
}
pragma solidity 0.5.17;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20Detailed.sol";
import "../interfaces/CERC20.sol";
import "../interfaces/Comptroller.sol";
contract TestCERC20 is CERC20 {
using SafeMath for uint;
uint public constant PRECISION = 10 ** 18;
uint public constant MAX_UINT = 2 ** 256 - 1;
address public _underlying;
uint public _exchangeRateCurrent = 10 ** (18 - 8) * PRECISION;
mapping(address => uint) public _balanceOf;
mapping(address => uint) public _borrowBalanceCurrent;
Comptroller public COMPTROLLER;
constructor(address __underlying, address _comptrollerAddr) public {
_underlying = __underlying;
COMPTROLLER = Comptroller(_comptrollerAddr);
}
function mint(uint mintAmount) external returns (uint) {
ERC20Detailed token = ERC20Detailed(_underlying);
require(token.transferFrom(msg.sender, address(this), mintAmount));
_balanceOf[msg.sender] = _balanceOf[msg.sender].add(mintAmount.mul(10 ** this.decimals()).div(PRECISION));
return 0;
}
function redeemUnderlying(uint redeemAmount) external returns (uint) {
_balanceOf[msg.sender] = _balanceOf[msg.sender].sub(redeemAmount.mul(10 ** this.decimals()).div(PRECISION));
ERC20Detailed token = ERC20Detailed(_underlying);
require(token.transfer(msg.sender, redeemAmount));
return 0;
}
function borrow(uint amount) external returns (uint) {
// add to borrow balance
_borrowBalanceCurrent[msg.sender] = _borrowBalanceCurrent[msg.sender].add(amount);
// transfer asset
ERC20Detailed token = ERC20Detailed(_underlying);
require(token.transfer(msg.sender, amount));
return 0;
}
function repayBorrow(uint amount) external returns (uint) {
// accept repayment
ERC20Detailed token = ERC20Detailed(_underlying);
uint256 repayAmount = amount == MAX_UINT ? _borrowBalanceCurrent[msg.sender] : amount;
require(token.transferFrom(msg.sender, address(this), repayAmount));
// subtract from borrow balance
_borrowBalanceCurrent[msg.sender] = _borrowBalanceCurrent[msg.sender].sub(repayAmount);
return 0;
}
function balanceOf(address account) external view returns (uint) { return _balanceOf[account]; }
function borrowBalanceCurrent(address account) external returns (uint) { return _borrowBalanceCurrent[account]; }
function underlying() external view returns (address) { return _underlying; }
function exchangeRateCurrent() external returns (uint) { return _exchangeRateCurrent; }
function decimals() external view returns (uint) { return 8; }
}
pragma solidity 0.5.17;
import "./TestCERC20.sol";
contract TestCERC20Factory {
mapping(address => address) public createdTokens;
event CreatedToken(address underlying, address cToken);
function newToken(address underlying, address comptroller) public returns(address) {
require(createdTokens[underlying] == address(0));
TestCERC20 token = new TestCERC20(underlying, comptroller);
createdTokens[underlying] = address(token);
emit CreatedToken(underlying, address(token));
return address(token);
}
}
pragma solidity 0.5.17;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../interfaces/CEther.sol";
import "../interfaces/Comptroller.sol";
contract TestCEther is CEther {
using SafeMath for uint;
uint public constant PRECISION = 10 ** 18;
uint public _exchangeRateCurrent = 10 ** (18 - 8) * PRECISION;
mapping(address => uint) public _balanceOf;
mapping(address => uint) public _borrowBalanceCurrent;
Comptroller public COMPTROLLER;
constructor(address _comptrollerAddr) public {
COMPTROLLER = Comptroller(_comptrollerAddr);
}
function mint() external payable {
_balanceOf[msg.sender] = _balanceOf[msg.sender].add(msg.value.mul(10 ** this.decimals()).div(PRECISION));
}
function redeemUnderlying(uint redeemAmount) external returns (uint) {
_balanceOf[msg.sender] = _balanceOf[msg.sender].sub(redeemAmount.mul(10 ** this.decimals()).div(PRECISION));
msg.sender.transfer(redeemAmount);
return 0;
}
function borrow(uint amount) external returns (uint) {
// add to borrow balance
_borrowBalanceCurrent[msg.sender] = _borrowBalanceCurrent[msg.sender].add(amount);
// transfer asset
msg.sender.transfer(amount);
return 0;
}
function repayBorrow() external payable {
_borrowBalanceCurrent[msg.sender] = _borrowBalanceCurrent[msg.sender].sub(msg.value);
}
function balanceOf(address account) external view returns (uint) { return _balanceOf[account]; }
function borrowBalanceCurrent(address account) external returns (uint) { return _borrowBalanceCurrent[account]; }
function exchangeRateCurrent() external returns (uint) { return _exchangeRateCurrent; }
function decimals() external view returns (uint) { return 8; }
function() external payable {}
}
pragma solidity 0.5.17;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../interfaces/Comptroller.sol";
import "../interfaces/PriceOracle.sol";
import "../interfaces/CERC20.sol";
contract TestComptroller is Comptroller {
using SafeMath for uint;
uint256 internal constant PRECISION = 10 ** 18;
mapping(address => address[]) public getAssetsIn;
uint256 internal collateralFactor = 2 * PRECISION / 3;
constructor() public {}
function enterMarkets(address[] calldata cTokens) external returns (uint[] memory) {
uint[] memory errors = new uint[](cTokens.length);
for (uint256 i = 0; i < cTokens.length; i = i.add(1)) {
getAssetsIn[msg.sender].push(cTokens[i]);
errors[i] = 0;
}
return errors;
}
function markets(address /*cToken*/) external view returns (bool isListed, uint256 collateralFactorMantissa) {
return (true, collateralFactor);
}
}
pragma solidity 0.5.17;
import "../interfaces/KyberNetwork.sol";
import "../Utils.sol";
import "@openzeppelin/contracts/ownership/Ownable.sol";
contract TestKyberNetwork is KyberNetwork, Utils(address(0), address(0), address(0)), Ownable {
mapping(address => uint256) public priceInUSDC;
constructor(address[] memory _tokens, uint256[] memory _pricesInUSDC) public {
for (uint256 i = 0; i < _tokens.length; i = i.add(1)) {
priceInUSDC[_tokens[i]] = _pricesInUSDC[i];
}
}
function setTokenPrice(address _token, uint256 _priceInUSDC) public onlyOwner {
priceInUSDC[_token] = _priceInUSDC;
}
function setAllTokenPrices(address[] memory _tokens, uint256[] memory _pricesInUSDC) public onlyOwner {
for (uint256 i = 0; i < _tokens.length; i = i.add(1)) {
priceInUSDC[_tokens[i]] = _pricesInUSDC[i];
}
}
function getExpectedRate(ERC20Detailed src, ERC20Detailed dest, uint /*srcQty*/) external view returns (uint expectedRate, uint slippageRate)
{
uint256 result = priceInUSDC[address(src)].mul(10**getDecimals(dest)).mul(PRECISION).div(priceInUSDC[address(dest)].mul(10**getDecimals(src)));
return (result, result);
}
function tradeWithHint(
ERC20Detailed src,
uint srcAmount,
ERC20Detailed dest,
address payable destAddress,
uint maxDestAmount,
uint /*minConversionRate*/,
address /*walletId*/,
bytes calldata /*hint*/
)
external
payable
returns(uint)
{
require(calcDestAmount(src, srcAmount, dest) <= maxDestAmount);
if (address(src) == address(ETH_TOKEN_ADDRESS)) {
require(srcAmount == msg.value);
} else {
require(src.transferFrom(msg.sender, address(this), srcAmount));
}
if (address(dest) == address(ETH_TOKEN_ADDRESS)) {
destAddress.transfer(calcDestAmount(src, srcAmount, dest));
} else {
require(dest.transfer(destAddress, calcDestAmount(src, srcAmount, dest)));
}
return calcDestAmount(src, srcAmount, dest);
}
function calcDestAmount(
ERC20Detailed src,
uint srcAmount,
ERC20Detailed dest
) internal view returns (uint destAmount) {
return srcAmount.mul(priceInUSDC[address(src)]).mul(10**getDecimals(dest)).div(priceInUSDC[address(dest)].mul(10**getDecimals(src)));
}
function() external payable {}
}
pragma solidity 0.5.17;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/ownership/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20Detailed.sol";
import "../interfaces/PriceOracle.sol";
import "../interfaces/CERC20.sol";
contract TestPriceOracle is PriceOracle, Ownable {
using SafeMath for uint;
uint public constant PRECISION = 10 ** 18;
address public CETH_ADDR;
mapping(address => uint256) public priceInUSD;
constructor(address[] memory _tokens, uint256[] memory _pricesInUSD, address _cETH) public {
for (uint256 i = 0; i < _tokens.length; i = i.add(1)) {
priceInUSD[_tokens[i]] = _pricesInUSD[i];
}
CETH_ADDR = _cETH;
}
function setTokenPrice(address _token, uint256 _priceInUSD) public onlyOwner {
priceInUSD[_token] = _priceInUSD;
}
function getUnderlyingPrice(address _cToken) external view returns (uint) {
if (_cToken == CETH_ADDR) {
return priceInUSD[_cToken];
}
CERC20 cToken = CERC20(_cToken);
ERC20Detailed underlying = ERC20Detailed(cToken.underlying());
return priceInUSD[_cToken].mul(PRECISION).div(10 ** uint256(underlying.decimals()));
}
}
pragma solidity 0.5.17;
import "@openzeppelin/contracts/token/ERC20/ERC20Mintable.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20Detailed.sol";
/**
* @title An ERC20 token used for testing.
* @author Zefram Lou (Zebang Liu)
*/
contract TestToken is ERC20Mintable, ERC20Burnable, ERC20Detailed {
constructor(string memory name, string memory symbol, uint8 decimals)
public
ERC20Detailed(name, symbol, decimals)
{}
}
pragma solidity 0.5.17;
import "./TestToken.sol";
contract TestTokenFactory {
mapping(bytes32 => address) public createdTokens;
event CreatedToken(string symbol, address addr);
function newToken(string memory name, string memory symbol, uint8 decimals) public returns(address) {
bytes32 symbolHash = keccak256(abi.encodePacked(symbol));
require(createdTokens[symbolHash] == address(0));
TestToken token = new TestToken(name, symbol, decimals);
token.addMinter(msg.sender);
token.renounceMinter();
createdTokens[symbolHash] = address(token);
emit CreatedToken(symbol, address(token));
return address(token);
}
function getToken(string memory symbol) public view returns(address) {
return createdTokens[keccak256(abi.encodePacked(symbol))];
}
}
pragma solidity 0.5.17;
contract TestUniswapOracle {
function update() external returns (bool success) {
return true;
}
function consult(address token, uint256 amountIn)
external
view
returns (uint256 amountOut)
{
return 3 * 10**5; // 1 PEAK = 0.30 USDC
}
}
| Withdraws Ether by burning Shares. _amountInUSDC Amount of funds to be withdrawn expressed in USDC. Fixed-point decimal. May be different from actual amount./ Transfer USDC to user Emit event | function withdrawUSDC(uint256 _amountInUSDC)
external
nonReentrant
during(CyclePhase.Intermission)
{
__withdraw(_amountInUSDC);
usdc.safeTransfer(msg.sender, _amountInUSDC);
emit Withdraw(
cycleNumber,
msg.sender,
USDC_ADDR,
_amountInUSDC,
_amountInUSDC,
now
);
}
| 15,852,063 |
./full_match/1/0x833f7bDa72AcDbE7acA33F28d00bBF2dF20682d6/sources/contracts/core/ACL.sol | Returns true if the address is unpausable admin and false if not | function isUnpausableAdmin(address addr) external view returns (bool) {
}
| 4,976,333 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.12;
import "@openzeppelin/contracts/utils/Strings.sol";
import "../interfaces/ISVGTypes.sol";
import "./OnChain.sol";
import "./SVGErrors.sol";
/// @title SVG image library
/**
* @dev These methods are best suited towards view/pure only function calls (ALL the way through the call stack).
* Do not waste gas using these methods in functions that also update state, unless your need requires it.
*/
library SVG {
using Strings for uint256;
/// Returns a named element based on the supplied attributes and contents
/// @dev attributes and contents is usually generated from string.concat, attributes is expecting a leading space
/// @param name The name of the element
/// @param attributes The attributes of the element, with a leading space
/// @param contents The contents of the element
/// @return a string representing the whole element
function createElement(string memory name, string memory attributes, string memory contents) internal pure returns (string memory) {
return string.concat(
"<", bytes(attributes).length == 0 ? name : string.concat(name, attributes),
bytes(contents).length == 0 ? "/>" : string.concat(">", contents, "</", name, ">")
);
}
/// Returns the root SVG attributes based on the supplied width and height
/// @dev includes necessary leading space for createElement's `attributes` parameter
/// @param width The width of the SVG view box
/// @param height The height of the SVG view box
/// @return a string representing the root SVG attributes, including a leading space
function svgAttributes(uint256 width, uint256 height) internal pure returns (string memory) {
return string.concat(" viewBox='0 0 ", width.toString(), " ", height.toString(), "' xmlns='http://www.w3.org/2000/svg'");
}
/// Returns an RGB string suitable as an attribute for SVG elements based on the supplied Color and ColorType
/// @dev includes necessary leading space for all types _except_ None
/// @param attribute The `ISVGTypes.ColorAttribute` of the desired attribute
/// @param value The converted color value
/// @return a string representing a color attribute in an SVG element
function colorAttribute(ISVGTypes.ColorAttribute attribute, string memory value) internal pure returns (string memory) {
if (attribute == ISVGTypes.ColorAttribute.Fill) return _attribute("fill", value);
if (attribute == ISVGTypes.ColorAttribute.Stop) return _attribute("stop-color", value);
return _attribute("stroke", value); // Fallback to Stroke
}
/// Returns an RGB color attribute value
/// @param color The `ISVGTypes.Color` of the color
/// @return a string representing the url attribute value
function colorAttributeRGBValue(ISVGTypes.Color memory color) internal pure returns (string memory) {
return _colorValue(ISVGTypes.ColorAttributeKind.RGB, OnChain.commaSeparated(
uint256(color.red).toString(),
uint256(color.green).toString(),
uint256(color.blue).toString()
));
}
/// Returns a URL color attribute value
/// @param url The url to the color
/// @return a string representing the url attribute value
function colorAttributeURLValue(string memory url) internal pure returns (string memory) {
return _colorValue(ISVGTypes.ColorAttributeKind.URL, url);
}
/// Returns an `ISVGTypes.Color` that is brightened by the provided percentage
/// @param source The `ISVGTypes.Color` to brighten
/// @param percentage The percentage of brightness to apply
/// @param minimumBump A minimum increase for each channel to ensure dark Colors also brighten
/// @return color the brightened `ISVGTypes.Color`
function brightenColor(ISVGTypes.Color memory source, uint8 percentage, uint8 minimumBump) internal pure returns (ISVGTypes.Color memory color) {
color.red = _brightenComponent(source.red, percentage, minimumBump);
color.green = _brightenComponent(source.green, percentage, minimumBump);
color.blue = _brightenComponent(source.blue, percentage, minimumBump);
color.alpha = source.alpha;
}
/// Returns an `ISVGTypes.Color` based on a packed representation of r, g, and b
/// @notice Useful for code where you want to utilize rgb hex values provided by a designer (e.g. #835525)
/// @dev Alpha will be hard-coded to 100% opacity
/// @param packedColor The `ISVGTypes.Color` to convert, e.g. 0x835525
/// @return color representing the packed input
function fromPackedColor(uint24 packedColor) internal pure returns (ISVGTypes.Color memory color) {
color.red = uint8(packedColor >> 16);
color.green = uint8(packedColor >> 8);
color.blue = uint8(packedColor);
color.alpha = 0xFF;
}
/// Returns a mixed Color by balancing the ratio of `color1` over `color2`, with a total percentage (for overmixing and undermixing outside the source bounds)
/// @dev Reverts with `RatioInvalid()` if `ratioPercentage` is > 100
/// @param color1 The first `ISVGTypes.Color` to mix
/// @param color2 The second `ISVGTypes.Color` to mix
/// @param ratioPercentage The percentage ratio of `color1` over `color2` (e.g. 60 = 60% first, 40% second)
/// @param totalPercentage The total percentage after mixing (for overmixing and undermixing outside the input colors)
/// @return color representing the result of the mixture
function mixColors(ISVGTypes.Color memory color1, ISVGTypes.Color memory color2, uint8 ratioPercentage, uint8 totalPercentage) internal pure returns (ISVGTypes.Color memory color) {
if (ratioPercentage > 100) revert RatioInvalid();
color.red = _mixComponents(color1.red, color2.red, ratioPercentage, totalPercentage);
color.green = _mixComponents(color1.green, color2.green, ratioPercentage, totalPercentage);
color.blue = _mixComponents(color1.blue, color2.blue, ratioPercentage, totalPercentage);
color.alpha = _mixComponents(color1.alpha, color2.alpha, ratioPercentage, totalPercentage);
}
/// Returns a proportionally-randomized Color between the start and stop colors using a random Color seed
/// @dev Each component (r,g,b) will move proportionally together in the direction from start to stop
/// @param start The starting bound of the `ISVGTypes.Color` to randomize
/// @param stop The stopping bound of the `ISVGTypes.Color` to randomize
/// @param random An `ISVGTypes.Color` to use as a seed for randomization
/// @return color representing the result of the randomization
function randomizeColors(ISVGTypes.Color memory start, ISVGTypes.Color memory stop, ISVGTypes.Color memory random) internal pure returns (ISVGTypes.Color memory color) {
unchecked { // `percent` calculation is always within uint8 because of % 101
uint8 percent = uint8((1320 * (uint(random.red) + uint(random.green) + uint(random.blue)) / 10000) % 101); // Range is from 0-100
color.red = _randomizeComponent(start.red, stop.red, random.red, percent);
color.green = _randomizeComponent(start.green, stop.green, random.green, percent);
color.blue = _randomizeComponent(start.blue, stop.blue, random.blue, percent);
color.alpha = 0xFF;
}
}
function _attribute(string memory name, string memory contents) private pure returns (string memory) {
return string.concat(" ", name, "='", contents, "'");
}
function _brightenComponent(uint8 component, uint8 percentage, uint8 minimumBump) private pure returns (uint8 result) {
unchecked { // `brightenedComponent` is always >= `wideComponent` because of the +100
uint wideComponent = uint(component);
uint brightenedComponent = wideComponent * (uint(percentage) + 100) / 100;
uint wideMinimumBump = uint(minimumBump);
if (brightenedComponent - wideComponent < wideMinimumBump) {
brightenedComponent = wideComponent + wideMinimumBump;
}
if (brightenedComponent > 0xFF) {
result = 0xFF; // Clamp to 8 bits
} else {
result = uint8(brightenedComponent);
}
}
}
function _colorValue(ISVGTypes.ColorAttributeKind attributeKind, string memory contents) private pure returns (string memory) {
return string.concat(attributeKind == ISVGTypes.ColorAttributeKind.RGB ? "rgb(" : "url(#", contents, ")");
}
function _mixComponents(uint8 component1, uint8 component2, uint8 ratioPercentage, uint8 totalPercentage) private pure returns (uint8 component) {
unchecked { // `ratioPercentage` is <= 100 because of the check in mixColors()
uint mixedComponent = (uint(component1) * ratioPercentage + uint(component2) * (100 - uint(ratioPercentage))) * uint(totalPercentage) / 10000;
if (mixedComponent > 0xFF) {
component = 0xFF; // Clamp to 8 bits
} else {
component = uint8(mixedComponent);
}
}
}
function _randomizeComponent(uint8 start, uint8 stop, uint8 random, uint8 percent) private pure returns (uint8 component) {
if (start == stop) {
component = start;
} else { // This is the standard case
(uint8 floor, uint8 ceiling) = start < stop ? (start, stop) : (stop, start);
unchecked { // `ceiling` is always > `floor`, thus -1 from `random` is ok
component = floor + uint8(uint(ceiling - (random & 0x01) - floor) * uint(percent) / 100);
}
}
}
}
| Returns the root SVG attributes based on the supplied width and height includes necessary leading space for createElement's `attributes` parameter width The width of the SVG view box height The height of the SVG view box return a string representing the root SVG attributes, including a leading space | function svgAttributes(uint256 width, uint256 height) internal pure returns (string memory) {
}
| 14,079,883 |
./full_match/5/0xeBE40917F559cA552B4241e958193C08C9A570d4/sources/contracts/Lottery.sol | buy ticket transfer total cost to this contract store the fee amount store the remaining as current jackpot add player to the list | function buyTicket(uint256 _ticketAmount) external {
uint256 totalCost = ticketPrice.mul(_ticketAmount);
mockToken.transferFrom(msg.sender, address(this), totalCost);
uint256 fee = totalCost.mul(feeRate).div(10000);
withdrawableFeeAmount = withdrawableFeeAmount.add(fee);
uint256 remaining = totalCost.sub(fee);
currentPrizePoolAmount = currentPrizePoolAmount.add(remaining);
for (uint256 i = 0; i < _ticketAmount; i++) {
currentPlayers.push(msg.sender);
}
emit TicketPurchased(msg.sender, _ticketAmount, totalCost);
}
| 11,624,491 |
./full_match/1/0x2a8b06562A455A79f7027cEd093f1E9dC0fC53B2/sources/contracts/Controller.sol | revoke consumer role to old energy storage contract | function _setConverterLogic(address newContract) internal {
if (_isContract(address(_converterLogic))) {
_lbaEnergyStorage.removeConsumer(address(_converterLogic));
_energyStorage.removeConsumer(address(_converterLogic));
}
_converterLogic = Converter(newContract);
_converterLogic.init(
address(_dao),
address(_multisig),
address(_energyStorage),
address(_lbaEnergyStorage),
address(_stakingLogic)
);
_lbaEnergyStorage.addConsumer(newContract);
_energyStorage.addConsumer(newContract);
emit ContractUpgraded(block.timestamp, "Converter Logic", address(this), newContract);
}
| 2,906,624 |
./full_match/80001/0x71ce4a1Ac512a4384D967228232B0BBD1d2B4014/sources/contracts/other/Pi/PiDragonKingdomContract.sol | Enable only ERC-20 payments for minting on this contract/ | function enableERC20OnlyMinting() public onlyTeamOrOwner {
onlyERC20MintingMode = true;
}
| 874,633 |
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.6.11;
import "./Governable.sol";
contract Config is Governable {
event ConfigSet(bytes32 config, uint256 value);
mapping (bytes32 => uint256) private _config;
function initialize() external initializer {
super.initialize(msg.sender);
setConfig("PROVIDER_MINIMUM_ANKR_STAKING", 100000 ether);
setConfig("PROVIDER_MINIMUM_ETH_STAKING", 2 ether);
setConfig("REQUESTER_MINIMUM_POOL_STAKING", 500 finney);
setConfig("EXIT_BLOCKS", 24);
}
function setConfig(bytes32 config, uint256 value) public governance {
_config[config] = value;
}
function getConfig(bytes32 config) public view returns(uint256) {
return _config[config];
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "@openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol";
contract Governable is Initializable {
address public governor;
event GovernorshipTransferred(address indexed previousGovernor, address indexed newGovernor);
/**
* @dev Contract initializer.
* called once by the factory at time of deployment
*/
function initialize(address governor_) virtual public initializer {
governor = governor_;
emit GovernorshipTransferred(address(0), governor);
}
modifier governance() {
require(msg.sender == governor);
_;
}
/**
* @dev Allows the current governor to relinquish control of the contract.
* @notice Renouncing to governorship will leave the contract without an governor.
* It will not be possible to call the functions with the `governance.js`
* modifier anymore.
*/
function renounceGovernorship() public governance {
emit GovernorshipTransferred(governor, address(0));
governor = address(0);
}
/**
* @dev Allows the current governor to transfer control of the contract to a newGovernor.
* @param newGovernor The address to transfer governorship to.
*/
function transferGovernorship(address newGovernor) public governance {
_transferGovernorship(newGovernor);
}
/**
* @dev Transfers control of the contract to a newGovernor.
* @param newGovernor The address to transfer governorship to.
*/
function _transferGovernorship(address newGovernor) internal {
require(newGovernor != address(0));
emit GovernorshipTransferred(governor, newGovernor);
governor = newGovernor;
}
uint256[50] private __gap;
}
pragma solidity ^0.6.11;
contract Configurable {
mapping (bytes32 => uint) internal config;
mapping (bytes32 => string) internal configString;
mapping (bytes32 => address) internal configAddress;
function getConfig(bytes32 key) public view returns (uint) {
return config[key];
}
function getConfig(bytes32 key, uint index) public view returns (uint) {
return config[bytes32(uint(key) ^ index)];
}
function getConfig(bytes32 key, address addr) public view returns (uint) {
return config[bytes32(uint(key) ^ uint(addr))];
}
function _setConfig(bytes32 key, uint value) internal {
if(config[key] != value)
config[key] = value;
}
function _setConfig(bytes32 key, uint index, uint value) internal {
_setConfig(bytes32(uint(key) ^ index), value);
}
function _setConfig(bytes32 key, address addr, uint value) internal {
_setConfig(bytes32(uint(key) ^ uint(addr)), value);
}
function setConfig(bytes32 key, uint value) internal {
_setConfig(key, value);
}
function setConfig(bytes32 key, uint index, uint value) internal {
_setConfig(bytes32(uint(key) ^ index), value);
}
function setConfig(bytes32 key, address addr, uint value) internal {
_setConfig(bytes32(uint(key) ^ uint(addr)), value);
}
function getConfigString(bytes32 key) public view returns (string memory) {
return configString[key];
}
function getConfigString(bytes32 key, uint index) public view returns (string memory) {
return configString[bytes32(uint(key) ^ index)];
}
function setConfigString(bytes32 key, string memory value) internal {
configString[key] = value;
}
function setConfigString(bytes32 key, uint index, string memory value) internal {
setConfigString(bytes32(uint(key) ^ index), value);
}
function getConfigAddress(bytes32 key) public view returns (address) {
return configAddress[key];
}
function getConfigAddress(bytes32 key, uint index) public view returns (address) {
return configAddress[bytes32(uint(key) ^ index)];
}
function setConfigAddress(bytes32 key, address addr) internal {
configAddress[key] = addr;
}
function setConfigAddress(bytes32 key, uint index, address addr) internal {
setConfigAddress(bytes32(uint(key) ^ index), addr);
}
}
pragma solidity ^0.6.11;
abstract contract Lockable {
mapping(address => bool) private _locks;
modifier unlocked(address addr) {
require(!_locks[addr], "Reentrancy protection");
_locks[addr] = true;
_;
_locks[addr] = false;
}
uint256[50] private __gap;
}
pragma solidity 0.6.11;
import "@openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol";
contract Pausable is OwnableUpgradeSafe {
mapping (bytes32 => bool) internal _paused;
modifier whenNotPaused(bytes32 action) {
require(!_paused[action], "This action currently paused");
_;
}
function togglePause(bytes32 action) public onlyOwner {
_paused[action] = !_paused[action];
}
function isPaused(bytes32 action) public view returns(bool) {
return _paused[action];
}
uint256[50] private __gap;
}
pragma solidity ^0.6.11;
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol";
interface IAETH is IERC20 {
function burn(uint256 amount) external;
function updateMicroPoolContract(address microPoolContract) external;
function ratio() external view returns (uint256);
function mintFrozen(address account, uint256 amount) external;
function mint(address account, uint256 amount) external returns (uint256);
function mintApprovedTo(address account, address spender, uint256 amount) external;
function mintPool() payable external;
function fundPool(uint256 poolIndex, uint256 amount) external;
}
pragma solidity ^0.6.11;
interface IConfig {
function getConfig(bytes32 config) external view returns (uint256);
function setConfig(bytes32 config, uint256 value) external;
}
pragma solidity ^0.6.11;
interface IMarketPlace {
function ethUsdRate() external returns (uint256);
function ankrEthRate() external returns (uint256);
function burnAeth(uint256 etherAmount) external returns (uint256);
}
pragma solidity ^0.6.11;
interface IStaking {
function compensateLoss(address provider, uint256 ethAmount) external returns (bool, uint256, uint256);
function freeze(address user, uint256 amount) external returns (bool);
function unfreeze(address user, uint256 amount) external returns (bool);
function frozenStakesOf(address staker) external view returns (uint256);
function lockedDepositsOf(address staker) external view returns (uint256);
function stakesOf(address staker) external view returns (uint256);
function frozenDepositsOf(address staker) external view returns (uint256);
function depositsOf(address staker) external view returns (uint256);
function deposit() external;
function deposit(address user) external;
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.6.11;
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol";
import "../lib/Lockable.sol";
import "../lib/interfaces/IAETH.sol";
import "../lib/interfaces/IMarketPlace.sol";
import "../lib/Configurable.sol";
contract AnkrDeposit_R3 is OwnableUpgradeSafe, Lockable, Configurable {
using SafeMath for uint256;
event Deposit(
address indexed user,
uint256 value
);
// if ends at value is zero,
event Freeze(
address indexed user,
uint256 value,
uint256 endsAt
);
event Unfreeze(
address indexed user,
uint256 value
);
event Withdraw(
address indexed user,
uint256 value
);
event Compensate(address indexed provider, uint256 ankrAmount, uint256 etherAmount);
// DEV
// 0x100: aETH
// 0x101: 0x00
// 0x102: ANKR (0x0c5f1428e01e46dce4fc4052a58a8ff63ff19ca5)
// 0x103: global pool
// 0x104: 0x00
// 0x105: 0x4069d8a3de3a72eca86ca5e0a4b94619085e7362 (operator)
// GOERLI
// 0x100: 0x00
// 0x101: 0x00
// 0x102: aETH
// 0x103: 0x00
// 0x104: ANKR
// 0x105: global pool
// 0x106: 0x00
// 0x107: 0x00
// PROD
// 0x100: aETH
// 0x101: 0x00
// 0x102: ANKR
// 0x103: global pool
// 0x104: 0x00000
// 0x105: operator
IAETH private _AETHContract; // 102
IMarketPlace _marketPlaceContract; // 103
IERC20 private _ankrContract; // 104
address private _globalPoolContract; // 105
address _governanceContract;
address _operator;
mapping (address => uint256[]) public _userLocks;
bytes32 constant _deposit_ = "AnkrDeposit#Deposit";
bytes32 constant _freeze_ = "AnkrDeposit#Freeze";
bytes32 constant _unfreeze_ = "AnkrDeposit#Unfreeze";
bytes32 constant _lockTotal_ = "AnkrDeposit#LockTotal";
bytes32 constant _lockEndsAt_ = "AnkrDeposit#LockEndsAt";
bytes32 constant _lockAmount_ = "AnkrDeposit#LockAmount";
bytes32 constant _lockID_ = "AnkrDeposit#LockID";
bytes32 constant _allowed_ = "AnkrDeposit#Allowed";
function deposit_init(address ankrContract, address globalPoolContract, address aethContract) internal initializer {
OwnableUpgradeSafe.__Ownable_init();
_ankrContract = IERC20(ankrContract);
_globalPoolContract = globalPoolContract;
_AETHContract = IAETH(aethContract);
allowAddressForFunction(globalPoolContract, _unfreeze_);
allowAddressForFunction(globalPoolContract, _freeze_);
}
modifier onlyOperator() {
require(msg.sender == owner() || msg.sender == _operator, "Ankr Deposit#onlyOperator: not allowed");
_;
}
modifier addressAllowed(address addr, bytes32 topic) {
require(getConfig(_allowed_ ^ topic, addr) > 0, "Ankr Deposit#addressAllowed: You are not allowed to run this function");
_;
}
function deposit() public unlocked(msg.sender) returns (uint256) {
return _claimAndDeposit(msg.sender);
}
function deposit(address user) public unlocked(user) returns (uint256) {
return _claimAndDeposit(user);
}
/*
This function used to deposit ankr with transferFrom
*/
function _claimAndDeposit(address user) private returns (uint256) {
address ths = address(this);
uint256 allowance = _ankrContract.allowance(user, ths);
if (allowance == 0) {
return 0;
}
_ankrContract.transferFrom(user, ths, allowance);
setConfig(_deposit_, user, depositsOf(user).add(allowance));
cleanUserLocks(user);
emit Deposit(user, allowance);
return allowance;
}
function withdraw(uint256 amount) public unlocked(msg.sender) returns (bool) {
return _withdrawFor(msg.sender, amount);
}
function _withdrawFor(address sender, uint256 amount) internal returns (bool) {
uint256 available = availableDepositsOf(sender);
require(available >= amount, "Ankr Deposit#withdraw: You dont have available deposit balance");
setConfig(_deposit_, sender, depositsOf(sender).sub(amount));
_transferToken(sender, amount);
cleanUserLocks(sender);
emit Withdraw(sender, amount);
return true;
}
function _unfreeze(address sender, uint256 amount)
internal
returns (bool)
{
setConfig(_freeze_, sender, _frozenDeposits(sender).sub(amount, "Ankr Deposit#_unfreeze: Insufficient funds"));
cleanUserLocks(sender);
emit Unfreeze(sender, amount);
return _withdrawFor(sender, amount);
}
function _freeze(address addr, uint256 amount)
internal
returns (bool)
{
_claimAndDeposit(addr);
require(availableDepositsOf(addr) >= amount, "Ankr Deposit#_freeze: You dont have enough amount to freeze ankr");
setConfig(_freeze_, addr, _frozenDeposits(addr).add(amount));
cleanUserLocks(addr);
emit Freeze(addr, amount, 0);
return true;
}
function unfreeze(address addr, uint256 amount)
public
addressAllowed(_globalPoolContract, _unfreeze_)
returns (bool)
{
return _unfreeze(addr, amount);
}
function freeze(address addr, uint256 amount)
public
addressAllowed(_globalPoolContract, _freeze_)
returns (bool)
{
return _freeze(addr, amount);
}
function availableDepositsOf(address user) public view returns (uint256) {
return depositsOf(user).sub(frozenDepositsOf(user));
}
function depositsOf(address user) public view returns (uint256) {
return getConfig(_deposit_, user);
}
function frozenDepositsOf(address user) public view returns (uint256) {
return _frozenDeposits(user).add(lockedDepositsOf(user));
}
function _frozenDeposits(address user) internal view returns(uint256) {
return getConfig(_freeze_, user);
}
function lockedDepositsOf(address user) public view returns(uint256) {
return getConfig(_lockTotal_, user).sub(availableAmountForUnlock(user));
}
function _transferToken(address to, uint256 amount) internal {
require(_ankrContract.transfer(to, amount), "Failed token transfer");
}
function allowAddressForFunction(address addr, bytes32 topic) public onlyOperator {
setConfig(_allowed_ ^ topic, addr, 1);
}
function _addNewLockToUser(address user, uint256 amount, uint256 endsAt, uint256 lockId) internal {
uint256 deposits = depositsOf(user);
uint256 lockedDeposits = lockedDepositsOf(user);
if (amount <= lockedDeposits) {
return;
}
amount = amount.sub(lockedDeposits);
require(amount <= deposits, "Ankr Deposit#_addNewLockToUser: Insufficient funds");
require(getConfig(_lockEndsAt_, lockId) == 0, "Ankr Deposit#_addNewLockToUser: Cannot set same lock id");
if (amount == 0) return;
// set ends at property for lock
setConfig(_lockEndsAt_, lockId, endsAt);
// set amount property for lock
setConfig(_lockAmount_, lockId, amount);
setConfig(_lockTotal_, user, getConfig(_lockTotal_, user).add(amount));
// set lock id
_userLocks[user].push(lockId);
}
function cleanUserLocks(address user) public {
uint256 userLockCount = _userLocks[user].length;
uint256 currentTs = block.timestamp;
if (userLockCount == 0) return;
for (uint256 i = 0; i < userLockCount; i++) {
uint256 lockId = _userLocks[user][i];
if (getConfig(_lockEndsAt_, lockId) > currentTs && getConfig(_lockAmount_, lockId) != 0) {
continue;
}
// set total lock amount for user
setConfig(_lockTotal_, user, getConfig(_lockTotal_, user).sub(getConfig(_lockAmount_, lockId)));
// remove lock from array
_userLocks[user][i] = _userLocks[user][userLockCount.sub(1)];
_userLocks[user].pop();
//
userLockCount--;
i--;
}
}
function availableAmountForUnlock(address user) public view returns (uint256) {
uint256 userLockCount = _userLocks[user].length;
uint256 amount = 0;
if (userLockCount == 0) {
return amount;
}
for (uint256 i = 0; i < userLockCount; i++) {
uint256 lockId = _userLocks[user][i];
if (getConfig(_lockEndsAt_, lockId) <= now) {
amount += getConfig(_lockAmount_, lockId);
}
}
return amount;
}
function changeOperator(address operator) public onlyOwner {
_operator = operator;
}
}
pragma solidity ^0.6.11;
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "../lib/Pausable.sol";
import "../lib/interfaces/IConfig.sol";
import "../lib/interfaces/IStaking.sol";
import "../lib/Configurable.sol";
import "../Config.sol";
import "./AnkrDeposit_R3.sol";
contract Governance_R3 is Pausable, AnkrDeposit_R3 {
using SafeMath for uint256;
event ConfigurationChanged(bytes32 indexed key, uint256 oldValue, uint256 newValue);
event Vote(address indexed holder, bytes32 indexed ID, bytes32 vote, uint256 votes);
event Propose(address indexed proposer, bytes32 proposeID, string topic, string content, uint span);
event ProposalFinished(bytes32 indexed proposeID, bool result, uint256 yes, uint256 no);
IConfig private configContract;
IStaking private depositContract;
bytes32 internal constant _spanLo_ = "Gov#spanLo";
bytes32 internal constant _spanHi_ = "Gov#spanHi";
bytes32 internal constant _proposalMinimumThreshold_ = "Gov#minimumDepositThreshold";
bytes32 internal constant _startBlock_ = "Gov#startBlock";
bytes32 internal constant _proposeTopic_ = "Gov#proposeTopic";
bytes32 internal constant _proposeContent_ = "Gov#proposeContent";
bytes32 internal constant _proposeEndAt_ = "Gov#ProposeEndAt";
bytes32 internal constant _proposeStartAt_ = "Gov#ProposeStartAt";
bytes32 internal constant _proposeTimelock_ = "Gov#ProposeTimelock";
bytes32 internal constant _proposeCountLimit_ = "Gov#ProposeCountLimit";
bytes32 internal constant _proposerLastProposeAt_ = "Gov#ProposerLastProposeAt";
bytes32 internal constant _proposerProposeCountInMonth_ = "Gov#ProposeCountInMonth";
bytes32 internal constant _proposer_ = "Gov#proposer";
bytes32 internal constant _proposerHasActiveProposal_ = "Gov#hasActiveProposal";
bytes32 internal constant _totalProposes_ = "Gov#proposer";
bytes32 internal constant _minimumVoteAcceptance_ = "Gov#minimumVoteAcceptance";
bytes32 internal constant _proposeID_ = "Gov#proposeID";
bytes32 internal constant _proposeStatus_ = "Gov#proposeStatus";
bytes32 internal constant _votes_ = "Gov#votes";
bytes32 internal constant _voteCount_ = "Gov#voteCount";
uint256 internal constant PROPOSE_STATUS_WAITING = 0;
uint256 internal constant PROPOSE_STATUS_VOTING = 1;
uint256 internal constant PROPOSE_STATUS_FAIL = 2;
uint256 internal constant PROPOSE_STATUS_PASS = 3;
uint256 internal constant PROPOSE_STATUS_CANCELED = 4;
uint256 internal constant MONTH = 2592000;
bytes32 internal constant VOTE_YES = "VOTE_YES";
bytes32 internal constant VOTE_NO = "VOTE_NO";
bytes32 internal constant VOTE_CANCEL = "VOTE_CANCEL";
uint256 internal constant DIVISOR = 1 ether;
function initialize(address ankrContract, address globalPoolContract, address aethContract) public initializer {
__Ownable_init();
deposit_init(ankrContract, globalPoolContract, aethContract);
// minimum ankrs deposited needed for voting
changeConfiguration(_proposalMinimumThreshold_, 5000000 ether);
changeConfiguration("PROVIDER_MINIMUM_ANKR_STAKING", 100000 ether);
changeConfiguration("PROVIDER_MINIMUM_ETH_TOP_UP", 0.1 ether);
changeConfiguration("PROVIDER_MINIMUM_ETH_STAKING", 2 ether);
changeConfiguration("REQUESTER_MINIMUM_POOL_STAKING", 500 finney);
changeConfiguration("EXIT_BLOCKS", 24);
changeConfiguration(_proposeCountLimit_, 2);
// 2 days
changeConfiguration(_proposeTimelock_, 60 * 60 * 24 * 2);
changeConfiguration(_spanLo_, 24 * 60 * 60 * 3);
// 3 days
changeConfiguration(_spanHi_, 24 * 60 * 60 * 7);
// 7 days
}
function propose(uint256 _timeSpan, string memory _topic, string memory _content) public {
require(_timeSpan >= getConfig(_spanLo_), "Gov#propose: Timespan lower than limit");
require(_timeSpan <= getConfig(_spanHi_), "Gov#propose: Timespan greater than limit");
uint256 proposalMinimum = getConfig(_proposalMinimumThreshold_);
address sender = msg.sender;
uint256 senderInt = uint(sender);
require(getConfig(_proposerHasActiveProposal_, sender) == 0, "Gov#propose: You have an active proposal");
setConfig(_proposerHasActiveProposal_, sender, 1);
deposit();
require(depositsOf(sender) >= proposalMinimum, "Gov#propose: Not enough balance");
// proposer can create 2 proposal in a month
uint256 lastProposeAt = getConfig(_proposerLastProposeAt_, senderInt);
if (now.sub(lastProposeAt) < MONTH) {
// get new count in this month
uint256 proposeCountInMonth = getConfig(_proposerProposeCountInMonth_, senderInt).add(1);
require(proposeCountInMonth <= getConfig(_proposeCountLimit_), "Gov#propose: Cannot create more proposals this month");
setConfig(_proposerProposeCountInMonth_, senderInt, proposeCountInMonth);
}
else {
setConfig(_proposerProposeCountInMonth_, senderInt, 1);
}
// set last propose at for proposer
setConfig(_proposerLastProposeAt_, senderInt, now);
uint256 totalProposes = getConfig(_totalProposes_);
bytes32 _proposeID = bytes32(senderInt ^ totalProposes ^ block.number);
uint256 idInteger = uint(_proposeID);
setConfig(_totalProposes_, totalProposes.add(1));
// set started block
setConfig(_startBlock_, idInteger, block.number);
// set sender
setConfigAddress(_proposer_, idInteger, sender);
// set
setConfigString(_proposeTopic_, idInteger, _topic);
setConfigString(_proposeContent_, idInteger, _content);
// proposal will start after #timelock# days
uint256 endsAt = _timeSpan.add(getConfig(_proposeTimelock_)).add(now);
setConfig(_proposeEndAt_, idInteger, endsAt);
setConfig(_proposeStatus_, idInteger, PROPOSE_STATUS_WAITING);
setConfig(_proposeStartAt_, idInteger, now);
// add new lock to user
_addNewLockToUser(sender, proposalMinimum, endsAt, senderInt ^ idInteger);
// set proposal status (pending)
emit Propose(sender, _proposeID, _topic, _content, _timeSpan);
__vote(_proposeID, VOTE_YES, false);
}
function vote(bytes32 _ID, bytes32 _vote) public {
deposit();
uint256 ID = uint256(_ID);
uint256 status = getConfig(_proposeStatus_, ID);
uint256 startAt = getConfig(_proposeStartAt_, ID);
// if propose status is waiting and enough time passed, change status
if (status == PROPOSE_STATUS_WAITING && now.sub(startAt) >= getConfig(_proposeTimelock_)) {
setConfig(_proposeStatus_, ID, PROPOSE_STATUS_VOTING);
status = PROPOSE_STATUS_VOTING;
}
require(status == PROPOSE_STATUS_VOTING, "Gov#__vote: Propose status is not VOTING");
require(getConfigAddress(_proposer_, ID) != msg.sender, "Gov#__vote: Proposers cannot vote their own proposals") ;
__vote(_ID, _vote, true);
}
string public go;
function __vote(bytes32 _ID, bytes32 _vote, bool _lockTokens) internal {
uint256 ID = uint256(_ID);
address _holder = msg.sender;
uint256 _holderID = uint(_holder) ^ uint(ID);
uint256 endsAt = getConfig(_proposeEndAt_, ID);
if (now < endsAt) {
// previous vote type
bytes32 voted = bytes32(getConfig(_votes_, _holderID));
require(voted == 0x0 || _vote == VOTE_CANCEL, "Gov#__vote: You already voted to this proposal");
// previous vote count
uint256 voteCount = getConfig(_voteCount_, _holderID);
uint256 ID_voted = uint256(_ID ^ voted);
// if this is a cancelling operation, set vote count to 0 for user and remove votes
if ((voted == VOTE_YES || voted == VOTE_NO) && _vote == VOTE_CANCEL) {
setConfig(_votes_, ID_voted, getConfig(_votes_, ID_voted).sub(voteCount));
setConfig(_voteCount_, _holderID, 0);
setConfig(_votes_, _holderID, uint256(_vote));
emit Vote(_holder, _ID, _vote, 0);
return;
}
else if (_vote == VOTE_YES || _vote == VOTE_NO) {
uint256 ID_vote = uint256(_ID ^ _vote);
// get total stakes from deposit contract
uint256 staked = depositsOf(_holder);
// add new lock to user
if (_lockTokens) {
_addNewLockToUser(_holder, staked, endsAt, _holderID);
}
setConfig(_votes_, ID_vote, getConfig(_votes_, ID_vote).add(staked.div(DIVISOR)));
setConfig(_votes_, _holderID, uint256(_vote));
emit Vote(_holder, _ID, _vote, staked);
}
}
}
//0xc7bc95c2
function getVotes(bytes32 _ID, bytes32 _vote) public view returns (uint256) {
return getConfig(_votes_, uint256(_ID ^ _vote));
}
function finishProposal(bytes32 _ID) public {
uint256 ID = uint256(_ID);
require(getConfig(_proposeEndAt_, ID) <= now, "Gov#finishProposal: There is still time for proposal");
uint256 status = getConfig(_proposeStatus_, ID);
require(status == PROPOSE_STATUS_VOTING || status == PROPOSE_STATUS_WAITING, "Gov#finishProposal: You cannot finish proposals that already finished");
_finishProposal(_ID);
}
function _finishProposal(bytes32 _ID) internal returns (bool result) {
uint256 ID = uint256(_ID);
uint256 yes = 0;
uint256 no = 0;
(result, yes, no,,,,,) = proposal(_ID);
setConfig(_proposeStatus_, ID, result ? PROPOSE_STATUS_PASS : PROPOSE_STATUS_FAIL);
setConfig(_proposerHasActiveProposal_, getConfigAddress(_proposer_, ID), 0);
emit ProposalFinished(_ID, result, yes, no);
}
function proposal(bytes32 _ID) public view returns (
bool result,
uint256 yes,
uint256 no,
string memory topic,
string memory content,
uint256 status,
uint256 startTime,
uint256 endTime
) {
uint256 idInteger = uint(_ID);
yes = getConfig(_votes_, uint256(_ID ^ VOTE_YES));
no = getConfig(_votes_, uint256(_ID ^ VOTE_NO));
result = yes > no && yes.add(no) > getConfig(_minimumVoteAcceptance_);
topic = getConfigString(_proposeTopic_, idInteger);
content = getConfigString(_proposeContent_, idInteger);
endTime = getConfig(_proposeEndAt_, idInteger);
startTime = getConfig(_proposeStartAt_, idInteger);
status = getConfig(_proposeStatus_, idInteger);
if (status == PROPOSE_STATUS_WAITING && now.sub(getConfig(_proposeStartAt_, idInteger)) >= getConfig(_proposeTimelock_)) {
status = PROPOSE_STATUS_VOTING;
}
}
function changeConfiguration(bytes32 key, uint256 value) public onlyOperator {
uint256 oldValue = config[key];
if (oldValue != value) {
config[key] = value;
emit ConfigurationChanged(key, oldValue, value);
}
}
function cancelProposal(bytes32 _ID, string memory _reason) public onlyOwner {
uint256 ID = uint(_ID);
require(getConfig(_proposeStatus_, ID) == PROPOSE_STATUS_WAITING, "Gov#cancelProposal: Only waiting proposals can be canceled");
address sender = msg.sender;
// set status cancel
setConfig(_proposeStatus_, ID, PROPOSE_STATUS_CANCELED);
// remove from propose count for month
setConfig(_proposerProposeCountInMonth_, ID, getConfig(_proposerProposeCountInMonth_, ID).sub(1));
// remove locked amount
setConfig(_lockTotal_, sender, getConfig(_lockTotal_, sender).sub(getConfig(_lockAmount_, uint(sender) ^ ID)));
// set locked amount to zero for this proposal
setConfig(_lockAmount_, uint(sender) ^ ID, 0);
}
}
pragma solidity ^0.6.0;
import "../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.
*/
contract ContextUpgradeSafe is Initializable {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
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;
}
pragma solidity >=0.4.24 <0.7.0;
/**
* @title Initializable
*
* @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.
*/
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;
}
pragma solidity ^0.6.0;
import "../GSN/Context.sol";
import "../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.
*/
contract OwnableUpgradeSafe is Initializable, ContextUpgradeSafe {
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;
}
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// 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;
}
}
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
| proposer can create 2 proposal in a month get new count in this month | function propose(uint256 _timeSpan, string memory _topic, string memory _content) public {
require(_timeSpan >= getConfig(_spanLo_), "Gov#propose: Timespan lower than limit");
require(_timeSpan <= getConfig(_spanHi_), "Gov#propose: Timespan greater than limit");
uint256 proposalMinimum = getConfig(_proposalMinimumThreshold_);
address sender = msg.sender;
uint256 senderInt = uint(sender);
require(getConfig(_proposerHasActiveProposal_, sender) == 0, "Gov#propose: You have an active proposal");
setConfig(_proposerHasActiveProposal_, sender, 1);
deposit();
require(depositsOf(sender) >= proposalMinimum, "Gov#propose: Not enough balance");
uint256 lastProposeAt = getConfig(_proposerLastProposeAt_, senderInt);
if (now.sub(lastProposeAt) < MONTH) {
uint256 proposeCountInMonth = getConfig(_proposerProposeCountInMonth_, senderInt).add(1);
require(proposeCountInMonth <= getConfig(_proposeCountLimit_), "Gov#propose: Cannot create more proposals this month");
setConfig(_proposerProposeCountInMonth_, senderInt, proposeCountInMonth);
}
else {
setConfig(_proposerProposeCountInMonth_, senderInt, 1);
}
uint256 totalProposes = getConfig(_totalProposes_);
bytes32 _proposeID = bytes32(senderInt ^ totalProposes ^ block.number);
uint256 idInteger = uint(_proposeID);
setConfig(_totalProposes_, totalProposes.add(1));
setConfigString(_proposeContent_, idInteger, _content);
setConfig(_proposeEndAt_, idInteger, endsAt);
setConfig(_proposeStatus_, idInteger, PROPOSE_STATUS_WAITING);
setConfig(_proposeStartAt_, idInteger, now);
__vote(_proposeID, VOTE_YES, false);
}
| 10,409,686 |
/*
Copyright 2022 dYdX Trading Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.0;
import { AccessControl } from "@openzeppelin/contracts/access/AccessControl.sol";
import { Pausable } from "@openzeppelin/contracts/security/Pausable.sol";
import { ERC721 } from "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import { ERC721Enumerable } from "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import { MerkleProof } from "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
import { Math } from "@openzeppelin/contracts/utils/math/Math.sol";
import { HedgiesRoles } from "./HedgiesRoles.sol";
/**
* @title Hedgies
* @author dYdX
*
* @notice The Hedgies NFT contract.
*/
contract Hedgies is
HedgiesRoles,
ERC721Enumerable,
Pausable
{
// ============ Structs ============
struct MerkleRoot {
bytes32 merkleRoot;
bytes ipfsCid;
}
struct TierMintingInformation {
uint256 unlockTimestamp;
uint256 maxSupply;
}
// ============ Events ============
event StartingIndexBlockSet(
uint256 startingIndexBlock
);
event StartingIndexValueSet(
uint256 startingIndexValue
);
event BaseURISet(
string baseURI
);
event MerkleRootSet(
MerkleRoot merkleRoot
);
event DistributionMintRateSet(
uint256 distributionMintRate
);
event DistributionOffsetSet(
uint256 distributionOffset
);
event FinalizedUri();
// ============ Constants ============
uint256 constant public NUM_TIERS = 3;
uint256 constant public DISTRIBUTION_BASE = 10 ** 18;
bytes32 immutable public PROVENANCE_HASH;
uint256 immutable public MAX_SUPPLY;
uint256 immutable public RESERVE_SUPPLY;
uint256 immutable public TIER_ZERO_MINTS_UNLOCK_TIMESTAMP;
uint256 immutable public TIER_ONE_MINTS_UNLOCK_TIMESTAMP;
uint256 immutable public TIER_TWO_MINTS_UNLOCK_TIMESTAMP;
uint256 immutable public TIER_ZERO_MINTS_MAX_SUPPLY;
uint256 immutable public TIER_ONE_MINTS_MAX_SUPPLY;
uint256 immutable public TIER_TWO_MINTS_MAX_SUPPLY;
// ============ State Variables ============
MerkleRoot public _MERKLE_ROOT_;
uint256 public _HEDGIE_DISTRIBUTION_MINT_RATE_;
uint256 public _HEDGIE_DISTRIBUTION_OFFSET_;
string public _BASE_URI_ = "";
bool public _URI_IS_FINALIZED_ = false;
mapping (address => bool) public _HAS_CLAIMED_HEDGIE_;
uint256 public _STARTING_INDEX_BLOCK_ = 0;
// Note: Packed into a shared storage slot.
bool public _STARTING_INDEX_SET_ = false;
uint248 public _STARTING_INDEX_VALUE_ = 0;
// ============ Constructor ============
constructor(
string[2] memory nameAndSymbol,
bytes32 provenanceHash,
uint256 reserveSupply,
bytes32 merkleRoot,
bytes memory ipfsCid,
uint256[3] memory mintTierTimestamps,
uint256[3] memory mintTierMaxSupplies,
uint256 maxSupply,
address[3] memory roleOwners,
uint256[2] memory mintToVariables
)
HedgiesRoles(roleOwners[0], roleOwners[1], roleOwners[2])
ERC721(nameAndSymbol[0], nameAndSymbol[1])
{
// Verify the mint tier information is all correct.
require(
(
reserveSupply <= mintTierMaxSupplies[0] &&
mintTierMaxSupplies[0] <= mintTierMaxSupplies[1] &&
mintTierMaxSupplies[1] <= mintTierMaxSupplies[2] &&
mintTierMaxSupplies[2] <= maxSupply
),
"Each mint tier must gte the previous, includes reserveSupply and maxSupply"
);
require(
(
mintTierTimestamps[0] < mintTierTimestamps[1] &&
mintTierTimestamps[1] < mintTierTimestamps[2]
),
"Each tier must unlock later than the previous one"
);
// Set the provenanceHash.
PROVENANCE_HASH = provenanceHash;
// Set the maxSupply.
MAX_SUPPLY = maxSupply;
// The reserve supply is the number of hedgies set aside for the team and giveaways.
RESERVE_SUPPLY = reserveSupply;
// The tier mint unlock timestamps.
TIER_ZERO_MINTS_UNLOCK_TIMESTAMP = mintTierTimestamps[0];
TIER_ONE_MINTS_UNLOCK_TIMESTAMP = mintTierTimestamps[1];
TIER_TWO_MINTS_UNLOCK_TIMESTAMP = mintTierTimestamps[2];
// The tier max supplies.
TIER_ZERO_MINTS_MAX_SUPPLY = mintTierMaxSupplies[0];
TIER_ONE_MINTS_MAX_SUPPLY = mintTierMaxSupplies[1];
TIER_TWO_MINTS_MAX_SUPPLY = mintTierMaxSupplies[2];
// Set the merkle-root for eligible minters.
_setMerkleRootAndCid(
merkleRoot,
ipfsCid
);
// Set the hedgie distribution information.
_setDistributionMintRate(mintToVariables[0]);
_setDistributionOffset(mintToVariables[1]);
}
// ============ Modifiers ============
modifier uriNotFinalized {
// Verify the sale has not been finalized.
require(
!_URI_IS_FINALIZED_,
'Cannot update once the sale has been finalized'
);
_;
}
// ============ External Admin-Only Functions ============
/**
* @notice Pause this contract.
*/
function pause()
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
_pause();
}
/**
* @notice Unpause this contract.
*/
function unpause()
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
_unpause();
}
/**
* @notice Set the sale of the collection as finalized, preventing the baseURI from
* being updated again.
* @dev Emits finalized event.
*/
function finalize()
external
uriNotFinalized
onlyRole(DEFAULT_ADMIN_ROLE)
{
_URI_IS_FINALIZED_ = true;
emit FinalizedUri();
}
/**
* @notice Mint a hedgie to a specific address up to the reserve supply.
*
* Important: The reserve supply should be minted before the sale is enabled.
*
* @param maxMint The maximum number of NFTs to mint in one call to the function.
* @param recipient The address to mint the token to.
*/
function reserveHedgies(
uint256 maxMint,
address recipient
)
external
whenNotPaused
onlyRole(RESERVER_ROLE)
{
// Get supply and NFTs to mint.
uint256 supply = totalSupply();
uint256 hedgiesToMint = Math.min(maxMint, RESERVE_SUPPLY - supply);
require(
hedgiesToMint > 0,
"Cannot premint once max premint supply has been reached"
);
// Mint each NFT sequentially.
for (uint256 i = 0; i < hedgiesToMint; i++) {
// Use _mint() instead of _safeMint() since we don't plan to mint to any smart contracts.
_mint(recipient, supply + i);
}
}
/**
* @notice Mint a hedgie to a specific address.
*
* @param recipient The address to mint the token to.
* @param tokenId The id of the token to mint.
*/
function mintHedgieTo(
address recipient,
uint256 tokenId
)
external
whenNotPaused
onlyRole(MINTER_ROLE)
{
// Do not mint tokenId that should have been minted by now.
require(
tokenId >= TIER_TWO_MINTS_MAX_SUPPLY,
"Cannot mint token with tokenId lte tier two maxSupply"
);
// Do not mint tokens with invalid tokenIds.
// Prevents supply > MAX_SUPPLY as no duplicate tokenIds are allowed either.
require(
tokenId < MAX_SUPPLY,
"Cannot mint token with tokenId greater than maxSupply"
);
uint256 supply = totalSupply();
// Do not begin minting until all hedgies from tier 2 are minted.
require(
supply >= TIER_TWO_MINTS_MAX_SUPPLY,
"Cannot mint token for distribution before sale has completed"
);
// Verify that the maximum distributable supply at this timestamp has not been exceeded.
// Note: If _HEDGIE_DISTRIBUTION_OFFSET_ >= block.timestamp this call will revert.
uint256 availableHedgiesToMint = (
_HEDGIE_DISTRIBUTION_MINT_RATE_* (
block.timestamp - _HEDGIE_DISTRIBUTION_OFFSET_
) / DISTRIBUTION_BASE
);
require(
supply < availableHedgiesToMint + TIER_TWO_MINTS_MAX_SUPPLY,
'At the current timestamp supply is capped for distributing'
);
// Use _mint() instead of _safeMint() since we don't plan to mint to any smart contracts.
_mint(recipient, tokenId);
}
/**
* @notice Set the mint rate to distribute Hedgies at.
* @dev Emits DistributionMintRateSet event from an internal call.
*
* @param distributionMintRate The mint rate to distribute Hedgies at.
*/
function setDistributionMintRate(
uint256 distributionMintRate
)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
_setDistributionMintRate(distributionMintRate);
}
/**
* @notice Set the offset for the mint rate to distribute Hedgies at. This is the timestamp at
* which we consider distribution via mintHedgieTo to have started.
* @dev Emits DistributionOffsetSet event from an internal call.
*
* @param distributionOffset The offset for the mint rate to distribute Hedgies at.
*/
function setDistributionOffset(
uint256 distributionOffset
)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
_setDistributionOffset(distributionOffset);
}
/**
* @notice Set the base URI which determines the metadata URI for all tokens.
* Note: this call will revert if the contract is finalized.
* @dev Emits BaseURISet event.
*
* @param baseURI The URI that determines the metadata URI for all tokens.
*/
function setBaseURI(
string calldata baseURI
)
external
uriNotFinalized
onlyRole(DEFAULT_ADMIN_ROLE)
{
// Set the base URI.
_BASE_URI_ = baseURI;
emit BaseURISet(baseURI);
}
/**
* @notice Update the Merkle root and CID for the minting tiers. This should not be necessary
* since these values should be set when the contract is constructed. This function is
* provided just in case.
* @dev Emits MerkleRootSet event from an internal call.
*
* @param merkleRoot The root of the Merkle tree that proves who is eligible for distribution.
* @param ipfsCid The content identifier in IPFS for the Merkle tree.
*/
function setMerkleRootAndCid(
bytes32 merkleRoot,
bytes calldata ipfsCid
)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
_setMerkleRootAndCid(merkleRoot, ipfsCid);
}
// ============ Other External Functions ============
/**
* @notice Mint a Hedgie if the tier 1 supply has not been reached. If we haven't set the starting index
* and this is the last token to be sold from tier 1, set the starting index block.
* @dev Emits StartingIndexBlockSet event from an internal call.
*
* @param tier The tier of the account minting a Hedgie.
* @param merkleProof The proof verifying the account is in the tier they are claiming to be in.
*/
function mintHedgie(
uint256 tier,
bytes32[] calldata merkleProof
)
external
whenNotPaused
{
// Get the tier minting information and verify that it is past the time when tier minting started.
TierMintingInformation memory tierMintingInformation = getMintsAndMintTimeForTier(tier);
require(
block.timestamp >= tierMintingInformation.unlockTimestamp,
"Tier minting is not yet allowed"
);
uint256 mintIndex = totalSupply();
// Verify the reserve supply has been minted.
require(
mintIndex >= RESERVE_SUPPLY,
"Not all Hedgies from the reserve supply have been minted"
);
// Verify the mint index is not past the max supply for the tier.
// Note: First ID to be minted is 0, and last to be minted is TIER_TWO_MINTS_MAX_SUPPLY - 1.
require(
mintIndex < tierMintingInformation.maxSupply,
"No Hedgies left to mint at this tier"
);
// The final tier is open to all.
if (tier < NUM_TIERS - 1) {
// Verify the address has not already minted.
require(
!_HAS_CLAIMED_HEDGIE_[msg.sender],
'Sender already claimed'
);
// Check if address is in the tier. The final tier is open to all.
require(
isAddressEligible(msg.sender, tier, merkleProof),
'Invalid Merkle proof'
);
// Mark the sender as having claimed.
_HAS_CLAIMED_HEDGIE_[msg.sender] = true;
}
// Use _mint() instead of _safeMint() since any contract calling this must be directly doing so.
_mint(msg.sender, mintIndex);
// Set the starting index block automatically when minting the last token.
if (mintIndex == TIER_TWO_MINTS_MAX_SUPPLY - 1) {
_setStartingIndexBlock(block.number);
}
}
/**
* @notice Set the starting index using the previously determined block number.
* @dev Emits StartingIndexBlockSet event from an internal call and StartingIndexValueSet event.
*/
function setStartingIndex()
external
{
// Verify the starting index has not been set.
require(
!_STARTING_INDEX_SET_,
"Starting index is already set"
);
// Verify the starting block has already been set.
uint256 startingIndexBlock = _STARTING_INDEX_BLOCK_;
require(
startingIndexBlock != 0,
"Starting index block must be set"
);
// Ensure the starting index block is within 256 blocks exclusive of the previous block
// and is not the current block as it has no blockHash yet.
// https://docs.soliditylang.org/en/v0.8.11/units-and-global-variables.html#block-and-transaction-properties
uint256 prevBlock = block.number - 1;
uint256 blockDifference = prevBlock - startingIndexBlock;
// If needed, set the starting index block to be within 256 of the current block.
if (blockDifference >= 256) {
startingIndexBlock = prevBlock - (blockDifference % 256);
_setStartingIndexBlock(startingIndexBlock);
}
// Set the starting index.
uint248 startingIndexValue = uint248(
uint256(blockhash(startingIndexBlock)) % MAX_SUPPLY
);
// Note: Packed into a shared storage slot.
_STARTING_INDEX_VALUE_ = startingIndexValue;
_STARTING_INDEX_SET_ = true;
emit StartingIndexValueSet(startingIndexValue);
}
// ============ Public Functions ============
/**
* @notice Get params for a minting tier: the unlock timestamp and number of mints available.
*
* @param tier The tier being checked for its unlock timestamp and number of total mints.
*/
function getMintsAndMintTimeForTier(
uint256 tier
)
public
view
returns (TierMintingInformation memory)
{
// Verify the tier is a valid mint tier.
require(
tier < NUM_TIERS,
"Invalid tier provided"
);
// Return the information for the tier being requested.
if (tier == 0) {
return TierMintingInformation({
unlockTimestamp: TIER_ZERO_MINTS_UNLOCK_TIMESTAMP,
maxSupply: TIER_ZERO_MINTS_MAX_SUPPLY
});
}
if (tier == 1) {
return TierMintingInformation({
unlockTimestamp: TIER_ONE_MINTS_UNLOCK_TIMESTAMP,
maxSupply: TIER_ONE_MINTS_MAX_SUPPLY
});
}
return TierMintingInformation({
unlockTimestamp: TIER_TWO_MINTS_UNLOCK_TIMESTAMP,
maxSupply: TIER_TWO_MINTS_MAX_SUPPLY
});
}
/**
* @notice Check if an address is eligible for a given tier.
*
* @param ethereumAddress The address trying to mint a hedige.
* @param tier The tier to check.
* @param merkleProof The Merkle proof proving that (ethereumAddress, tier) is in the tree.
*/
function isAddressEligible(
address ethereumAddress,
uint256 tier,
bytes32[] calldata merkleProof
)
public
view
returns (bool)
{
// Get the node of the ethereumAddress and tier and verify it is in the Merkle tree.
bytes32 node = keccak256(abi.encodePacked(ethereumAddress, tier));
return MerkleProof.verify(merkleProof, _MERKLE_ROOT_.merkleRoot, node);
}
/**
* @notice See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
override(AccessControl, ERC721Enumerable)
returns (bool)
{
return (
AccessControl.supportsInterface(interfaceId) ||
ERC721Enumerable.supportsInterface(interfaceId)
);
}
// ============ Internal Functions ============
/**
* @notice Get the base URI.
*/
function _baseURI()
internal
view
override
returns (string memory)
{
// Get the base URI.
return _BASE_URI_;
}
/**
* @notice Set the starting index.
* @dev Emits StartingIndexBlockSet event.
*
* @param startingIndexBlock The block number to set the starting index to.
*/
function _setStartingIndexBlock(
uint256 startingIndexBlock
)
internal
{
_STARTING_INDEX_BLOCK_ = startingIndexBlock;
emit StartingIndexBlockSet(startingIndexBlock);
}
/**
* @notice Set the merkle root and CID.
* @dev Emits MerkleRootSet event.
*
* @param merkleRoot The root of the Merkle tree that proves who is eligible for distribution.
* @param ipfsCid The content identifier in IPFS for the Merkle tree data.
*/
function _setMerkleRootAndCid(
bytes32 merkleRoot,
bytes memory ipfsCid
)
internal
{
// Get the full Merkle root and set _MERKLE_ROOT_ in storage.
MerkleRoot memory fullMerkleRoot = MerkleRoot({
merkleRoot: merkleRoot,
ipfsCid: ipfsCid
});
_MERKLE_ROOT_ = fullMerkleRoot;
emit MerkleRootSet(fullMerkleRoot);
}
/**
* @notice Set the mint rate to distribute Hedgies at.
* @dev Emits DistributionMintRateSet event.
*
* @param distributionMintRate The mint rate to distribute Hedgies at.
*/
function _setDistributionMintRate(
uint256 distributionMintRate
)
internal
{
// Set the distribution mint rate.
_HEDGIE_DISTRIBUTION_MINT_RATE_ = distributionMintRate;
emit DistributionMintRateSet(distributionMintRate);
}
/**
* @notice Set the offset for the mint rate to distribute Hedgies at. This is the timestamp at
* which we consider distribution via mintHedgieTo to have started.
* @dev Emits DistributionOffsetSet event.
*
* @param distributionOffset The offset for the mint rate to distribute Hedgies at.
*/
function _setDistributionOffset(
uint256 distributionOffset
)
internal
{
// Set the offset for the distribution mint rate.
_HEDGIE_DISTRIBUTION_OFFSET_ = distributionOffset;
emit DistributionOffsetSet(distributionOffset);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/AccessControl.sol)
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 revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*
* NOTE: This function is deprecated in favor of {_grantRole}.
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Grants `role` to `account`.
*
* Internal function without access restriction.
*/
function _grantRole(bytes32 role, address account) internal virtual {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
/**
* @dev Revokes `role` from `account`.
*
* Internal function without access restriction.
*/
function _revokeRole(bytes32 role, address account) internal virtual {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/Pausable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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 (utils/cryptography/MerkleProof.sol)
pragma solidity ^0.8.0;
/**
* @dev These functions deal with verification of Merkle Trees proofs.
*
* The proofs can be generated using the JavaScript library
* https://github.com/miguelmota/merkletreejs[merkletreejs].
* Note: the hashing algorithm should be keccak256 and pair sorting should be enabled.
*
* See `test/utils/cryptography/MerkleProof.test.js` for some examples.
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(
bytes32[] memory proof,
bytes32 root,
bytes32 leaf
) internal pure returns (bool) {
return processProof(proof, leaf) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merklee tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leafs & pre-images are assumed to be sorted.
*
* _Available since v4.4._
*/
function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
// Hash(current element of the proof + current computed hash)
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
return computedHash;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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);
}
}
/*
Copyright 2022 dYdX Trading Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.0;
import { AccessControl } from "@openzeppelin/contracts/access/AccessControl.sol";
/**
* @title HedgiesRoles
* @author dYdX
*
* @notice Defines roles used in the Hedgies contract. The hierarchy of roles and powers
* of each role are described below.
*
* Roles:
*
* DEFAULT_ADMIN_ROLE
* | -> May add or remove users from any of the below roles it manages.
* |
* +-- RESERVER_ROLE
* | -> May reserve to any address as long as reserve supply has not been met.
* |
* +-- MINTER_ROLE
* -> May mint to any address as long as mint supply has not been met.
*/
contract HedgiesRoles is
AccessControl
{
bytes32 public constant RESERVER_ROLE = keccak256('RESERVER_ROLE');
bytes32 public constant MINTER_ROLE = keccak256('MINTER_ROLE');
constructor(
address admin,
address reserver,
address minter
) {
// Assign roles.
_grantRole(DEFAULT_ADMIN_ROLE, admin);
_grantRole(RESERVER_ROLE, reserver);
_grantRole(MINTER_ROLE, minter);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface 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
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
| Set the mint rate to distribute Hedgies at. Emits DistributionMintRateSet event from an internal call. distributionMintRate The mint rate to distribute Hedgies at./ | function setDistributionMintRate(
uint256 distributionMintRate
)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
_setDistributionMintRate(distributionMintRate);
}
| 1,063,356 |
/**
*Submitted for verification at Etherscan.io on 2021-03-22
*/
// 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);
}
pragma solidity >=0.6.0;
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library SafeERC20 {
function _safeApprove(IERC20 token, address to, uint value) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), '!TransferHelper: APPROVE_FAILED');
}
function safeApprove(IERC20 token, address to, uint value) internal {
if (value > 0) _safeApprove(token, to, 0);
return _safeApprove(token, to, value);
}
function safeTransfer(IERC20 token, address to, uint value) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), '!TransferHelper: TRANSFER_FAILED');
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), '!TransferHelper: TRANSFER_FROM_FAILED');
}
function safeTransferETH(address to, uint value) internal {
(bool success,) = to.call{value:value}(new bytes(0));
require(success, '!TransferHelper: ETH_TRANSFER_FAILED');
}
}
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IMintERC20 {
/**
* @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);
function mint(address recipient, uint256 amount) external;
function burn(uint256 amount) external;
function burnFrom(address sender, uint256 amount) external;
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
pragma solidity >=0.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, 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;
}
}
/**
*Submitted for verification at Etherscan.io on 2021-01-14
*/
pragma solidity >=0.6.0 <0.8.0;
/**
* @title Initializable
*
* @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.
*/
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;
}
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.
*/
contract Context is Initializable {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
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;
}
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.
*/
contract Ownable is Initializable, Context {
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;
}
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;
}
pragma solidity >=0.6.2;
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
pragma solidity >=0.6.2;
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
pragma solidity >=0.5.0;
interface IWETH {
function deposit() external payable;
function transfer(address to, uint value) external returns (bool);
function withdraw(uint) external;
}
pragma solidity ^0.7.0;
interface IWETHelper {
function withdraw(uint) external;
}
contract WETHelper {
receive() external payable {
}
function safeTransferETH(address to, uint value) internal {
(bool success,) = to.call{value:value}(new bytes(0));
require(success, '!WETHelper: ETH_TRANSFER_FAILED');
}
function withdraw(address _eth, address _to, uint256 _amount) public {
IWETHelper(_eth).withdraw(_amount);
safeTransferETH(_to, _amount);
}
}
pragma solidity ^0.7.0;
interface IUniswapV2Router02Api {
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
}
library UniTools {
function swapExactTokensForTokens(
address _uniRouter,
address _fromToken,
address _toToken,
uint256 _amount) internal returns (uint256) {
if (_fromToken == _toToken || _amount == 0) return _amount;
address[] memory path = new address[](2);
path[0] = _fromToken;
path[1] = _toToken;
uint[] memory amount = IUniswapV2Router02Api(_uniRouter).swapExactTokensForTokens(
_amount, 0, path, address(this), 0xffffffff);
return amount[amount.length - 1];
}
function swapExactTokensForTokens(
address _fromToken,
address _toToken,
uint256 _amount) internal returns (uint256) {
return swapExactTokensForTokens(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, _fromToken, _toToken, _amount);
}
function swapExactTokensForTokens3(
address _uniRouter,
address _fromToken,
address _midToken,
address _toToken,
uint256 _amount) internal returns (uint256) {
address[] memory path;
if (_midToken == address(0)) {
path = new address[](2);
path[0] = _fromToken;
path[1] = _toToken;
} else {
path = new address[](3);
path[0] = _fromToken;
path[1] = _midToken;
path[2] = _toToken;
}
uint[] memory amount = IUniswapV2Router02Api(_uniRouter).swapExactTokensForTokens(
_amount, 0, path, address(this), 0xffffffff);
return amount[amount.length - 1];
}
function swapExactTokensForTokens3(
address _fromToken,
address _midToken,
address _toToken,
uint256 _amount) internal returns (uint256) {
return swapExactTokensForTokens3(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, _fromToken, _midToken, _toToken, _amount);
}
}
pragma solidity 0.7.6;
interface IMigratorChef {
// Perform LP token migration from legacy UniswapV2 to SushiSwap.
// Take the current LP token address and return the new LP token address.
// Migrator should have full access to the caller's LP token.
// Return the new LP token address.
//
// XXX Migrator must have allowance access to UniswapV2 LP tokens.
// SushiSwap must mint EXACTLY the same amount of SushiSwap LP tokens or
// else something bad will happen. Traditional UniswapV2 does not
// do that so be careful!
function migrate(IERC20 token) external returns (IERC20);
}
// MasterChef is the master of Sushi. He can make Sushi and he is a fair guy.
//
// Note that it's ownable and the owner wields tremendous power. The ownership
// will be transferred to a governance smart contract once SUSHI is sufficiently
// distributed and the community can show to govern itself.
//
// Have fun reading it. Hopefully it's bug-free. God bless.
contract MasterChef is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
using SafeERC20 for IMintERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 lpAmount; // Single token, swap to LP token.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of SUSHIs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accSushiPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accSushiPerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. SUSHIs to distribute per block.
uint256 buybackRatio; // Buyback ratio, 0 means no ratio. 5 means 0.5%
uint256 poolType; // Pool type
uint256 amount; // User deposit amount
uint256 lpAmount; // ETH/Token convert to uniswap liq amount
address routerv2; // RouterV2
address moneyToken; // Money Token, USDT, BUSD, ETH, BNB, BTC
uint256 lastRewardBlock; // Last block number that SUSHIs distribution occurs.
uint256 accSushiPerShare; // Accumulated SUSHIs per share, times 1e12. See below.
}
// Pool type.
uint256 internal constant POOL_THISLPTOKEN = 0;
uint256 internal constant POOL_TOKEN = 1;
uint256 internal constant POOL_LPTOKEN = 2;
uint256 internal constant POOL_SLPTOKEN = 3;
uint256 internal constant POOL_SLPLPTOKEN = 4;
uint256 internal constant POOL_UNSUPPORT = 5;
// ETH Mainnet
address public constant UNIV2ROUTER2 = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
address public constant SLPV2ROUTER2 = 0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F;
address public constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
// The SUSHI TOKEN!
IMintERC20 public sushi;
// Dev address.
address public devaddr;
// Block number when bonus SUSHI period ends.
uint256 public bonusEndBlock;
// SUSHI tokens created per block.
uint256 public sushiPerBlock;
// Bonus muliplier for early sushi makers.
uint256 public constant BONUS_MULTIPLIER = 10;
// The migrator contract. It has a lot of power. Can only be set through governance (owner).
IMigratorChef public migrator;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes LP tokens.
mapping (uint256 => mapping (address => UserInfo)) public userInfo;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The block number when SUSHI mining starts.
uint256 public startBlock;
// Treasury address;
address public treasury;
uint256 public mintReward;
address public pairaddr;
// ETH Helper for the transfer, stateless.
WETHelper public wethelper;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount, uint256 buybackAmount, uint256 liquidity);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount, uint256 buybackAmount, uint256 liquidity);
event Mint(address indexed to, uint256 amount, uint256 devamount);
function initialize(
IMintERC20 _sushi,
address _devaddr,
address _treasury,
uint256 _sushiPerBlock,
uint256 _startBlock,
uint256 _bonusEndBlock
) public initializer {
Ownable.__Ownable_init();
sushi = _sushi;
devaddr = _devaddr;
treasury = _treasury;
sushiPerBlock = _sushiPerBlock;
startBlock = _startBlock;
bonusEndBlock = _bonusEndBlock;
wethelper = new WETHelper();
}
receive() external payable {
assert(msg.sender == WETH);
}
function setPair(address _pairaddr) public onlyOwner {
pairaddr = _pairaddr;
IERC20(pairaddr).safeApprove(UNIV2ROUTER2, uint(-1));
IERC20(WETH).safeApprove(UNIV2ROUTER2, uint(-1));
IERC20(address(sushi)).safeApprove(UNIV2ROUTER2, uint(-1));
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
function add(uint256 _allocPoint, IERC20 _lpToken, address _moneyToken, bool _withUpdate, uint256 _buybackRatio, uint256 _type) public {
require(msg.sender == owner() || msg.sender == devaddr, "!dev addr");
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
address routerv2 = UNIV2ROUTER2;
if (_type == POOL_SLPTOKEN || _type == POOL_SLPLPTOKEN) {
routerv2 = SLPV2ROUTER2;
}
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
buybackRatio: _buybackRatio,
poolType: _type,
amount: 0,
lpAmount: 0,
routerv2: routerv2,
moneyToken: _moneyToken,
lastRewardBlock: lastRewardBlock,
accSushiPerShare: 0
}));
_lpToken.safeApprove(UNIV2ROUTER2, uint(-1));
_lpToken.safeApprove(SLPV2ROUTER2, uint(-1));
}
// Update the given pool's SUSHI allocation point. Can only be called by the owner.
function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate, uint256 _buybackRatio) public {
require(msg.sender == owner() || msg.sender == devaddr, "!dev addr");
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
poolInfo[_pid].buybackRatio = _buybackRatio;
}
// Set the migrator contract. Can only be called by the owner.
function setMigrator(IMigratorChef _migrator) public onlyOwner {
migrator = _migrator;
}
// Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good.
function migrate(uint256 _pid) public {
require(address(migrator) != address(0), "migrate: no migrator");
PoolInfo storage pool = poolInfo[_pid];
IERC20 lpToken = pool.lpToken;
uint256 bal = lpToken.balanceOf(address(this));
lpToken.safeApprove(address(migrator), bal);
IERC20 newLpToken = migrator.migrate(lpToken);
require(bal == newLpToken.balanceOf(address(this)), "migrate: bad");
pool.lpToken = newLpToken;
}
// Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
if (_to <= bonusEndBlock) {
return _to.sub(_from).mul(BONUS_MULTIPLIER);
} else if (_from >= bonusEndBlock) {
return _to.sub(_from);
} else {
return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add(
_to.sub(bonusEndBlock)
);
}
}
// View function to see pending SUSHIs on frontend.
function pendingSushi(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accSushiPerShare = pool.accSushiPerShare;
uint256 lpSupply = pool.amount;
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 sushiReward = multiplier.mul(sushiPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accSushiPerShare = accSushiPerShare.add(sushiReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accSushiPerShare).div(1e12).sub(user.rewardDebt);
}
// Update reward variables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.amount;
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 sushiReward = multiplier.mul(sushiPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
mint(devaddr, sushiReward, sushiReward.div(100));
mintReward.add(sushiReward);
pool.accSushiPerShare = pool.accSushiPerShare.add(sushiReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to MasterChef for SUSHI allocation.
function deposit(uint256 _pid, uint256 _amount) public payable {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
uint256 buybackAmount;
uint256 liquidity;
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accSushiPerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
safeSushiTransfer(msg.sender, pending);
}
}
if (msg.value > 0) {
IWETH(WETH).deposit{value: msg.value}();
}
if (address(pool.lpToken) == WETH) {
if(_amount > 0) {
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
}
if (msg.value > 0) {
_amount = _amount.add(msg.value);
}
} else if(_amount > 0) {
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
}
if(_amount > 0) {
buybackAmount = _amount.mul(pool.buybackRatio).div(1000);
if (pool.buybackRatio > 0 && buybackAmount == 0) {
buybackAmount = _amount;
}
pool.lpToken.safeTransfer(treasury, buybackAmount);
_amount = _amount.sub(buybackAmount);
if (pool.poolType == POOL_TOKEN || pool.poolType == POOL_SLPTOKEN) {
liquidity = tokenToLp(pool.routerv2, pool.lpToken, pool.moneyToken, _amount);
user.lpAmount = user.lpAmount.add(liquidity);
pool.lpAmount = pool.lpAmount.add(liquidity);
}
pool.amount = pool.amount.add(_amount);
user.amount = user.amount.add(_amount);
}
user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount, buybackAmount, liquidity);
}
// Withdraw LP tokens from MasterChef.
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accSushiPerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
safeSushiTransfer(msg.sender, pending);
}
uint256 buybackAmount;
uint256 liquidity;
if(_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.amount = pool.amount.sub(_amount);
if (pool.poolType == POOL_TOKEN || pool.poolType == POOL_SLPTOKEN) {
liquidity = user.lpAmount.mul(_amount).div(user.amount.add(_amount));
uint256 amount2 = lpToToken(pool.routerv2, pool.lpToken, pool.moneyToken, liquidity);
if (amount2 < _amount) _amount = amount2;
user.lpAmount = user.lpAmount.sub(liquidity);
pool.lpAmount = pool.lpAmount.sub(liquidity);
}
buybackAmount = _amount.mul(pool.buybackRatio).div(1000);
if (pool.buybackRatio > 0 && buybackAmount == 0) {
buybackAmount = _amount;
}
pool.lpToken.safeTransfer(treasury, buybackAmount);
_amount = _amount.sub(buybackAmount);
if (address(pool.lpToken) == WETH) {
withdrawEth(address(msg.sender), _amount, false);
} else {
pool.lpToken.safeTransfer(address(msg.sender), _amount);
}
}
user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12);
emit Withdraw(msg.sender, _pid, _amount, buybackAmount, liquidity);
}
// Safe sushi transfer function, just in case if rounding error causes pool to not have enough SUSHIs.
function safeSushiTransfer(address _to, uint256 _amount) internal {
uint256 sushiBal = sushi.balanceOf(address(this));
if (_amount > sushiBal) {
sushi.transfer(_to, sushiBal);
} else {
sushi.transfer(_to, _amount);
}
}
// Update dev address by the previous dev.
function dev(address _devaddr) public {
require(msg.sender == devaddr, "dev: wut?");
devaddr = _devaddr;
}
// Update Treasury contract address;
function setTreasury(address _treasury) public {
require(msg.sender == owner() || msg.sender == devaddr, "!dev addr");
treasury = _treasury;
}
function tokenToLp(address _uniRouter, IERC20 _token, address _moneyToken, uint256 _amount) internal returns (uint256 liq) {
if (_amount == 0) return 0;
if (address(_token) != WETH) {
_amount = UniTools.swapExactTokensForTokens3(_uniRouter, address(_token), _moneyToken, WETH, _amount);
}
uint256 amountBuy = _amount.mul(5025).div(10000);
uint256 amountEth = _amount.sub(amountBuy);
uint256 amountToken = UniTools.swapExactTokensForTokens(WETH, address(sushi), amountEth);
(,, liq) = IUniswapV2Router02(UNIV2ROUTER2).addLiquidity(
WETH, address(sushi), amountEth, amountToken, 0, 0, address(this), 0xffffffff);
}
function lpToToken(address _uniRouter, IERC20 _token, address _moneyToken, uint256 _liquidity) internal returns (uint256 amountAsset){
if (_liquidity == 0) return 0;
(uint256 amountToken, uint256 amountEth) = IUniswapV2Router02(UNIV2ROUTER2).removeLiquidity(
address(sushi), WETH, _liquidity, 0, 0, address(this), 0xffffffff);
amountEth = amountEth.add(UniTools.swapExactTokensForTokens(address(sushi), WETH, amountToken));
if (address(_token) == WETH) {
amountAsset = amountEth;
} else {
amountAsset = UniTools.swapExactTokensForTokens3(_uniRouter, WETH, _moneyToken, address(_token), amountEth);
}
}
function withdrawEth(address _to, uint256 _amount, bool _isWeth) internal {
if (_isWeth) {
IERC20(WETH).safeTransfer(_to, _amount);
} else {
IERC20(WETH).safeTransfer(address(wethelper), _amount);
wethelper.withdraw(WETH, _to, _amount);
}
}
function mint(address devto, uint256 rewardAmount, uint256 devRewardAmount) internal {
if (rewardAmount == 0) {
emit Mint(devto, 0, 0);
return;
}
require(sushi.transfer(devto, devRewardAmount), '!sushi transfer of pool failed');
emit Mint(devto, rewardAmount, devRewardAmount);
}
} | Deposit LP tokens to MasterChef for SUSHI allocation. | function deposit(uint256 _pid, uint256 _amount) public payable {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
uint256 buybackAmount;
uint256 liquidity;
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accSushiPerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
safeSushiTransfer(msg.sender, pending);
}
}
if (msg.value > 0) {
}
if (address(pool.lpToken) == WETH) {
if(_amount > 0) {
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
}
if (msg.value > 0) {
_amount = _amount.add(msg.value);
}
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
}
if(_amount > 0) {
buybackAmount = _amount.mul(pool.buybackRatio).div(1000);
if (pool.buybackRatio > 0 && buybackAmount == 0) {
buybackAmount = _amount;
}
pool.lpToken.safeTransfer(treasury, buybackAmount);
_amount = _amount.sub(buybackAmount);
if (pool.poolType == POOL_TOKEN || pool.poolType == POOL_SLPTOKEN) {
liquidity = tokenToLp(pool.routerv2, pool.lpToken, pool.moneyToken, _amount);
user.lpAmount = user.lpAmount.add(liquidity);
pool.lpAmount = pool.lpAmount.add(liquidity);
}
pool.amount = pool.amount.add(_amount);
user.amount = user.amount.add(_amount);
}
user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount, buybackAmount, liquidity);
}
| 6,515,663 |
//SPDX-License-Identifier: MIT
//Copyright 2021 Louis Sobel
pragma solidity ^0.8.0;
/*
88888888ba, 88888888ba 888b 88 88888888888 888888888888
88 `"8b 88 "8b 8888b 88 88 88
88 `8b 88 ,8P 88 `8b 88 88 88
88 88 88aaaaaa8P' 88 `8b 88 88aaaaa 88
88 88 88""""""8b, 88 `8b 88 88""""" 88
88 8P 88 `8b 88 `8b 88 88 88
88 .a8P 88 a8P 88 `8888 88 88
88888888Y"' 88888888P" 88 `888 88 88
https://dbnft.io
Generate NFTs by compiling the DBN language to EVM opcodes, then
deploying a contract that can render your art as a bitmap.
> Line 0 0 100 100
╱
╱
╱
╱
╱
╱
╱
╱
╱
╱
*/
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "./DBNERC721Enumerable.sol";
import "./OpenSeaTradable.sol";
import "./OwnerSignedTicketRestrictable.sol";
import "./Drawing.sol";
import "./Token.sol";
import "./Serialize.sol";
/**
* @notice Compile DBN drawings to Ethereum Virtual Machine opcodes and deploy the code as NFT art.
* @dev This contract implements the ERC721 (including Metadata and Enumerable extensions)
* @author Louis Sobel
*/
contract DBNCoordinator is Ownable, DBNERC721Enumerable, OpenSeaTradable, OwnerSignedTicketRestrictable {
using Counters for Counters.Counter;
using Strings for uint256;
/**
* @dev There's two ~types of tokenId out of the 10201 (101x101) total tokens
* - 101 "allowlisted ones" [0, 100]
* - And "Open" ones [101, 10200]
* Minting of the allowlisted ones is through mintTokenId function
* Minting of the Open ones is through plain mint
*/
uint256 private constant LAST_ALLOWLISTED_TOKEN_ID = 100;
uint256 private constant LAST_TOKEN_ID = 10200;
/**
* @dev Event emitted when a a token is minted, linking the token ID
* to the address of the deployed drawing contract
*/
event DrawingDeployed(uint256 tokenId, address addr);
// Configuration
enum ContractMode { AllowlistOnly, Open }
ContractMode private _contractMode;
uint256 private _mintPrice;
string private _baseExternalURI;
address payable public recipient;
bool public recipientLocked;
// Minting
Counters.Counter private _tokenIds;
mapping (uint256 => address) private _drawingAddressForTokenId;
/**
* @dev Initializes the contract
* @param owner address to immediately transfer the contract to
* @param baseExternalURI URL (like https//dbnft.io/dbnft/) to which
* tokenIDs will be appended to get the `external_URL` metadata field
* @param openSeaProxyRegistry address of the opensea proxy registry, will
* be saved and queried in isAllowedForAll to facilitate opensea listing
*/
constructor(
address owner,
string memory baseExternalURI,
address payable _recipient,
address openSeaProxyRegistry
) ERC721("Design By Numbers NFT", "DBNFT") {
transferOwnership(owner);
_baseExternalURI = baseExternalURI;
_contractMode = ContractMode.AllowlistOnly;
// first _open_ token id
_tokenIds._value = LAST_ALLOWLISTED_TOKEN_ID + 1;
// initial mint price
_mintPrice = 0;
// initial recipient
recipient = _recipient;
// set up the opensea proxy registry
_setOpenSeaRegistry(openSeaProxyRegistry);
}
/******************************************************************************************
* _____ ____ _ _ ______ _____ _____
* / ____/ __ \| \ | | ____|_ _/ ____|
* | | | | | | \| | |__ | || | __
* | | | | | | . ` | __| | || | |_ |
* | |___| |__| | |\ | | _| || |__| |
* \_____\____/|_| \_|_| |_____\_____|
*
* Functions for configuring / interacting with the contract itself
*/
/**
* @notice The current "mode" of the contract: either AllowlistOnly (0) or Open (1).
* In AllowlistOnly mode, a signed ticket is required to mint. In Open mode,
* minting is open to all.
*/
function getContractMode() public view returns (ContractMode) {
return _contractMode;
}
/**
* @notice Moves the contract mode to Open. Only the owner can call this. Once the
* contract moves to Open, it cannot be moved back to AllowlistOnly
*/
function openMinting() public onlyOwner {
_contractMode = ContractMode.Open;
}
/**
* @notice Returns the current cost to mint. Applies to either mode.
* (And of course, this does not include gas ⛽️)
*/
function getMintPrice() public view returns (uint256) {
return _mintPrice;
}
/**
* @notice Sets the cost to mint. Only the owner can call this.
*/
function setMintPrice(uint256 price) public onlyOwner {
_mintPrice = price;
}
/**
* @notice Sets the recipient. Cannot be called after the recipient is locked.
* Only the owner can call this.
*/
function setRecipient(address payable to) public onlyOwner {
require(!recipientLocked, "RECIPIENT_LOCKED");
recipient = to;
}
/**
* @notice Prevents any future changes to the recipient.
* Only the owner can call this.
* @dev This enables post-deploy configurability of the recipient,
* combined with the ability to lock it in to facilitate
* confidence as to where the funds will be able to go.
*/
function lockRecipient() public onlyOwner {
recipientLocked = true;
}
/**
* @notice Disburses the contract balance to the stored recipient.
* Only the owner can call this.
*/
function disburse() public onlyOwner {
recipient.transfer(address(this).balance);
}
/******************************************************************************************
* __ __ _____ _ _ _______ _____ _ _ _____
* | \/ |_ _| \ | |__ __|_ _| \ | |/ ____|
* | \ / | | | | \| | | | | | | \| | | __
* | |\/| | | | | . ` | | | | | | . ` | | |_ |
* | | | |_| |_| |\ | | | _| |_| |\ | |__| |
* |_| |_|_____|_| \_| |_| |_____|_| \_|\_____|
*
* Functions for minting tokens!
*/
/**
* @notice Mints a token by deploying the given drawing bytecode
* @param bytecode The bytecode of the drawing to mint a token for.
* This bytecode should have been created by the DBN Compiler, otherwise
* the behavior of this function / the subsequent token is undefined.
*
* Requires passed value of at least the current mint price.
* Will revert if there are no more tokens available or if the current contract
* mode is not yet Open.
*/
function mint(bytes memory bytecode) public payable {
require(_contractMode == ContractMode.Open, "NOT_OPEN");
uint256 tokenId = _tokenIds.current();
require(tokenId <= LAST_TOKEN_ID, 'SOLD_OUT');
_tokenIds.increment();
_mintAtTokenId(bytecode, tokenId);
}
/**
* @notice Mints a token at the specific token ID by deploying the given drawing bytecode.
* Requires passing a ticket id and a signature generated by the contract owner
* granting permission for the caller to mint the specific token ID.
* @param bytecode The bytecode of the drawing to mint a token for
* This bytecode should have been created by the DBN Compiler, otherwise
* the behavior of this function / the subsequent token is undefined.
* @param tokenId The token ID to mint. Needs to be in the range [0, LAST_ALLOWLISTED_TOKEN_ID]
* @param ticketId The ID of the ticket; included as part of the signed data
* @param signature The bytes of the signature that must have been generated
* by the current owner of the contract.
*
* Requires passed value of at least the current mint price.
*/
function mintTokenId(
bytes memory bytecode,
uint256 tokenId,
uint256 ticketId,
bytes memory signature
) public payable onlyWithTicketFor(tokenId, ticketId, signature) {
require(tokenId <= LAST_ALLOWLISTED_TOKEN_ID, 'WRONG_TOKENID_RANGE');
_mintAtTokenId(bytecode, tokenId);
}
/**
* @dev Internal function that does the actual minting for both open and allowlisted mint
* @param bytecode The bytecode of the drawing to mint a token for
* @param tokenId The token ID to mint
*/
function _mintAtTokenId(
bytes memory bytecode,
uint256 tokenId
) internal {
require(msg.value >= _mintPrice, "WRONG_PRICE");
// Deploy the drawing
address addr = Drawing.deploy(bytecode, tokenId);
// Link the token ID to the drawing address
_drawingAddressForTokenId[tokenId] = addr;
// Mint the token (to the sender)
_safeMint(msg.sender, tokenId);
emit DrawingDeployed(tokenId, addr);
}
/**
* @notice Allows gas-less trading on OpenSea by safelisting the ProxyRegistry of the user
* @dev Override isApprovedForAll to check first if current operator is owner's OpenSea proxy
* @inheritdoc ERC721
*/
function isApprovedForAll(
address owner,
address operator
) public view override returns (bool) {
return super.isApprovedForAll(owner, operator) || _isOwnersOpenSeaProxy(owner, operator);
}
/******************************************************************************************
* _______ ____ _ ________ _ _ _____ ______ _____ ______ _____ _____
* |__ __/ __ \| |/ / ____| \ | | | __ \| ____| /\ | __ \| ____| __ \ / ____|
* | | | | | | ' /| |__ | \| | | |__) | |__ / \ | | | | |__ | |__) | (___
* | | | | | | < | __| | . ` | | _ /| __| / /\ \ | | | | __| | _ / \___ \
* | | | |__| | . \| |____| |\ | | | \ \| |____ / ____ \| |__| | |____| | \ \ ____) |
* |_| \____/|_|\_\______|_| \_| |_| \_\______/_/ \_\_____/|______|_| \_\_____/
*
* Functions for reading / querying tokens
*/
/**
* @dev Helper that gets the address for a given token and reverts if it is not present
* @param tokenId the token to get the address of
*/
function _addressForToken(uint256 tokenId) internal view returns (address) {
address addr = _drawingAddressForTokenId[tokenId];
require(addr != address(0), "UNKNOWN_ID");
return addr;
}
/**
* @dev Helper that pulls together the metadata struct for a given token
* @param tokenId the token to get the metadata for
* @param addr the address of its drawing contract
*/
function _getMetadata(uint256 tokenId, address addr) internal view returns (Token.Metadata memory) {
string memory tokenIdAsString = tokenId.toString();
return Token.Metadata(
string(abi.encodePacked("DBNFT #", tokenIdAsString)),
string(Drawing.description(addr)),
string(abi.encodePacked(_baseExternalURI, tokenIdAsString)),
uint256(uint160(addr)).toHexString()
);
}
/**
* @notice The ERC721 tokenURI of the given token as an application/json data URI
* @param tokenId the token to get the tokenURI of
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
address addr = _addressForToken(tokenId);
(, bytes memory bitmapData) = Drawing.render(addr);
Token.Metadata memory metadata = _getMetadata(tokenId, addr);
return Serialize.tokenURI(bitmapData, metadata);
}
/**
* @notice Returns the metadata of the token, without the image data, as a JSON string
* @param tokenId the token to get the metadata of
*/
function tokenMetadata(uint256 tokenId) public view returns (string memory) {
address addr = _addressForToken(tokenId);
Token.Metadata memory metadata = _getMetadata(tokenId, addr);
return Serialize.metadataAsJSON(metadata);
}
/**
* @notice Returns the underlying bytecode of the drawing contract
* @param tokenId the token to get the drawing bytecode of
*/
function tokenCode(uint256 tokenId) public view returns (bytes memory) {
address addr = _addressForToken(tokenId);
return addr.code;
}
/**
* @notice Renders the token and returns an estimate of the gas used and the bitmap data itself
* @param tokenId the token to render
*/
function renderToken(uint256 tokenId) public view returns (uint256, bytes memory) {
address addr = _addressForToken(tokenId);
return Drawing.render(addr);
}
/**
* @notice Returns a list of which tokens in the [0, LAST_ALLOWLISTED_TOKEN_ID]
* have already been minted.
*/
function mintedAllowlistedTokens() public view returns (uint256[] memory) {
uint8 count = 0;
for (uint8 i = 0; i <= LAST_ALLOWLISTED_TOKEN_ID; i++) {
if (_exists(i)) {
count++;
}
}
uint256[] memory result = new uint256[](count);
count = 0;
for (uint8 i = 0; i <= LAST_ALLOWLISTED_TOKEN_ID; i++) {
if (_exists(i)) {
result[count] = i;
count++;
}
}
return result;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./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 {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev 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;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol";
/**
* @dev Modified copy of OpenZeppelin ERC721 Enumerable.
*
* Changes:
* - gets rid of _removeTokenFromAllTokensEnumeration: no burns (saves space)
* - adds public accessor for the allTokens array
*/
abstract contract DBNERC721Enumerable 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;
/**
* @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), "OWNER_INDEX_OOB");
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 < DBNERC721Enumerable.totalSupply(), "GLOBAL_INDEX_OOB");
return _allTokens[index];
}
/**
* @notice Get a list of all minted tokens.
* @dev No guarantee of order.
*/
function allTokens() public view returns (uint256[] memory) {
return _allTokens;
}
/**
* @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`.
* - `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 != 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 {
_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];
}
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// Based off of https://gist.github.com/dievardump/483eb43bc6ed30b14f01e01842e3339b/
/// - but removes the _contractURI bits
/// - and makes it abstract
/// @title OpenSea contract helper that defines a few things
/// @author Simon Fremaux (@dievardump)
/// @dev This is a contract used to add OpenSea's
/// gas-less trading and contractURI support
abstract contract OpenSeaTradable {
address private _proxyRegistry;
/// @notice Returns the current OS proxyRegistry address registered
function openSeaProxyRegistry() public view returns (address) {
return _proxyRegistry;
}
/// @notice Helper allowing OpenSea gas-less trading by verifying who's operator
/// for owner
/// @dev Allows to check if `operator` is owner's OpenSea proxy on eth mainnet / rinkeby
/// or to check if operator is OpenSea's proxy contract on Polygon and Mumbai
/// @param owner the owner we check for
/// @param operator the operator (proxy) we check for
function _isOwnersOpenSeaProxy(address owner, address operator) internal virtual view
returns (bool)
{
address proxyRegistry_ = _proxyRegistry;
// if we have a proxy registry
if (proxyRegistry_ != address(0)) {
address ownerProxy = ProxyRegistry(proxyRegistry_).proxies(owner);
return ownerProxy == operator;
}
return false;
}
/// @dev Internal function to set the _proxyRegistry
/// @param proxyRegistryAddress the new proxy registry address
function _setOpenSeaRegistry(address proxyRegistryAddress) internal virtual {
_proxyRegistry = proxyRegistryAddress;
}
}
contract ProxyRegistry {
mapping(address => address) public proxies;
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
/**
* @dev Implements a mixin that uses ECDSA cryptography to restrict token minting to "ticket"-holders.
* This allows off-chain, gasless allowlisting of minting.
*
* A "Ticket" is a logical tuple of:
* - the Token ID
* - the address of a minter
* - the address of the token contract
* - a ticket ID (random number)
*
* By signing this tuple, the owner of the contract can grant permission to a specific address
* to mint a specific token ID at that specific token contract.
*/
abstract contract OwnerSignedTicketRestrictable is Ownable {
// Mapping to enable (very basic) ticket revocation
mapping (uint256 => bool) private _revokedTickets;
/**
* @dev Throws if the given signature, signed by the contract owner, does not grant
* the transaction sender a ticket to mint the given tokenId
* @param tokenId the ID of the token to check
* @param ticketId the ID of the ticket (included in signature)
* @param signature the bytes of the signature to use for verification
*
* This delegates straight into the checkTicket public function.
*/
modifier onlyWithTicketFor(uint256 tokenId, uint256 ticketId, bytes memory signature) {
checkTicket(msg.sender, tokenId, ticketId, signature);
_;
}
/**
* @notice Check the validity of a signature
* @dev Throws if the given signature wasn't signed by the contract owner for the
* "ticket" described by address(this) and the passed parameters
* (or if the ticket ID is revoked)
* @param minter the address of the minter in the ticket
* @param tokenId the token ID of the ticket
* @param ticketId the ticket ID
* @param signature the bytes of the signature
*
* Reuse of a ticket is prevented by existing controls preventing double-minting.
*/
function checkTicket(
address minter,
uint256 tokenId,
uint256 ticketId,
bytes memory signature
) public view {
bytes memory params = abi.encode(
address(this),
minter,
tokenId,
ticketId
);
address addr = ECDSA.recover(
ECDSA.toEthSignedMessageHash(keccak256(params)),
signature
);
require(addr == owner(), "BAD_SIGNATURE");
require(!_revokedTickets[ticketId], "TICKET_REVOKED");
}
/**
* @notice Revokes the given ticket IDs, preventing them from being used in the future
* @param ticketIds the ticket IDs to revoke
* @dev This can do nothing if the ticket ID has already been used, but
* this function gives an escape hatch for accidents, etc.
*/
function revokeTickets(uint256[] calldata ticketIds) public onlyOwner {
for (uint i=0; i<ticketIds.length; i++) {
_revokedTickets[ticketIds[i]] = true;
}
}
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./BitmapHeader.sol";
/**
* @dev Internal helper library to encapsulate interactions with a "Drawing" contract
*/
library Drawing {
/**
* @dev Deploys the given bytecode as a drawing contract
* @param bytecode The bytecode to pass to the CREATE opcode
* Must have been generated by the DBN compiler for predictable results.
* @param tokenId The tokenId to inject into the bytecode
* @return the address of the newly created contract
*
* Will also inject the given tokenID into the bytecode before deploy so that
* It is available in the deployed contract's context via a codecopy.
*
* The bytecode passed needs to be _deploy_ bytecode (so end up returning the
* actual bytecode). If any issues occur with the CREATE the transaction
* will fail with an assert (consuming all remaining gas). Detailed reasoning inline.
*/
function deploy(bytes memory bytecode, uint256 tokenId) internal returns (address) {
// First, inject the token id into the bytecode.
// The end of the bytecode is [2 bytes token id][32 bytes ipfs hash]
// (and we get the tokenID in in bigendian)
// This clearly assumes some coordination with the compiler (leaving this space blank!)
bytecode[bytecode.length - 32 - 2] = bytes1(uint8((tokenId & 0xFF00) >> 8));
bytecode[bytecode.length - 32 - 1] = bytes1(uint8(tokenId & 0xFF));
address addr;
assembly {
addr := create(0, add(bytecode, 0x20), mload(bytecode))
}
/*
if addr is zero, a few things could have happened:
a) out-of-gas in the create (which gets forwarded [current*(63/64) - 32000])
b) other exceptional halt (call stack too deep, invalid jump, etc)
c) revert from the create
in a): we should drain all existing gas and effectively bubble up the out of gas.
this makes sure that gas estimators do the right thing
in b): this is a nasty situation, so let's just drain away our gas anyway (true assert)
in c): pretty much same as b) — this is a bug in the passed bytecode, and we should fail.
that said, we _could_ check the μo return buffer for REVERT data, but no need for now.
So no matter what, we want to "assert" the addr is not zero
*/
assert(addr != address(0));
return addr;
}
/**
* @dev Renders the specified drawing contract as a bitmap
* @param addr The address of the drawing contract
* @return an estimation of the gas used and the 10962 bytes of the bitmap
*
* It calls the "0xBD" opcode of the drawing to get just the bitmap pixel data;
* the bitmap header is generated within this calling contract. This is to ensure
* that even if the deployed drawing doesn't conform to the DBN-drawing spec,
* a valid bitmap will always be returned.
*
* To further ensure that a valid bitmap is always returned, if the call
* to the drawing contract reverts, a bitmap will still be returned
* (though with the center pixel set to "55" to facilitate debugging)
*/
function render(address addr) internal view returns (uint256, bytes memory) {
uint bitmapLength = 10962;
uint headerLength = 40 + 14 + 404;
uint pixelDataLength = (10962 - headerLength);
bytes memory result = new bytes(bitmapLength);
bytes memory input = hex"BD";
uint256 startGas = gasleft();
BitmapHeader.writeTo(result);
uint resultOffset = 0x20 + headerLength; // after the header (and 0x20 for the dynamic byte length)
assembly {
let success := staticcall(
gas(),
addr,
add(input, 0x20),
1,
0, // return dst, but we're using the returnbuffer
0 // return length (we're using the returnbuffer)
)
let dataDst := add(result, resultOffset)
switch success
case 1 {
// Render call succeeded!
// copy min(returndataize, pixelDataLength) from the returnbuffer
// in happy path: returndatasize === pixeldatalength
// -> then great, either
// unexpected (too little data): returndatasize < pixeldatalength
// -> then we mustn't copy too much from the buffer! (use returndatasize)
// unexpected (too much data): returndatasize > pixeldatalength
// -> then we mustn't overflow our result! (use pixeldatalength)
let copySize := returndatasize()
if gt(copySize, pixelDataLength) {
copySize := pixelDataLength
}
returndatacopy(
dataDst, // dst offset
0, // src offset
copySize // length
)
}
case 0 {
// Render call failed :/
// Leave a little indicating pixel to hopefully help debugging
mstore8(
add(dataDst, 5250), // location of the center pixel (50 * 104 + 50)
0x55
)
}
}
// this overestimates _some_, but that's fine
uint256 endGas = gasleft();
return ((startGas - endGas), result);
}
/**
* @dev Gets the description stored in the code of a drawing contract
* @param addr The address of the drawing contract
* @return a (possibly empty) string description of the drawing
*
* It calls the "0xDE" opcode of the drawing to get its description.
* If the call fails, it will return an empty string.
*/
function description(address addr) internal view returns (string memory) {
(bool success, bytes memory desc) = addr.staticcall(hex"DE");
if (success) {
return string(desc);
} else {
return "";
}
}
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Namespace to encapsulate a "Metadata" struct for a drawing
*/
library Token {
struct Metadata {
string name;
string description;
string externalUrl;
string drawingAddress;
}
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./Token.sol";
import "./Base64.sol";
/**
* @dev Internal library encapsulating JSON / Token URI serialization
*/
library Serialize {
/**
* @dev Generates a ERC721 TokenURI for the given data
* @param bitmapData The raw bytes of the drawing's bitmap
* @param metadata The struct holding information about the drawing
* @return a string application/json data URI containing the token information
*
* We do _not_ base64 encode the JSON. This results in a slightly non-compliant
* data URI, because of the commas (and potential non-URL-safe characters).
* Empirically, this is fine: and re-base64-encoding everything would use
* gas and time and is not worth it.
*
* There's also a few ways we could encode the image in the metadata JSON:
* 1. image/bmp data url in the `image` field (base64-encoded given binary data)
* 2. raw svg data in the `image_data` field
* 3. image/svg data url in the `image` field (containing a base64-encoded image, but not itself base64-encoded)
* 4. (3), but with another layer of base64 encoding
* Through some trial and error, (1) does not work with Rarible or OpenSea. The rest do. (4) would be yet another
* layer of base64 (taking time, so is not desirable), (2) uses a potentially non-standard field, so we use (3).
*/
function tokenURI(bytes memory bitmapData, Token.Metadata memory metadata) internal pure returns (string memory) {
string memory imageKey = "image";
bytes memory imageData = _svgDataURI(bitmapData);
string memory fragment = _metadataJSONFragmentWithoutImage(metadata);
return string(abi.encodePacked(
'data:application/json,',
fragment,
// image data :)
'","', imageKey, '":"', imageData, '"}'
));
}
/**
* @dev Returns just the metadata of the image (no bitmap data) as a JSON string
* @param metadata The struct holding information about the drawing
*/
function metadataAsJSON(Token.Metadata memory metadata) internal pure returns (string memory) {
string memory fragment = _metadataJSONFragmentWithoutImage(metadata);
return string(abi.encodePacked(
fragment,
'"}'
));
}
/**
* @dev Returns a partial JSON string with the metadata of the image.
* Used by both the full tokenURI and the plain-metadata serializers.
* @param metadata The struct holding information about the drawing
*/
function _metadataJSONFragmentWithoutImage(Token.Metadata memory metadata) internal pure returns (string memory) {
return string(abi.encodePacked(
// name
'{"name":"',
metadata.name,
// description
'","description":"',
metadata.description,
// external_url
'","external_url":"',
metadata.externalUrl,
// code address
'","drawing_address":"',
metadata.drawingAddress
));
}
/**
* @dev Generates a data URI of an SVG containing an <image> tag containing the given bitmapData
* @param bitmapData The raw bytes of the drawing's bitmap
*/
function _svgDataURI(bytes memory bitmapData) internal pure returns (bytes memory) {
return abi.encodePacked(
"data:image/svg+xml,",
"<svg xmlns='http://www.w3.org/2000/svg' width='303' height='303'><image width='303' height='303' style='image-rendering: pixelated' href='",
"data:image/bmp;base64,",
Base64.encode(bitmapData),
"'/></svg>"
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/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;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./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;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s;
uint8 v;
assembly {
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Library encapsulating logic to generate the header + palette for a bitmap.
*
* Uses the "40-byte" header format, as described at
* http://www.ece.ualberta.ca/~elliott/ee552/studentAppNotes/2003_w/misc/bmp_file_format/bmp_file_format.htm
*
* Note that certain details (width, height, palette size, file size) are hardcoded
* based off the DBN-specific assumptions of 101x101 with 101 shades of grey.
*
*/
library BitmapHeader {
bytes32 internal constant HEADER1 = 0x424dd22a000000000000ca010000280000006500000065000000010008000000;
bytes22 internal constant HEADER2 = 0x00000000000000000000000000006500000000000000;
/**
* @dev Writes a 458 byte bitmap header + palette to the given array
* @param output The destination array. Gets mutated!
*/
function writeTo(bytes memory output) internal pure {
assembly {
mstore(add(output, 0x20), HEADER1)
mstore(add(output, 0x40), HEADER2)
}
// palette index is "DBN" color : [0, 100]
// map that to [0, 255] via:
// 255 - ((255 * c) / 100)
for (uint i = 0; i < 101; i++) {
bytes1 c = bytes1(uint8(255 - ((255 * i) / 100)));
uint o = i*4 + 54; // after the header
output[o] = c;
output[o + 1] = c;
output[o + 2] = c;
}
}
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Helper library for base64-encoding bytes
*/
library Base64 {
uint256 internal constant ALPHA1 = 0x4142434445464748494a4b4c4d4e4f505152535455565758595a616263646566;
uint256 internal constant ALPHA2 = 0x6768696a6b6c6d6e6f707172737475767778797a303132333435363738392b2f;
/**
* @dev Encodes the given bytearray to base64
* @param input The input data
* @return the output data
*/
function encode(bytes memory input) internal pure returns (bytes memory) {
if (input.length == 0) {
return input;
}
bytes memory output = new bytes(_encodedLength(input.length));
uint remaining = input.length;
assembly {
let src := add(input, 0x20)
let dst := add(output, 0x20)
// chunk loop
for {} gt(remaining, 0) {} {
let chunk := shr(16, mload(src))
let processing := 30
let sixtetCounter := 240 // 30 * 8
if lt(remaining, 30) {
processing := remaining
// slide right by 30–#remaining bytes (shl by 3 to get bits)
chunk := shr(shl(3, sub(30, remaining)), chunk)
// but now it needs to be nudge to the left by a few bits,
// to make sure total number of bits is multiple of 6
// 0 mod 3: nudge 0 bits
// 1 mod 3: nudge 4 bits
// 2 mod 3: nudge 2 bits
// we take advantage that this is the same as
// (v * 4) % 6
// this is empirically true, though I don't remember the number theory proving it
let nudgeBits := mulmod(remaining, 4, 6)
chunk := shl(nudgeBits, chunk)
// initial sixtet (remaining * 8 + nudge)
sixtetCounter := add(shl(3, remaining), nudgeBits)
}
remaining := sub(remaining, processing)
src := add(src, processing)
// byte loop
for {} gt(sixtetCounter, 0) {} {
sixtetCounter := sub(sixtetCounter, 6)
let val := shr(sixtetCounter, and(shl(sixtetCounter, 0x3F), chunk))
let alpha := ALPHA1
if gt(val, 0x1F) {
alpha := ALPHA2
val := sub(val, 0x20)
}
let char := byte(val, alpha)
mstore8(dst, char)
dst := add(dst, 1)
}
}
// padding depending on input length % 3
switch mod(mload(input), 3)
case 1 {
// two pads
mstore8(dst, 0x3D) // 0x3d is =
mstore8(add(1, dst), 0x3D) // 0x3d is =
}
case 2 {
// one pad
mstore8(dst, 0x3D)
}
}
return output;
}
/**
* @dev Helper to get the length of the output data
*
* Implements Ceil(inputLength / 3) * 4
*/
function _encodedLength(uint inputLength) internal pure returns (uint) {
return ((inputLength + 2) / 3) * 4;
}
} | Sets the cost to mint. Only the owner can call this./ | function setMintPrice(uint256 price) public onlyOwner {
_mintPrice = price;
}
| 13,463,207 |
./partial_match/1/0x724Ba15845719549ea1eA2f0aAC9D75d31DbD818/sources/Token.sol | See {IToken-compliance}./ | function compliance() external override view returns (ICompliance) {
return tokenCompliance;
}
| 3,940,264 |
./partial_match/1/0x25C7C475934f40908523a36d5d7ea810D890b50F/sources/contracts/L1/Colosseum.sol | Returns the challenge corresponding to the given L2 output index. _outputIndex Index of the L2 checkpoint output. _challenger Address of the challenger. return The challenge data./ | function getChallenge(uint256 _outputIndex, address _challenger)
external
view
returns (Types.Challenge memory)
{
return challenges[_outputIndex][_challenger];
}
| 16,186,970 |
./partial_match/1/0xB048Bbc1Ee6b733FFfCFb9e9CeF7375518e25997/sources/contracts/lens/QuoterV2.sol | @inheritdoc IPancakeV3SwapCallback | function pancakeV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes memory path
) external view override {
(address tokenIn, address tokenOut, uint24 fee) = path.decodeFirstPool();
CallbackValidation.verifyCallback(deployer, tokenIn, tokenOut, fee);
(bool isExactInput, uint256 amountToPay, uint256 amountReceived) =
amount0Delta > 0
? (tokenIn < tokenOut, uint256(amount0Delta), uint256(-amount1Delta))
: (tokenOut < tokenIn, uint256(amount1Delta), uint256(-amount0Delta));
IPancakeV3Pool pool = getPool(tokenIn, tokenOut, fee);
(uint160 sqrtPriceX96After, int24 tickAfter, , , , , ) = pool.slot0();
if (isExactInput) {
assembly {
let ptr := mload(0x40)
mstore(ptr, amountReceived)
mstore(add(ptr, 0x20), sqrtPriceX96After)
mstore(add(ptr, 0x40), tickAfter)
revert(ptr, 96)
}
assembly {
let ptr := mload(0x40)
mstore(ptr, amountToPay)
mstore(add(ptr, 0x20), sqrtPriceX96After)
mstore(add(ptr, 0x40), tickAfter)
revert(ptr, 96)
}
}
}
| 2,770,943 |
// File: contracts\lib\TransferHelper.sol
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.3;
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED');
}
function safeTransfer(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED');
}
function safeTransferFrom(address token, address from, address to, uint value) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED');
}
function safeTransferETH(address to, uint value) internal {
(bool success,) = to.call{value:value}(new bytes(0));
require(success, 'TransferHelper: ETH_TRANSFER_FAILED');
}
}
// File: contracts\interface\INestMining.sol
/// @dev This interface defines the mining methods for nest
interface INestMining {
/// @dev Post event
/// @param tokenAddress The address of TOKEN contract
/// @param miner Address of miner
/// @param index Index of the price sheet
/// @param ethNum The numbers of ethers to post sheets
event Post(address tokenAddress, address miner, uint index, uint ethNum, uint price);
/* ========== Structures ========== */
/// @dev Nest mining configuration structure
struct Config {
// Eth number of each post. 30
// We can stop post and taking orders by set postEthUnit to 0 (closing and withdraw are not affected)
uint32 postEthUnit;
// Post fee(0.0001eth,DIMI_ETHER). 1000
uint16 postFeeUnit;
// Proportion of miners digging(10000 based). 8000
uint16 minerNestReward;
// The proportion of token dug by miners is only valid for the token created in version 3.0
// (10000 based). 9500
uint16 minerNTokenReward;
// When the circulation of ntoken exceeds this threshold, post() is prohibited(Unit: 10000 ether). 500
uint32 doublePostThreshold;
// The limit of ntoken mined blocks. 100
uint16 ntokenMinedBlockLimit;
// -- Public configuration
// The number of times the sheet assets have doubled. 4
uint8 maxBiteNestedLevel;
// Price effective block interval. 20
uint16 priceEffectSpan;
// The amount of nest to pledge for each post(Unit: 1000). 100
uint16 pledgeNest;
}
/// @dev PriceSheetView structure
struct PriceSheetView {
// Index of the price sheeet
uint32 index;
// Address of miner
address miner;
// The block number of this price sheet packaged
uint32 height;
// The remain number of this price sheet
uint32 remainNum;
// The eth number which miner will got
uint32 ethNumBal;
// The eth number which equivalent to token's value which miner will got
uint32 tokenNumBal;
// The pledged number of nest in this sheet. (Unit: 1000nest)
uint24 nestNum1k;
// The level of this sheet. 0 expresses initial price sheet, a value greater than 0 expresses bite price sheet
uint8 level;
// Post fee shares, if there are many sheets in one block, this value is used to divide up mining value
uint8 shares;
// The token price. (1eth equivalent to (price) token)
uint152 price;
}
/* ========== Configuration ========== */
/// @dev Modify configuration
/// @param config Configuration object
function setConfig(Config memory config) external;
/// @dev Get configuration
/// @return Configuration object
function getConfig() external view returns (Config memory);
/// @dev Set the ntokenAddress from tokenAddress, if ntokenAddress is equals to tokenAddress, means the token is disabled
/// @param tokenAddress Destination token address
/// @param ntokenAddress The ntoken address
function setNTokenAddress(address tokenAddress, address ntokenAddress) external;
/// @dev Get the ntokenAddress from tokenAddress, if ntokenAddress is equals to tokenAddress, means the token is disabled
/// @param tokenAddress Destination token address
/// @return The ntoken address
function getNTokenAddress(address tokenAddress) external view returns (address);
/* ========== Mining ========== */
/// @notice Post a price sheet for TOKEN
/// @dev It is for TOKEN (except USDT and NTOKENs) whose NTOKEN has a total supply below a threshold (e.g. 5,000,000 * 1e18)
/// @param tokenAddress The address of TOKEN contract
/// @param ethNum The numbers of ethers to post sheets
/// @param tokenAmountPerEth The price of TOKEN
function post(address tokenAddress, uint ethNum, uint tokenAmountPerEth) external payable;
/// @notice Post two price sheets for a token and its ntoken simultaneously
/// @dev Support dual-posts for TOKEN/NTOKEN, (ETH, TOKEN) + (ETH, NTOKEN)
/// @param tokenAddress The address of TOKEN contract
/// @param ethNum The numbers of ethers to post sheets
/// @param tokenAmountPerEth The price of TOKEN
/// @param ntokenAmountPerEth The price of NTOKEN
function post2(address tokenAddress, uint ethNum, uint tokenAmountPerEth, uint ntokenAmountPerEth) external payable;
/// @notice Call the function to buy TOKEN/NTOKEN from a posted price sheet
/// @dev bite TOKEN(NTOKEN) by ETH, (+ethNumBal, -tokenNumBal)
/// @param tokenAddress The address of token(ntoken)
/// @param index The position of the sheet in priceSheetList[token]
/// @param takeNum The amount of biting (in the unit of ETH), realAmount = takeNum * newTokenAmountPerEth
/// @param newTokenAmountPerEth The new price of token (1 ETH : some TOKEN), here some means newTokenAmountPerEth
function takeToken(address tokenAddress, uint index, uint takeNum, uint newTokenAmountPerEth) external payable;
/// @notice Call the function to buy ETH from a posted price sheet
/// @dev bite ETH by TOKEN(NTOKEN), (-ethNumBal, +tokenNumBal)
/// @param tokenAddress The address of token(ntoken)
/// @param index The position of the sheet in priceSheetList[token]
/// @param takeNum The amount of biting (in the unit of ETH), realAmount = takeNum
/// @param newTokenAmountPerEth The new price of token (1 ETH : some TOKEN), here some means newTokenAmountPerEth
function takeEth(address tokenAddress, uint index, uint takeNum, uint newTokenAmountPerEth) external payable;
/// @notice Close a price sheet of (ETH, USDx) | (ETH, NEST) | (ETH, TOKEN) | (ETH, NTOKEN)
/// @dev Here we allow an empty price sheet (still in VERIFICATION-PERIOD) to be closed
/// @param tokenAddress The address of TOKEN contract
/// @param index The index of the price sheet w.r.t. `token`
function close(address tokenAddress, uint index) external;
/// @notice Close a batch of price sheets passed VERIFICATION-PHASE
/// @dev Empty sheets but in VERIFICATION-PHASE aren't allowed
/// @param tokenAddress The address of TOKEN contract
/// @param indices A list of indices of sheets w.r.t. `token`
function closeList(address tokenAddress, uint[] memory indices) external;
/// @notice Close two batch of price sheets passed VERIFICATION-PHASE
/// @dev Empty sheets but in VERIFICATION-PHASE aren't allowed
/// @param tokenAddress The address of TOKEN1 contract
/// @param tokenIndices A list of indices of sheets w.r.t. `token`
/// @param ntokenIndices A list of indices of sheets w.r.t. `ntoken`
function closeList2(address tokenAddress, uint[] memory tokenIndices, uint[] memory ntokenIndices) external;
/// @dev The function updates the statistics of price sheets
/// It calculates from priceInfo to the newest that is effective.
function stat(address tokenAddress) external;
/// @dev Settlement Commission
/// @param tokenAddress The token address
function settle(address tokenAddress) external;
/// @dev List sheets by page
/// @param tokenAddress Destination token address
/// @param offset Skip previous (offset) records
/// @param count Return (count) records
/// @param order Order. 0 reverse order, non-0 positive order
/// @return List of price sheets
function list(address tokenAddress, uint offset, uint count, uint order) external view returns (PriceSheetView[] memory);
/// @dev Estimated mining amount
/// @param tokenAddress Destination token address
/// @return Estimated mining amount
function estimate(address tokenAddress) external view returns (uint);
/// @dev Query the quantity of the target quotation
/// @param tokenAddress Token address. The token can't mine. Please make sure you don't use the token address when calling
/// @param index The index of the sheet
/// @return minedBlocks Mined block period from previous block
/// @return totalShares Total shares of sheets in the block
function getMinedBlocks(address tokenAddress, uint index) external view returns (uint minedBlocks, uint totalShares);
/* ========== Accounts ========== */
/// @dev Withdraw assets
/// @param tokenAddress Destination token address
/// @param value The value to withdraw
function withdraw(address tokenAddress, uint value) external;
/// @dev View the number of assets specified by the user
/// @param tokenAddress Destination token address
/// @param addr Destination address
/// @return Number of assets
function balanceOf(address tokenAddress, address addr) external view returns (uint);
/// @dev Gets the address corresponding to the given index number
/// @param index The index number of the specified address
/// @return The address corresponding to the given index number
function indexAddress(uint index) external view returns (address);
/// @dev Gets the registration index number of the specified address
/// @param addr Destination address
/// @return 0 means nonexistent, non-0 means index number
function getAccountIndex(address addr) external view returns (uint);
/// @dev Get the length of registered account array
/// @return The length of registered account array
function getAccountCount() external view returns (uint);
}
// File: contracts\interface\INestQuery.sol
/// @dev This interface defines the methods for price query
interface INestQuery {
/// @dev Get the latest trigger price
/// @param tokenAddress Destination token address
/// @return blockNumber The block number of price
/// @return price The token price. (1eth equivalent to (price) token)
function triggeredPrice(address tokenAddress) external view returns (uint blockNumber, uint price);
/// @dev Get the full information of latest trigger price
/// @param tokenAddress Destination token address
/// @return blockNumber The block number of price
/// @return price The token price. (1eth equivalent to (price) token)
/// @return avgPrice Average price
/// @return sigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that
/// the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447,
/// it means that the volatility has exceeded the range that can be expressed
function triggeredPriceInfo(address tokenAddress) external view returns (
uint blockNumber,
uint price,
uint avgPrice,
uint sigmaSQ
);
/// @dev Find the price at block number
/// @param tokenAddress Destination token address
/// @param height Destination block number
/// @return blockNumber The block number of price
/// @return price The token price. (1eth equivalent to (price) token)
function findPrice(
address tokenAddress,
uint height
) external view returns (uint blockNumber, uint price);
/// @dev Get the latest effective price
/// @param tokenAddress Destination token address
/// @return blockNumber The block number of price
/// @return price The token price. (1eth equivalent to (price) token)
function latestPrice(address tokenAddress) external view returns (uint blockNumber, uint price);
/// @dev Get the last (num) effective price
/// @param tokenAddress Destination token address
/// @param count The number of prices that want to return
/// @return An array which length is num * 2, each two element expresses one price like blockNumber|price
function lastPriceList(address tokenAddress, uint count) external view returns (uint[] memory);
/// @dev Returns the results of latestPrice() and triggeredPriceInfo()
/// @param tokenAddress Destination token address
/// @return latestPriceBlockNumber The block number of latest price
/// @return latestPriceValue The token latest price. (1eth equivalent to (price) token)
/// @return triggeredPriceBlockNumber The block number of triggered price
/// @return triggeredPriceValue The token triggered price. (1eth equivalent to (price) token)
/// @return triggeredAvgPrice Average price
/// @return triggeredSigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that
/// the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447,
/// it means that the volatility has exceeded the range that can be expressed
function latestPriceAndTriggeredPriceInfo(address tokenAddress) external view
returns (
uint latestPriceBlockNumber,
uint latestPriceValue,
uint triggeredPriceBlockNumber,
uint triggeredPriceValue,
uint triggeredAvgPrice,
uint triggeredSigmaSQ
);
/// @dev Get the latest trigger price. (token and ntoken)
/// @param tokenAddress Destination token address
/// @return blockNumber The block number of price
/// @return price The token price. (1eth equivalent to (price) token)
/// @return ntokenBlockNumber The block number of ntoken price
/// @return ntokenPrice The ntoken price. (1eth equivalent to (price) ntoken)
function triggeredPrice2(address tokenAddress) external view returns (
uint blockNumber,
uint price,
uint ntokenBlockNumber,
uint ntokenPrice
);
/// @dev Get the full information of latest trigger price. (token and ntoken)
/// @param tokenAddress Destination token address
/// @return blockNumber The block number of price
/// @return price The token price. (1eth equivalent to (price) token)
/// @return avgPrice Average price
/// @return sigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that
/// the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447,
/// it means that the volatility has exceeded the range that can be expressed
/// @return ntokenBlockNumber The block number of ntoken price
/// @return ntokenPrice The ntoken price. (1eth equivalent to (price) ntoken)
/// @return ntokenAvgPrice Average price of ntoken
/// @return ntokenSigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that
/// the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447,
/// it means that the volatility has exceeded the range that can be expressed
function triggeredPriceInfo2(address tokenAddress) external view returns (
uint blockNumber,
uint price,
uint avgPrice,
uint sigmaSQ,
uint ntokenBlockNumber,
uint ntokenPrice,
uint ntokenAvgPrice,
uint ntokenSigmaSQ
);
/// @dev Get the latest effective price. (token and ntoken)
/// @param tokenAddress Destination token address
/// @return blockNumber The block number of price
/// @return price The token price. (1eth equivalent to (price) token)
/// @return ntokenBlockNumber The block number of ntoken price
/// @return ntokenPrice The ntoken price. (1eth equivalent to (price) ntoken)
function latestPrice2(address tokenAddress) external view returns (
uint blockNumber,
uint price,
uint ntokenBlockNumber,
uint ntokenPrice
);
}
// File: contracts\interface\INTokenController.sol
///@dev This interface defines the methods for ntoken management
interface INTokenController {
/// @notice when the auction of a token gets started
/// @param tokenAddress The address of the (ERC20) token
/// @param ntokenAddress The address of the ntoken w.r.t. token for incentives
/// @param owner The address of miner who opened the oracle
event NTokenOpened(address tokenAddress, address ntokenAddress, address owner);
/// @notice ntoken disable event
/// @param tokenAddress token address
event NTokenDisabled(address tokenAddress);
/// @notice ntoken enable event
/// @param tokenAddress token address
event NTokenEnabled(address tokenAddress);
/// @dev ntoken configuration structure
struct Config {
// The number of nest needed to pay for opening ntoken. 10000 ether
uint96 openFeeNestAmount;
// ntoken management is enabled. 0: not enabled, 1: enabled
uint8 state;
}
/// @dev A struct for an ntoken
struct NTokenTag {
// ntoken address
address ntokenAddress;
// How much nest has paid for open this ntoken
uint96 nestFee;
// token address
address tokenAddress;
// Index for this ntoken
uint40 index;
// Create time
uint48 startTime;
// State of this ntoken. 0: disabled; 1 normal
uint8 state;
}
/* ========== Governance ========== */
/// @dev Modify configuration
/// @param config Configuration object
function setConfig(Config memory config) external;
/// @dev Get configuration
/// @return Configuration object
function getConfig() external view returns (Config memory);
/// @dev Set the token mapping
/// @param tokenAddress Destination token address
/// @param ntokenAddress Destination ntoken address
/// @param state status for this map
function setNTokenMapping(address tokenAddress, address ntokenAddress, uint state) external;
/// @dev Get token address from ntoken address
/// @param ntokenAddress Destination ntoken address
/// @return token address
function getTokenAddress(address ntokenAddress) external view returns (address);
/// @dev Get ntoken address from token address
/// @param tokenAddress Destination token address
/// @return ntoken address
function getNTokenAddress(address tokenAddress) external view returns (address);
/* ========== ntoken management ========== */
/// @dev Bad tokens should be banned
function disable(address tokenAddress) external;
/// @dev enable ntoken
function enable(address tokenAddress) external;
/// @notice Open a NToken for a token by anyone (contracts aren't allowed)
/// @dev Create and map the (Token, NToken) pair in NestPool
/// @param tokenAddress The address of token contract
function open(address tokenAddress) external;
/* ========== VIEWS ========== */
/// @dev Get ntoken information
/// @param tokenAddress Destination token address
/// @return ntoken information
function getNTokenTag(address tokenAddress) external view returns (NTokenTag memory);
/// @dev Get opened ntoken count
/// @return ntoken count
function getNTokenCount() external view returns (uint);
/// @dev List ntoken information by page
/// @param offset Skip previous (offset) records
/// @param count Return (count) records
/// @param order Order. 0 reverse order, non-0 positive order
/// @return ntoken information by page
function list(uint offset, uint count, uint order) external view returns (NTokenTag[] memory);
}
// File: contracts\interface\INestLedger.sol
/// @dev This interface defines the nest ledger methods
interface INestLedger {
/// @dev Application Flag Changed event
/// @param addr DAO application contract address
/// @param flag Authorization flag, 1 means authorization, 0 means cancel authorization
event ApplicationChanged(address addr, uint flag);
/// @dev Configuration structure of nest ledger contract
struct Config {
// nest reward scale(10000 based). 2000
uint16 nestRewardScale;
// // ntoken reward scale(10000 based). 8000
// uint16 ntokenRewardScale;
}
/// @dev Modify configuration
/// @param config Configuration object
function setConfig(Config memory config) external;
/// @dev Get configuration
/// @return Configuration object
function getConfig() external view returns (Config memory);
/// @dev Set DAO application
/// @param addr DAO application contract address
/// @param flag Authorization flag, 1 means authorization, 0 means cancel authorization
function setApplication(address addr, uint flag) external;
/// @dev Check DAO application flag
/// @param addr DAO application contract address
/// @return Authorization flag, 1 means authorization, 0 means cancel authorization
function checkApplication(address addr) external view returns (uint);
/// @dev Carve reward
/// @param ntokenAddress Destination ntoken address
function carveETHReward(address ntokenAddress) external payable;
/// @dev Add reward
/// @param ntokenAddress Destination ntoken address
function addETHReward(address ntokenAddress) external payable;
/// @dev The function returns eth rewards of specified ntoken
/// @param ntokenAddress The ntoken address
function totalETHRewards(address ntokenAddress) external view returns (uint);
/// @dev Pay
/// @param ntokenAddress Destination ntoken address. Indicates which ntoken to pay with
/// @param tokenAddress Token address of receiving funds (0 means ETH)
/// @param to Address to receive
/// @param value Amount to receive
function pay(address ntokenAddress, address tokenAddress, address to, uint value) external;
/// @dev Settlement
/// @param ntokenAddress Destination ntoken address. Indicates which ntoken to settle with
/// @param tokenAddress Token address of receiving funds (0 means ETH)
/// @param to Address to receive
/// @param value Amount to receive
function settle(address ntokenAddress, address tokenAddress, address to, uint value) external payable;
}
// File: contracts\interface\INToken.sol
/// @dev ntoken interface
interface INToken {
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
/// @dev Mint
/// @param value The amount of NToken to add
function increaseTotal(uint256 value) external;
/// @notice The view of variables about minting
/// @dev The naming follows Nestv3.0
/// @return createBlock The block number where the contract was created
/// @return recentlyUsedBlock The block number where the last minting went
function checkBlockInfo() external view returns(uint256 createBlock, uint256 recentlyUsedBlock);
/// @dev The ABI keeps unchanged with old NTokens, so as to support token-and-ntoken-mining
/// @return The address of bidder
function checkBidder() external view returns(address);
/// @notice The view of totalSupply
/// @return The total supply of ntoken
function totalSupply() external view returns (uint256);
/// @dev The view of balances
/// @param owner The address of an account
/// @return The balance of the account
function balanceOf(address owner) 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);
}
// File: contracts\interface\INestMapping.sol
/// @dev The interface defines methods for nest builtin contract address mapping
interface INestMapping {
/// @dev Set the built-in contract address of the system
/// @param nestTokenAddress Address of nest token contract
/// @param nestNodeAddress Address of nest node contract
/// @param nestLedgerAddress INestLedger implementation contract address
/// @param nestMiningAddress INestMining implementation contract address for nest
/// @param ntokenMiningAddress INestMining implementation contract address for ntoken
/// @param nestPriceFacadeAddress INestPriceFacade implementation contract address
/// @param nestVoteAddress INestVote implementation contract address
/// @param nestQueryAddress INestQuery implementation contract address
/// @param nnIncomeAddress NNIncome contract address
/// @param nTokenControllerAddress INTokenController implementation contract address
function setBuiltinAddress(
address nestTokenAddress,
address nestNodeAddress,
address nestLedgerAddress,
address nestMiningAddress,
address ntokenMiningAddress,
address nestPriceFacadeAddress,
address nestVoteAddress,
address nestQueryAddress,
address nnIncomeAddress,
address nTokenControllerAddress
) external;
/// @dev Get the built-in contract address of the system
/// @return nestTokenAddress Address of nest token contract
/// @return nestNodeAddress Address of nest node contract
/// @return nestLedgerAddress INestLedger implementation contract address
/// @return nestMiningAddress INestMining implementation contract address for nest
/// @return ntokenMiningAddress INestMining implementation contract address for ntoken
/// @return nestPriceFacadeAddress INestPriceFacade implementation contract address
/// @return nestVoteAddress INestVote implementation contract address
/// @return nestQueryAddress INestQuery implementation contract address
/// @return nnIncomeAddress NNIncome contract address
/// @return nTokenControllerAddress INTokenController implementation contract address
function getBuiltinAddress() external view returns (
address nestTokenAddress,
address nestNodeAddress,
address nestLedgerAddress,
address nestMiningAddress,
address ntokenMiningAddress,
address nestPriceFacadeAddress,
address nestVoteAddress,
address nestQueryAddress,
address nnIncomeAddress,
address nTokenControllerAddress
);
/// @dev Get address of nest token contract
/// @return Address of nest token contract
function getNestTokenAddress() external view returns (address);
/// @dev Get address of nest node contract
/// @return Address of nest node contract
function getNestNodeAddress() external view returns (address);
/// @dev Get INestLedger implementation contract address
/// @return INestLedger implementation contract address
function getNestLedgerAddress() external view returns (address);
/// @dev Get INestMining implementation contract address for nest
/// @return INestMining implementation contract address for nest
function getNestMiningAddress() external view returns (address);
/// @dev Get INestMining implementation contract address for ntoken
/// @return INestMining implementation contract address for ntoken
function getNTokenMiningAddress() external view returns (address);
/// @dev Get INestPriceFacade implementation contract address
/// @return INestPriceFacade implementation contract address
function getNestPriceFacadeAddress() external view returns (address);
/// @dev Get INestVote implementation contract address
/// @return INestVote implementation contract address
function getNestVoteAddress() external view returns (address);
/// @dev Get INestQuery implementation contract address
/// @return INestQuery implementation contract address
function getNestQueryAddress() external view returns (address);
/// @dev Get NNIncome contract address
/// @return NNIncome contract address
function getNnIncomeAddress() external view returns (address);
/// @dev Get INTokenController implementation contract address
/// @return INTokenController implementation contract address
function getNTokenControllerAddress() external view returns (address);
/// @dev Registered address. The address registered here is the address accepted by nest system
/// @param key The key
/// @param addr Destination address. 0 means to delete the registration information
function registerAddress(string memory key, address addr) external;
/// @dev Get registered address
/// @param key The key
/// @return Destination address. 0 means empty
function checkAddress(string memory key) external view returns (address);
}
// File: contracts\interface\INestGovernance.sol
/// @dev This interface defines the governance methods
interface INestGovernance is INestMapping {
/// @dev Set governance authority
/// @param addr Destination address
/// @param flag Weight. 0 means to delete the governance permission of the target address. Weight is not
/// implemented in the current system, only the difference between authorized and unauthorized.
/// Here, a uint96 is used to represent the weight, which is only reserved for expansion
function setGovernance(address addr, uint flag) external;
/// @dev Get governance rights
/// @param addr Destination address
/// @return Weight. 0 means to delete the governance permission of the target address. Weight is not
/// implemented in the current system, only the difference between authorized and unauthorized.
/// Here, a uint96 is used to represent the weight, which is only reserved for expansion
function getGovernance(address addr) external view returns (uint);
/// @dev Check whether the target address has governance rights for the given target
/// @param addr Destination address
/// @param flag Permission weight. The permission of the target address must be greater than this weight to pass the check
/// @return True indicates permission
function checkGovernance(address addr, uint flag) external view returns (bool);
}
// File: contracts\NestBase.sol
/// @dev Base contract of nest
contract NestBase {
// Address of nest token contract
address constant NEST_TOKEN_ADDRESS = 0x04abEdA201850aC0124161F037Efd70c74ddC74C;
// Genesis block number of nest
// NEST token contract is created at block height 6913517. However, because the mining algorithm of nest1.0
// is different from that at present, a new mining algorithm is adopted from nest2.0. The new algorithm
// includes the attenuation logic according to the block. Therefore, it is necessary to trace the block
// where the nest begins to decay. According to the circulation when nest2.0 is online, the new mining
// algorithm is used to deduce and convert the nest, and the new algorithm is used to mine the nest2.0
// on-line flow, the actual block is 5120000
uint constant NEST_GENESIS_BLOCK = 5120000;
/// @dev To support open-zeppelin/upgrades
/// @param nestGovernanceAddress INestGovernance implementation contract address
function initialize(address nestGovernanceAddress) virtual public {
require(_governance == address(0), 'NEST:!initialize');
_governance = nestGovernanceAddress;
}
/// @dev INestGovernance implementation contract address
address public _governance;
/// @dev Rewritten in the implementation contract, for load other contract addresses. Call
/// super.update(nestGovernanceAddress) when overriding, and override method without onlyGovernance
/// @param nestGovernanceAddress INestGovernance implementation contract address
function update(address nestGovernanceAddress) virtual public {
address governance = _governance;
require(governance == msg.sender || INestGovernance(governance).checkGovernance(msg.sender, 0), "NEST:!gov");
_governance = nestGovernanceAddress;
}
/// @dev Migrate funds from current contract to NestLedger
/// @param tokenAddress Destination token address.(0 means eth)
/// @param value Migrate amount
function migrate(address tokenAddress, uint value) external onlyGovernance {
address to = INestGovernance(_governance).getNestLedgerAddress();
if (tokenAddress == address(0)) {
INestLedger(to).addETHReward { value: value } (address(0));
} else {
TransferHelper.safeTransfer(tokenAddress, to, value);
}
}
//---------modifier------------
modifier onlyGovernance() {
require(INestGovernance(_governance).checkGovernance(msg.sender, 0), "NEST:!gov");
_;
}
modifier noContract() {
require(msg.sender == tx.origin, "NEST:!contract");
_;
}
}
// File: contracts\NestMining.sol
/// @dev This contract implemented the mining logic of nest
contract NestMining is NestBase, INestMining, INestQuery {
// /// @param nestTokenAddress Address of nest token contract
// /// @param nestGenesisBlock Genesis block number of nest
// constructor(address nestTokenAddress, uint nestGenesisBlock) {
// NEST_TOKEN_ADDRESS = nestTokenAddress;
// NEST_GENESIS_BLOCK = nestGenesisBlock;
// // Placeholder in _accounts, the index of a real account must greater than 0
// _accounts.push();
// }
/// @dev To support open-zeppelin/upgrades
/// @param nestGovernanceAddress INestGovernance implementation contract address
function initialize(address nestGovernanceAddress) override public {
super.initialize(nestGovernanceAddress);
// Placeholder in _accounts, the index of a real account must greater than 0
_accounts.push();
}
///@dev Definitions for the price sheet, include the full information. (use 256-bits, a storage unit in ethereum evm)
struct PriceSheet {
// Index of miner account in _accounts. for this way, mapping an address(which need 160-bits) to a 32-bits
// integer, support 4 billion accounts
uint32 miner;
// The block number of this price sheet packaged
uint32 height;
// The remain number of this price sheet
uint32 remainNum;
// The eth number which miner will got
uint32 ethNumBal;
// The eth number which equivalent to token's value which miner will got
uint32 tokenNumBal;
// The pledged number of nest in this sheet. (Unit: 1000nest)
uint24 nestNum1k;
// The level of this sheet. 0 expresses initial price sheet, a value greater than 0 expresses bite price sheet
uint8 level;
// Post fee shares, if there are many sheets in one block, this value is used to divide up mining value
uint8 shares;
// Represent price as this way, may lose precision, the error less than 1/10^14
// price = priceFraction * 16 ^ priceExponent
uint56 priceFloat;
}
/// @dev Definitions for the price information
struct PriceInfo {
// Record the index of price sheet, for update price information from price sheet next time.
uint32 index;
// The block number of this price
uint32 height;
// The remain number of this price sheet
uint32 remainNum;
// Price, represent as float
// Represent price as this way, may lose precision, the error less than 1/10^14
uint56 priceFloat;
// Avg Price, represent as float
// Represent price as this way, may lose precision, the error less than 1/10^14
uint56 avgFloat;
// Square of price volatility, need divide by 2^48
uint48 sigmaSQ;
}
/// @dev Price channel
struct PriceChannel {
// Array of price sheets
PriceSheet[] sheets;
// Price information
PriceInfo price;
// Commission is charged for every post(post2), the commission should be deposited to NestLedger,
// for saving gas, according to sheets.length, every increase of 256 will deposit once, The calculation formula is:
//
// totalFee = fee * increment
//
// In consideration of takeToken, takeEth, change postFeeUnit or miner pay more fee, the formula will be invalid,
// at this point, it is need to settle immediately, the details of triggering settlement logic are as follows
//
// 1. When there is a bite transaction(currentFee is 0), the counter of no fee sheets will be increase 1
// 2. If the Commission of this time is inconsistent with that of last time, deposit immediately
// 3. When the increment of sheets.length is 256, deposit immediately
// 4. Everyone can trigger immediate settlement by manually calling the settle() method
//
// In order to realize the logic above, the following values are defined
//
// 1. PriceChannel.feeInfo
// Low 128-bits represent last fee per post
// High 128-bits represent the current counter of no fee sheets (including settled)
//
// 2. COLLECT_REWARD_MASK
// The mask of batch deposit trigger, while COLLECT_REWARD_MASK & sheets.length == COLLECT_REWARD_MASK, it will trigger deposit,
// COLLECT_REWARD_MASK is set to 0xF for testing (means every 16 sheets will deposit once),
// and it will be set to 0xFF for mainnet (means every 256 sheets will deposit once)
// The information of mining fee
// Low 128-bits represent fee per post
// High 128-bits represent the current counter of no fee sheets (including settled)
uint feeInfo;
}
/// @dev Structure is used to represent a storage location. Storage variable can be used to avoid indexing from mapping many times
struct UINT {
uint value;
}
/// @dev Account information
struct Account {
// Address of account
address addr;
// Balances of mining account
// tokenAddress=>balance
mapping(address=>UINT) balances;
}
// Configuration
Config _config;
// Registered account information
Account[] _accounts;
// Mapping from address to index of account. address=>accountIndex
mapping(address=>uint) _accountMapping;
// Mapping from token address to price channel. tokenAddress=>PriceChannel
mapping(address=>PriceChannel) _channels;
// Mapping from token address to ntoken address. tokenAddress=>ntokenAddress
mapping(address=>address) _addressCache;
// Cache for genesis block number of ntoken. ntokenAddress=>genesisBlockNumber
mapping(address=>uint) _genesisBlockNumberCache;
// INestPriceFacade implementation contract address
address _nestPriceFacadeAddress;
// INTokenController implementation contract address
address _nTokenControllerAddress;
// INestLegder implementation contract address
address _nestLedgerAddress;
// Unit of post fee. 0.0001 ether
uint constant DIMI_ETHER = 0.0001 ether;
// The mask of batch deposit trigger, while COLLECT_REWARD_MASK & sheets.length == COLLECT_REWARD_MASK, it will trigger deposit,
// COLLECT_REWARD_MASK is set to 0xF for testing (means every 16 sheets will deposit once),
// and it will be set to 0xFF for mainnet (means every 256 sheets will deposit once)
uint constant COLLECT_REWARD_MASK = 0xFF;
// Ethereum average block time interval, 14 seconds
uint constant ETHEREUM_BLOCK_TIMESPAN = 14;
/* ========== Governance ========== */
/// @dev Rewritten in the implementation contract, for load other contract addresses. Call
/// super.update(nestGovernanceAddress) when overriding, and override method without onlyGovernance
/// @param nestGovernanceAddress INestGovernance implementation contract address
function update(address nestGovernanceAddress) override public {
super.update(nestGovernanceAddress);
(
//address nestTokenAddress
,
//address nestNodeAddress
,
//address nestLedgerAddress
_nestLedgerAddress,
//address nestMiningAddress
,
//address ntokenMiningAddress
,
//address nestPriceFacadeAddress
_nestPriceFacadeAddress,
//address nestVoteAddress
,
//address nestQueryAddress
,
//address nnIncomeAddress
,
//address nTokenControllerAddress
_nTokenControllerAddress
) = INestGovernance(nestGovernanceAddress).getBuiltinAddress();
}
/// @dev Modify configuration
/// @param config Configuration object
function setConfig(Config memory config) override external onlyGovernance {
_config = config;
}
/// @dev Get configuration
/// @return Configuration object
function getConfig() override external view returns (Config memory) {
return _config;
}
/// @dev Clear chache of token. while ntoken recreated, this method is need to call
/// @param tokenAddress Token address
function resetNTokenCache(address tokenAddress) external onlyGovernance {
// Clear cache
address ntokenAddress = _getNTokenAddress(tokenAddress);
_genesisBlockNumberCache[ntokenAddress] = 0;
_addressCache[tokenAddress] = _addressCache[ntokenAddress] = address(0);
}
/// @dev Set the ntokenAddress from tokenAddress, if ntokenAddress is equals to tokenAddress, means the token is disabled
/// @param tokenAddress Destination token address
/// @param ntokenAddress The ntoken address
function setNTokenAddress(address tokenAddress, address ntokenAddress) override external onlyGovernance {
_addressCache[tokenAddress] = ntokenAddress;
}
/// @dev Get the ntokenAddress from tokenAddress, if ntokenAddress is equals to tokenAddress, means the token is disabled
/// @param tokenAddress Destination token address
/// @return The ntoken address
function getNTokenAddress(address tokenAddress) override external view returns (address) {
return _addressCache[tokenAddress];
}
/* ========== Mining ========== */
// Get ntoken address of from token address
function _getNTokenAddress(address tokenAddress) private returns (address) {
address ntokenAddress = _addressCache[tokenAddress];
if (ntokenAddress == address(0)) {
ntokenAddress = INTokenController(_nTokenControllerAddress).getNTokenAddress(tokenAddress);
if (ntokenAddress != address(0)) {
_addressCache[tokenAddress] = ntokenAddress;
}
}
return ntokenAddress;
}
// Get genesis block number of ntoken
function _getNTokenGenesisBlock(address ntokenAddress) private returns (uint) {
uint genesisBlockNumber = _genesisBlockNumberCache[ntokenAddress];
if (genesisBlockNumber == 0) {
(genesisBlockNumber,) = INToken(ntokenAddress).checkBlockInfo();
_genesisBlockNumberCache[ntokenAddress] = genesisBlockNumber;
}
return genesisBlockNumber;
}
/// @notice Post a price sheet for TOKEN
/// @dev It is for TOKEN (except USDT and NTOKENs) whose NTOKEN has a total supply below a threshold (e.g. 5,000,000 * 1e18)
/// @param tokenAddress The address of TOKEN contract
/// @param ethNum The numbers of ethers to post sheets
/// @param tokenAmountPerEth The price of TOKEN
function post(address tokenAddress, uint ethNum, uint tokenAmountPerEth) override external payable {
Config memory config = _config;
// 1. Check arguments
require(ethNum > 0 && ethNum == uint(config.postEthUnit), "NM:!ethNum");
require(tokenAmountPerEth > 0, "NM:!price");
// 2. Check price channel
// Check if the token allow post()
address ntokenAddress = _getNTokenAddress(tokenAddress);
require(ntokenAddress != address(0) && ntokenAddress != tokenAddress, "NM:!tokenAddress");
// Unit of nest is different, but the total supply already exceeded the number of this issue. No additional judgment will be made
// ntoken is mint when the price sheet is closed (or withdrawn), this may be the problem that the user
// intentionally does not close or withdraw, which leads to the inaccurate judgment of the total amount. ignore
require(INToken(ntokenAddress).totalSupply() < uint(config.doublePostThreshold) * 10000 ether, "NM:!post2");
// 3. Load token channel and sheets
PriceChannel storage channel = _channels[tokenAddress];
PriceSheet[] storage sheets = channel.sheets;
// 4. Freeze assets
uint accountIndex = _addressIndex(msg.sender);
// Freeze token and nest
// Because of the use of floating-point representation(fraction * 16 ^ exponent), it may bring some precision loss
// After assets are frozen according to tokenAmountPerEth * ethNum, the part with poor accuracy may be lost when
// the assets are returned, It should be frozen according to decodeFloat(fraction, exponent) * ethNum
// However, considering that the loss is less than 1 / 10 ^ 14, the loss here is ignored, and the part of
// precision loss can be transferred out as system income in the future
_freeze2(
_accounts[accountIndex].balances,
tokenAddress,
tokenAmountPerEth * ethNum,
uint(config.pledgeNest) * 1000 ether
);
// 5. Deposit fee
// The revenue is deposited every 256 sheets, deducting the times of taking orders and the settled part
uint length = sheets.length;
uint shares = _collect(config, channel, ntokenAddress, length, msg.value - ethNum * 1 ether);
require(shares > 0 && shares < 256, "NM:!fee");
// Calculate the price
// According to the current mechanism, the newly added sheet cannot take effect, so the calculated price
// is placed before the sheet is added, which can reduce unnecessary traversal
_stat(config, channel, sheets);
// 6. Create token price sheet
emit Post(tokenAddress, msg.sender, length, ethNum, tokenAmountPerEth);
_createPriceSheet(sheets, accountIndex, uint32(ethNum), uint(config.pledgeNest), shares, tokenAmountPerEth);
}
/// @notice Post two price sheets for a token and its ntoken simultaneously
/// @dev Support dual-posts for TOKEN/NTOKEN, (ETH, TOKEN) + (ETH, NTOKEN)
/// @param tokenAddress The address of TOKEN contract
/// @param ethNum The numbers of ethers to post sheets
/// @param tokenAmountPerEth The price of TOKEN
/// @param ntokenAmountPerEth The price of NTOKEN
function post2(
address tokenAddress,
uint ethNum,
uint tokenAmountPerEth,
uint ntokenAmountPerEth
) override external payable {
Config memory config = _config;
// 1. Check arguments
require(ethNum > 0 && ethNum == uint(config.postEthUnit), "NM:!ethNum");
require(tokenAmountPerEth > 0 && ntokenAmountPerEth > 0, "NM:!price");
// 2. Check price channel
address ntokenAddress = _getNTokenAddress(tokenAddress);
require(ntokenAddress != address(0) && ntokenAddress != tokenAddress, "NM:!tokenAddress");
// 3. Load token channel and sheets
PriceChannel storage channel = _channels[tokenAddress];
PriceSheet[] storage sheets = channel.sheets;
// 4. Freeze assets
uint pledgeNest = uint(config.pledgeNest);
uint accountIndex = _addressIndex(msg.sender);
{
mapping(address=>UINT) storage balances = _accounts[accountIndex].balances;
_freeze(balances, tokenAddress, ethNum * tokenAmountPerEth);
_freeze2(balances, ntokenAddress, ethNum * ntokenAmountPerEth, pledgeNest * 2000 ether);
}
// 5. Deposit fee
// The revenue is deposited every 256 sheets, deducting the times of taking orders and the settled part
uint length = sheets.length;
uint shares = _collect(config, channel, ntokenAddress, length, msg.value - ethNum * 2 ether);
require(shares > 0 && shares < 256, "NM:!fee");
// Calculate the price
// According to the current mechanism, the newly added sheet cannot take effect, so the calculated price
// is placed before the sheet is added, which can reduce unnecessary traversal
_stat(config, channel, sheets);
// 6. Create token price sheet
emit Post(tokenAddress, msg.sender, length, ethNum, tokenAmountPerEth);
_createPriceSheet(sheets, accountIndex, uint32(ethNum), pledgeNest, shares, tokenAmountPerEth);
// 7. Load ntoken channel and sheets
channel = _channels[ntokenAddress];
sheets = channel.sheets;
// Calculate the price
// According to the current mechanism, the newly added sheet cannot take effect, so the calculated price
// is placed before the sheet is added, which can reduce unnecessary traversal
_stat(config, channel, sheets);
// 8. Create token price sheet
emit Post(ntokenAddress, msg.sender, sheets.length, ethNum, ntokenAmountPerEth);
_createPriceSheet(sheets, accountIndex, uint32(ethNum), pledgeNest, 0, ntokenAmountPerEth);
}
/// @notice Call the function to buy TOKEN/NTOKEN from a posted price sheet
/// @dev bite TOKEN(NTOKEN) by ETH, (+ethNumBal, -tokenNumBal)
/// @param tokenAddress The address of token(ntoken)
/// @param index The position of the sheet in priceSheetList[token]
/// @param takeNum The amount of biting (in the unit of ETH), realAmount = takeNum * newTokenAmountPerEth
/// @param newTokenAmountPerEth The new price of token (1 ETH : some TOKEN), here some means newTokenAmountPerEth
function takeToken(
address tokenAddress,
uint index,
uint takeNum,
uint newTokenAmountPerEth
) override external payable {
Config memory config = _config;
// 1. Check arguments
require(takeNum > 0 && takeNum % uint(config.postEthUnit) == 0, "NM:!takeNum");
require(newTokenAmountPerEth > 0, "NM:!price");
// 2. Load price sheet
PriceChannel storage channel = _channels[tokenAddress];
PriceSheet[] storage sheets = channel.sheets;
PriceSheet memory sheet = sheets[index];
// 3. Check state
require(uint(sheet.remainNum) >= takeNum, "NM:!remainNum");
require(uint(sheet.height) + uint(config.priceEffectSpan) >= block.number, "NM:!state");
// 4. Deposit fee
{
// The revenue is deposited every 256 sheets, deducting the times of taking orders and the settled part
address ntokenAddress = _getNTokenAddress(tokenAddress);
if (tokenAddress != ntokenAddress) {
_collect(config, channel, ntokenAddress, sheets.length, 0);
}
}
// 5. Calculate the number of eth, token and nest needed, and freeze them
uint needEthNum;
uint level = uint(sheet.level);
// When the level of the sheet is less than 4, both the nest and the scale of the offer are doubled
if (level < uint(config.maxBiteNestedLevel)) {
// Double scale sheet
needEthNum = takeNum << 1;
++level;
}
// When the level of the sheet reaches 4 or more, nest doubles, but the scale does not
else {
// Single scale sheet
needEthNum = takeNum;
// It is possible that the length of a single chain exceeds 255. When the length of a chain reaches 4
// or more, there is no logical dependence on the specific value of the contract, and the count will
// not increase after it is accumulated to 255
if (level < 255) ++level;
}
require(msg.value == (needEthNum + takeNum) * 1 ether, "NM:!value");
// Number of nest to be pledged
//uint needNest1k = ((takeNum << 1) / uint(config.postEthUnit)) * uint(config.pledgeNest);
// sheet.ethNumBal + sheet.tokenNumBal is always two times to sheet.ethNum
uint needNest1k = (takeNum << 2) * uint(sheet.nestNum1k) / (uint(sheet.ethNumBal) + uint(sheet.tokenNumBal));
// Freeze nest and token
uint accountIndex = _addressIndex(msg.sender);
{
mapping(address=>UINT) storage balances = _accounts[accountIndex].balances;
uint backTokenValue = decodeFloat(sheet.priceFloat) * takeNum;
if (needEthNum * newTokenAmountPerEth > backTokenValue) {
_freeze2(
balances,
tokenAddress,
needEthNum * newTokenAmountPerEth - backTokenValue,
needNest1k * 1000 ether
);
} else {
_freeze(balances, NEST_TOKEN_ADDRESS, needNest1k * 1000 ether);
_unfreeze(balances, tokenAddress, backTokenValue - needEthNum * newTokenAmountPerEth);
}
}
// 6. Update the biten sheet
sheet.remainNum = uint32(uint(sheet.remainNum) - takeNum);
sheet.ethNumBal = uint32(uint(sheet.ethNumBal) + takeNum);
sheet.tokenNumBal = uint32(uint(sheet.tokenNumBal) - takeNum);
sheets[index] = sheet;
// 7. Calculate the price
// According to the current mechanism, the newly added sheet cannot take effect, so the calculated price
// is placed before the sheet is added, which can reduce unnecessary traversal
_stat(config, channel, sheets);
// 8. Create price sheet
emit Post(tokenAddress, msg.sender, sheets.length, needEthNum, newTokenAmountPerEth);
_createPriceSheet(sheets, accountIndex, uint32(needEthNum), needNest1k, level << 8, newTokenAmountPerEth);
}
/// @notice Call the function to buy ETH from a posted price sheet
/// @dev bite ETH by TOKEN(NTOKEN), (-ethNumBal, +tokenNumBal)
/// @param tokenAddress The address of token(ntoken)
/// @param index The position of the sheet in priceSheetList[token]
/// @param takeNum The amount of biting (in the unit of ETH), realAmount = takeNum
/// @param newTokenAmountPerEth The new price of token (1 ETH : some TOKEN), here some means newTokenAmountPerEth
function takeEth(
address tokenAddress,
uint index,
uint takeNum,
uint newTokenAmountPerEth
) override external payable {
Config memory config = _config;
// 1. Check arguments
require(takeNum > 0 && takeNum % uint(config.postEthUnit) == 0, "NM:!takeNum");
require(newTokenAmountPerEth > 0, "NM:!price");
// 2. Load price sheet
PriceChannel storage channel = _channels[tokenAddress];
PriceSheet[] storage sheets = channel.sheets;
PriceSheet memory sheet = sheets[index];
// 3. Check state
require(uint(sheet.remainNum) >= takeNum, "NM:!remainNum");
require(uint(sheet.height) + uint(config.priceEffectSpan) >= block.number, "NM:!state");
// 4. Deposit fee
{
// The revenue is deposited every 256 sheets, deducting the times of taking orders and the settled part
address ntokenAddress = _getNTokenAddress(tokenAddress);
if (tokenAddress != ntokenAddress) {
_collect(config, channel, ntokenAddress, sheets.length, 0);
}
}
// 5. Calculate the number of eth, token and nest needed, and freeze them
uint needEthNum;
uint level = uint(sheet.level);
// When the level of the sheet is less than 4, both the nest and the scale of the offer are doubled
if (level < uint(config.maxBiteNestedLevel)) {
// Double scale sheet
needEthNum = takeNum << 1;
++level;
}
// When the level of the sheet reaches 4 or more, nest doubles, but the scale does not
else {
// Single scale sheet
needEthNum = takeNum;
// It is possible that the length of a single chain exceeds 255. When the length of a chain reaches 4
// or more, there is no logical dependence on the specific value of the contract, and the count will
// not increase after it is accumulated to 255
if (level < 255) ++level;
}
require(msg.value == (needEthNum - takeNum) * 1 ether, "NM:!value");
// Number of nest to be pledged
//uint needNest1k = ((takeNum << 1) / uint(config.postEthUnit)) * uint(config.pledgeNest);
// sheet.ethNumBal + sheet.tokenNumBal is always two times to sheet.ethNum
uint needNest1k = (takeNum << 2) * uint(sheet.nestNum1k) / (uint(sheet.ethNumBal) + uint(sheet.tokenNumBal));
// Freeze nest and token
uint accountIndex = _addressIndex(msg.sender);
_freeze2(
_accounts[accountIndex].balances,
tokenAddress,
needEthNum * newTokenAmountPerEth + decodeFloat(sheet.priceFloat) * takeNum,
needNest1k * 1000 ether
);
// 6. Update the biten sheet
sheet.remainNum = uint32(uint(sheet.remainNum) - takeNum);
sheet.ethNumBal = uint32(uint(sheet.ethNumBal) - takeNum);
sheet.tokenNumBal = uint32(uint(sheet.tokenNumBal) + takeNum);
sheets[index] = sheet;
// 7. Calculate the price
// According to the current mechanism, the newly added sheet cannot take effect, so the calculated price
// is placed before the sheet is added, which can reduce unnecessary traversal
_stat(config, channel, sheets);
// 8. Create price sheet
emit Post(tokenAddress, msg.sender, sheets.length, needEthNum, newTokenAmountPerEth);
_createPriceSheet(sheets, accountIndex, uint32(needEthNum), needNest1k, level << 8, newTokenAmountPerEth);
}
// Create price sheet
function _createPriceSheet(
PriceSheet[] storage sheets,
uint accountIndex,
uint32 ethNum,
uint nestNum1k,
uint level_shares,
uint tokenAmountPerEth
) private {
sheets.push(PriceSheet(
uint32(accountIndex), // uint32 miner;
uint32(block.number), // uint32 height;
ethNum, // uint32 remainNum;
ethNum, // uint32 ethNumBal;
ethNum, // uint32 tokenNumBal;
uint24(nestNum1k), // uint32 nestNum1k;
uint8(level_shares >> 8), // uint8 level;
uint8(level_shares & 0xFF),
encodeFloat(tokenAmountPerEth)
));
}
// Nest ore drawing attenuation interval. 2400000 blocks, about one year
uint constant NEST_REDUCTION_SPAN = 2400000;
// The decay limit of nest ore drawing becomes stable after exceeding this interval. 24 million blocks, about 10 years
uint constant NEST_REDUCTION_LIMIT = 24000000; //NEST_REDUCTION_SPAN * 10;
// Attenuation gradient array, each attenuation step value occupies 16 bits. The attenuation value is an integer
uint constant NEST_REDUCTION_STEPS = 0x280035004300530068008300A300CC010001400190;
// 0
// | (uint(400 / uint(1)) << (16 * 0))
// | (uint(400 * 8 / uint(10)) << (16 * 1))
// | (uint(400 * 8 * 8 / uint(10 * 10)) << (16 * 2))
// | (uint(400 * 8 * 8 * 8 / uint(10 * 10 * 10)) << (16 * 3))
// | (uint(400 * 8 * 8 * 8 * 8 / uint(10 * 10 * 10 * 10)) << (16 * 4))
// | (uint(400 * 8 * 8 * 8 * 8 * 8 / uint(10 * 10 * 10 * 10 * 10)) << (16 * 5))
// | (uint(400 * 8 * 8 * 8 * 8 * 8 * 8 / uint(10 * 10 * 10 * 10 * 10 * 10)) << (16 * 6))
// | (uint(400 * 8 * 8 * 8 * 8 * 8 * 8 * 8 / uint(10 * 10 * 10 * 10 * 10 * 10 * 10)) << (16 * 7))
// | (uint(400 * 8 * 8 * 8 * 8 * 8 * 8 * 8 * 8 / uint(10 * 10 * 10 * 10 * 10 * 10 * 10 * 10)) << (16 * 8))
// | (uint(400 * 8 * 8 * 8 * 8 * 8 * 8 * 8 * 8 * 8 / uint(10 * 10 * 10 * 10 * 10 * 10 * 10 * 10 * 10)) << (16 * 9))
// //| (uint(400 * 8 * 8 * 8 * 8 * 8 * 8 * 8 * 8 * 8 * 8 / uint(10 * 10 * 10 * 10 * 10 * 10 * 10 * 10 * 10 * 10)) << (16 * 10));
// | (uint(40) << (16 * 10));
// Calculation of attenuation gradient
function _redution(uint delta) private pure returns (uint) {
if (delta < NEST_REDUCTION_LIMIT) {
return (NEST_REDUCTION_STEPS >> ((delta / NEST_REDUCTION_SPAN) << 4)) & 0xFFFF;
}
return (NEST_REDUCTION_STEPS >> 160) & 0xFFFF;
}
/// @notice Close a price sheet of (ETH, USDx) | (ETH, NEST) | (ETH, TOKEN) | (ETH, NTOKEN)
/// @dev Here we allow an empty price sheet (still in VERIFICATION-PERIOD) to be closed
/// @param tokenAddress The address of TOKEN contract
/// @param index The index of the price sheet w.r.t. `token`
function close(address tokenAddress, uint index) override external {
Config memory config = _config;
PriceChannel storage channel = _channels[tokenAddress];
PriceSheet[] storage sheets = channel.sheets;
// Load the price channel
address ntokenAddress = _getNTokenAddress(tokenAddress);
// Call _close() method to close price sheet
(uint accountIndex, Tunple memory total) = _close(config, sheets, index, ntokenAddress);
if (accountIndex > 0) {
// Return eth
if (uint(total.ethNum) > 0) {
payable(indexAddress(accountIndex)).transfer(uint(total.ethNum) * 1 ether);
}
// Unfreeze assets
_unfreeze3(
_accounts[accountIndex].balances,
tokenAddress,
total.tokenValue,
ntokenAddress,
uint(total.ntokenValue),
uint(total.nestValue)
);
}
// Calculate the price
_stat(config, channel, sheets);
}
/// @notice Close a batch of price sheets passed VERIFICATION-PHASE
/// @dev Empty sheets but in VERIFICATION-PHASE aren't allowed
/// @param tokenAddress The address of TOKEN contract
/// @param indices A list of indices of sheets w.r.t. `token`
function closeList(address tokenAddress, uint[] memory indices) override external {
// Call _closeList() method to close price sheets
(
uint accountIndex,
Tunple memory total,
address ntokenAddress
) = _closeList(_config, _channels[tokenAddress], tokenAddress, indices);
// Return eth
payable(indexAddress(accountIndex)).transfer(uint(total.ethNum) * 1 ether);
// Unfreeze assets
_unfreeze3(
_accounts[accountIndex].balances,
tokenAddress,
uint(total.tokenValue),
ntokenAddress,
uint(total.ntokenValue),
uint(total.nestValue)
);
}
/// @notice Close two batch of price sheets passed VERIFICATION-PHASE
/// @dev Empty sheets but in VERIFICATION-PHASE aren't allowed
/// @param tokenAddress The address of TOKEN1 contract
/// @param tokenIndices A list of indices of sheets w.r.t. `token`
/// @param ntokenIndices A list of indices of sheets w.r.t. `ntoken`
function closeList2(
address tokenAddress,
uint[] memory tokenIndices,
uint[] memory ntokenIndices
) override external {
Config memory config = _config;
mapping(address=>PriceChannel) storage channels = _channels;
// Call _closeList() method to close price sheets
(
uint accountIndex1,
Tunple memory total1,
address ntokenAddress
) = _closeList(config, channels[tokenAddress], tokenAddress, tokenIndices);
(
uint accountIndex2,
Tunple memory total2,
//address ntokenAddress2
) = _closeList(config, channels[ntokenAddress], ntokenAddress, ntokenIndices);
require(accountIndex1 == accountIndex2, "NM:!miner");
//require(ntokenAddress1 == tokenAddress2, "NM:!tokenAddress");
require(uint(total2.ntokenValue) == 0, "NM!ntokenValue");
// Return eth
payable(indexAddress(accountIndex1)).transfer((uint(total1.ethNum) + uint(total2.ethNum)) * 1 ether);
// Unfreeze assets
_unfreeze3(
_accounts[accountIndex1].balances,
tokenAddress,
uint(total1.tokenValue),
ntokenAddress,
uint(total1.ntokenValue) + uint(total2.tokenValue)/* + uint(total2.ntokenValue) */,
uint(total1.nestValue) + uint(total2.nestValue)
);
}
// Calculation number of blocks which mined
function _calcMinedBlocks(
PriceSheet[] storage sheets,
uint index,
PriceSheet memory sheet
) private view returns (uint minedBlocks, uint totalShares) {
uint length = sheets.length;
uint height = uint(sheet.height);
totalShares = uint(sheet.shares);
// Backward looking for sheets in the same block
for (uint i = index; ++i < length && uint(sheets[i].height) == height;) {
// Multiple sheets in the same block is a small probability event at present, so it can be ignored
// to read more than once, if there are always multiple sheets in the same block, it means that the
// sheets are very intensive, and the gas consumed here does not have a great impact
totalShares += uint(sheets[i].shares);
}
//i = index;
// Find sheets in the same block forward
uint prev = height;
while (index > 0 && uint(prev = sheets[--index].height) == height) {
// Multiple sheets in the same block is a small probability event at present, so it can be ignored
// to read more than once, if there are always multiple sheets in the same block, it means that the
// sheets are very intensive, and the gas consumed here does not have a great impact
totalShares += uint(sheets[index].shares);
}
if (index > 0 || height > prev) {
minedBlocks = height - prev;
} else {
minedBlocks = 10;
}
}
// This structure is for the _close() method to return multiple values
struct Tunple {
uint tokenValue;
uint64 ethNum;
uint96 nestValue;
uint96 ntokenValue;
}
// Close price sheet
function _close(
Config memory config,
PriceSheet[] storage sheets,
uint index,
address ntokenAddress
) private returns (uint accountIndex, Tunple memory value) {
PriceSheet memory sheet = sheets[index];
uint height = uint(sheet.height);
// Check the status of the price sheet to see if it has reached the effective block interval or has been finished
if ((accountIndex = uint(sheet.miner)) > 0 && (height + uint(config.priceEffectSpan) < block.number)) {
// TMP: tmp is a polysemous name, here means sheet.shares
uint tmp = uint(sheet.shares);
// Mining logic
// The price sheet which shares is zero dosen't mining
if (tmp > 0) {
// Currently, mined represents the number of blocks has mined
(uint mined, uint totalShares) = _calcMinedBlocks(sheets, index, sheet);
// nest mining
if (ntokenAddress == NEST_TOKEN_ADDRESS) {
// Since then, mined represents the amount of mining
// mined = (
// mined
// * uint(sheet.shares)
// * _redution(height - NEST_GENESIS_BLOCK)
// * 1 ether
// * uint(config.minerNestReward)
// / 10000
// / totalShares
// );
// The original expression is shown above. In order to save gas,
// the part that can be calculated in advance is calculated first
mined = (
mined
* tmp
* _redution(height - NEST_GENESIS_BLOCK)
* uint(config.minerNestReward)
* 0.0001 ether
/ totalShares
);
}
// ntoken mining
else {
// The limit blocks can be mined
if (mined > uint(config.ntokenMinedBlockLimit)) {
mined = uint(config.ntokenMinedBlockLimit);
}
// Since then, mined represents the amount of mining
mined = (
mined
* tmp
* _redution(height - _getNTokenGenesisBlock(ntokenAddress))
* 0.01 ether
/ totalShares
);
// Put this logic into widhdran() method to reduce gas consumption
// ntoken bidders
address bidder = INToken(ntokenAddress).checkBidder();
// Legacy ntoken, need separate
if (bidder != address(this)) {
// Considering that multiple sheets in the same block are small probability events,
// we can send token to bidders in each closing operation
// 5% for bidder
// TMP: tmp is a polysemous name, here means mint ntoken amount for miner
tmp = mined * uint(config.minerNTokenReward) / 10000;
_unfreeze(
_accounts[_addressIndex(bidder)].balances,
ntokenAddress,
mined - tmp
);
// Miner take according proportion which set
mined = tmp;
}
}
value.ntokenValue = uint96(mined);
}
value.nestValue = uint96(uint(sheet.nestNum1k) * 1000 ether);
value.ethNum = uint64(sheet.ethNumBal);
value.tokenValue = decodeFloat(sheet.priceFloat) * uint(sheet.tokenNumBal);
// Set sheet.miner to 0, express the sheet is closed
sheet.miner = uint32(0);
sheet.ethNumBal = uint32(0);
sheet.tokenNumBal = uint32(0);
sheets[index] = sheet;
}
}
// Batch close sheets
function _closeList(
Config memory config,
PriceChannel storage channel,
address tokenAddress,
uint[] memory indices
) private returns (uint accountIndex, Tunple memory total, address ntokenAddress) {
ntokenAddress = _getNTokenAddress(tokenAddress);
PriceSheet[] storage sheets = channel.sheets;
accountIndex = 0;
// 1. Traverse sheets
for (uint i = indices.length; i > 0;) {
// Because too many variables need to be returned, too many variables will be defined, so the structure of tunple is defined
(uint minerIndex, Tunple memory value) = _close(config, sheets, indices[--i], ntokenAddress);
// Batch closing quotation can only close sheet of the same user
if (accountIndex == 0) {
// accountIndex == 0 means the first sheet, and the number of this sheet is taken
accountIndex = minerIndex;
} else {
// accountIndex != 0 means that it is a follow-up sheet, and the miner number must be consistent with the previous record
require(accountIndex == minerIndex, "NM:!miner");
}
total.ntokenValue += value.ntokenValue;
total.nestValue += value.nestValue;
total.ethNum += value.ethNum;
total.tokenValue += value.tokenValue;
}
_stat(config, channel, sheets);
}
// Calculate price, average price and volatility
function _stat(Config memory config, PriceChannel storage channel, PriceSheet[] storage sheets) private {
// Load token price information
PriceInfo memory p0 = channel.price;
// Length of sheets
uint length = sheets.length;
// The index of the sheet to be processed in the sheet array
uint index = uint(p0.index);
// The latest block number for which the price has been calculated
uint prev = uint(p0.height);
// It's not necessary to load the price information in p0
// Eth count variable used to calculate price
uint totalEthNum = 0;
// Token count variable for price calculation
uint totalTokenValue = 0;
// Block number of current sheet
uint height = 0;
// Traverse the sheets to find the effective price
uint effectBlock = block.number - uint(config.priceEffectSpan);
PriceSheet memory sheet;
for (; ; ++index) {
// Gas attack analysis, each post transaction, calculated according to post, needs to write
// at least one sheet and freeze two kinds of assets, which needs to consume at least 30000 gas,
// In addition to the basic cost of the transaction, at least 50000 gas is required.
// In addition, there are other reading and calculation operations. The gas consumed by each
// transaction is impossible less than 70000 gas, The attacker can accumulate up to 20 blocks
// of sheets to be generated. To ensure that the calculation can be completed in one block,
// it is necessary to ensure that the consumption of each price does not exceed 70000 / 20 = 3500 gas,
// According to the current logic, each calculation of a price needs to read a storage unit (800)
// and calculate the consumption, which can not reach the dangerous value of 3500, so the gas attack
// is not considered
// Traverse the sheets that has reached the effective interval from the current position
bool flag = index >= length || (height = uint((sheet = sheets[index]).height)) >= effectBlock;
// Not the same block (or flag is false), calculate the price and update it
if (flag || prev != height) {
// totalEthNum > 0 Can calculate the price
if (totalEthNum > 0) {
// Calculate average price and Volatility
// Calculation method of volatility of follow-up price
uint tmp = decodeFloat(p0.priceFloat);
// New price
uint price = totalTokenValue / totalEthNum;
// Update price
p0.remainNum = uint32(totalEthNum);
p0.priceFloat = encodeFloat(price);
// Clear cumulative values
totalEthNum = 0;
totalTokenValue = 0;
if (tmp > 0) {
// Calculate average price
// avgPrice[i + 1] = avgPrice[i] * 95% + price[i] * 5%
p0.avgFloat = encodeFloat((decodeFloat(p0.avgFloat) * 19 + price) / 20);
// When the accuracy of the token is very high or the value of the token relative to
// eth is very low, the price may be very large, and there may be overflow problem,
// it is not considered for the moment
tmp = (price << 48) / tmp;
if (tmp > 0x1000000000000) {
tmp = tmp - 0x1000000000000;
} else {
tmp = 0x1000000000000 - tmp;
}
// earn = price[i] / price[i - 1] - 1;
// seconds = time[i] - time[i - 1];
// sigmaSQ[i + 1] = sigmaSQ[i] * 95% + (earn ^ 2 / seconds) * 5%
tmp = (
uint(p0.sigmaSQ) * 19 +
// It is inevitable that prev greatter than p0.height
((tmp * tmp / ETHEREUM_BLOCK_TIMESPAN / (prev - uint(p0.height))) >> 48)
) / 20;
// The current implementation assumes that the volatility cannot exceed 1, and
// corresponding to this, when the calculated value exceeds 1, expressed as 0xFFFFFFFFFFFF
if (tmp > 0xFFFFFFFFFFFF) {
tmp = 0xFFFFFFFFFFFF;
}
p0.sigmaSQ = uint48(tmp);
}
// The calculation methods of average price and volatility are different for first price
else {
// The average price is equal to the price
//p0.avgTokenAmount = uint64(price);
p0.avgFloat = p0.priceFloat;
// The volatility is 0
p0.sigmaSQ = uint48(0);
}
// Update price block number
p0.height = uint32(prev);
}
// Move to new block number
prev = height;
}
if (flag) {
break;
}
// Cumulative price information
totalEthNum += uint(sheet.remainNum);
totalTokenValue += decodeFloat(sheet.priceFloat) * uint(sheet.remainNum);
}
// Update price infomation
if (index > uint(p0.index)) {
p0.index = uint32(index);
channel.price = p0;
}
}
/// @dev The function updates the statistics of price sheets
/// It calculates from priceInfo to the newest that is effective.
function stat(address tokenAddress) override external {
PriceChannel storage channel = _channels[tokenAddress];
_stat(_config, channel, channel.sheets);
}
// Collect and deposit the commission into NestLedger
function _collect(
Config memory config,
PriceChannel storage channel,
address ntokenAddress,
uint length,
uint currentFee
) private returns (uint) {
// Commission is charged for every post(post2), the commission should be deposited to NestLedger,
// for saving gas, according to sheets.length, every increase of 256 will deposit once, The calculation formula is:
//
// totalFee = fee * increment
//
// In consideration of takeToken, takeEth, change postFeeUnit or miner pay more fee, the formula will be invalid,
// at this point, it is need to settle immediately, the details of triggering settlement logic are as follows
//
// 1. When there is a bite transaction(currentFee is 0), the counter of no fee sheets will be increase 1
// 2. If the Commission of this time is inconsistent with that of last time, deposit immediately
// 3. When the increment of sheets.length is 256, deposit immediately
// 4. Everyone can trigger immediate settlement by manually calling the settle() method
//
// In order to realize the logic above, the following values are defined
//
// 1. PriceChannel.feeInfo
// Low 128-bits represent last fee per post
// High 128-bits represent the current counter of no fee sheets (including settled)
//
// 2. COLLECT_REWARD_MASK
// The mask of batch deposit trigger, while COLLECT_REWARD_MASK & sheets.length == COLLECT_REWARD_MASK, it will trigger deposit,
// COLLECT_REWARD_MASK is set to 0xF for testing (means every 16 sheets will deposit once),
// and it will be set to 0xFF for mainnet (means every 256 sheets will deposit once)
uint feeUnit = uint(config.postFeeUnit) * DIMI_ETHER;
require(currentFee % feeUnit == 0, "NM:!fee");
uint feeInfo = channel.feeInfo;
uint oldFee = feeInfo & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
// length == 255 means is time to save reward
// currentFee != oldFee means the fee is changed, need to settle
if (length & COLLECT_REWARD_MASK == COLLECT_REWARD_MASK || (currentFee != oldFee && currentFee > 0)) {
// Save reward
INestLedger(_nestLedgerAddress).carveETHReward {
value: currentFee + oldFee * ((length & COLLECT_REWARD_MASK) - (feeInfo >> 128))
} (ntokenAddress);
// Update fee information
channel.feeInfo = currentFee | (((length + 1) & COLLECT_REWARD_MASK) << 128);
}
// currentFee is 0, increase no fee counter
else if (currentFee == 0) {
// channel.feeInfo = feeInfo + (1 << 128);
channel.feeInfo = feeInfo + 0x100000000000000000000000000000000;
}
// Calculate share count
return currentFee / feeUnit;
}
/// @dev Settlement Commission
/// @param tokenAddress The token address
function settle(address tokenAddress) override external {
address ntokenAddress = _getNTokenAddress(tokenAddress);
// ntoken is no reward
if (tokenAddress != ntokenAddress) {
PriceChannel storage channel = _channels[tokenAddress];
uint length = channel.sheets.length & COLLECT_REWARD_MASK;
uint feeInfo = channel.feeInfo;
// Save reward
INestLedger(_nestLedgerAddress).carveETHReward {
value: (feeInfo & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) * (length - (feeInfo >> 128))
} (ntokenAddress);
// Manual settlement does not need to update Commission variables
channel.feeInfo = (feeInfo & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) | (length << 128);
}
}
// Convert PriceSheet to PriceSheetView
function _toPriceSheetView(PriceSheet memory sheet, uint index) private view returns (PriceSheetView memory) {
return PriceSheetView(
// Index number
uint32(index),
// Miner address
indexAddress(sheet.miner),
// The block number of this price sheet packaged
sheet.height,
// The remain number of this price sheet
sheet.remainNum,
// The eth number which miner will got
sheet.ethNumBal,
// The eth number which equivalent to token's value which miner will got
sheet.tokenNumBal,
// The pledged number of nest in this sheet. (Unit: 1000nest)
sheet.nestNum1k,
// The level of this sheet. 0 expresses initial price sheet, a value greater than 0 expresses bite price sheet
sheet.level,
// Post fee shares
sheet.shares,
// Price
uint152(decodeFloat(sheet.priceFloat))
);
}
/// @dev List sheets by page
/// @param tokenAddress Destination token address
/// @param offset Skip previous (offset) records
/// @param count Return (count) records
/// @param order Order. 0 reverse order, non-0 positive order
/// @return List of price sheets
function list(
address tokenAddress,
uint offset,
uint count,
uint order
) override external view returns (PriceSheetView[] memory) {
PriceSheet[] storage sheets = _channels[tokenAddress].sheets;
PriceSheetView[] memory result = new PriceSheetView[](count);
uint length = sheets.length;
uint i = 0;
// Reverse order
if (order == 0) {
uint index = length - offset;
uint end = index > count ? index - count : 0;
while (index > end) {
--index;
result[i++] = _toPriceSheetView(sheets[index], index);
}
}
// Positive order
else {
uint index = offset;
uint end = index + count;
if (end > length) {
end = length;
}
while (index < end) {
result[i++] = _toPriceSheetView(sheets[index], index);
++index;
}
}
return result;
}
/// @dev Estimated mining amount
/// @param tokenAddress Destination token address
/// @return Estimated mining amount
function estimate(address tokenAddress) override external view returns (uint) {
address ntokenAddress = INTokenController(_nTokenControllerAddress).getNTokenAddress(tokenAddress);
if (tokenAddress == ntokenAddress) {
return 0;
}
PriceSheet[] storage sheets = _channels[tokenAddress].sheets;
uint index = sheets.length;
while (index > 0) {
PriceSheet memory sheet = sheets[--index];
if (uint(sheet.shares) > 0) {
// Standard mining amount
uint standard = (block.number - uint(sheet.height)) * 1 ether;
// Genesis block number of ntoken
uint genesisBlock = NEST_GENESIS_BLOCK;
// Not nest, the calculation methods of standard mining amount and genesis block number are different
if (ntokenAddress != NEST_TOKEN_ADDRESS) {
// The standard mining amount of ntoken is 1/100 of nest
standard /= 100;
// Genesis block number of ntoken is obtained separately
(genesisBlock,) = INToken(ntokenAddress).checkBlockInfo();
}
return standard * _redution(block.number - genesisBlock);
}
}
return 0;
}
/// @dev Query the quantity of the target quotation
/// @param tokenAddress Token address. The token can't mine. Please make sure you don't use the token address when calling
/// @param index The index of the sheet
/// @return minedBlocks Mined block period from previous block
/// @return totalShares Total shares of sheets in the block
function getMinedBlocks(
address tokenAddress,
uint index
) override external view returns (uint minedBlocks, uint totalShares) {
PriceSheet[] storage sheets = _channels[tokenAddress].sheets;
PriceSheet memory sheet = sheets[index];
// The bite sheet or ntoken sheet dosen't mining
if (uint(sheet.shares) == 0) {
return (0, 0);
}
return _calcMinedBlocks(sheets, index, sheet);
}
/* ========== Accounts ========== */
/// @dev Withdraw assets
/// @param tokenAddress Destination token address
/// @param value The value to withdraw
function withdraw(address tokenAddress, uint value) override external {
// The user's locked nest and the mining pool's nest are stored together. When the nest is mined over,
// the problem of taking the locked nest as the ore drawing will appear
// As it will take a long time for nest to finish mining, this problem will not be considered for the time being
UINT storage balance = _accounts[_accountMapping[msg.sender]].balances[tokenAddress];
//uint balanceValue = balance.value;
//require(balanceValue >= value, "NM:!balance");
balance.value -= value;
// ntoken mining
uint ntokenBalance = INToken(tokenAddress).balanceOf(address(this));
if (ntokenBalance < value) {
// mining
INToken(tokenAddress).increaseTotal(value - ntokenBalance);
}
TransferHelper.safeTransfer(tokenAddress, msg.sender, value);
}
/// @dev View the number of assets specified by the user
/// @param tokenAddress Destination token address
/// @param addr Destination address
/// @return Number of assets
function balanceOf(address tokenAddress, address addr) override external view returns (uint) {
return _accounts[_accountMapping[addr]].balances[tokenAddress].value;
}
/// @dev Gets the index number of the specified address. If it does not exist, register
/// @param addr Destination address
/// @return The index number of the specified address
function _addressIndex(address addr) private returns (uint) {
uint index = _accountMapping[addr];
if (index == 0) {
// If it exceeds the maximum number that 32 bits can store, you can't continue to register a new account.
// If you need to support a new account, you need to update the contract
require((_accountMapping[addr] = index = _accounts.length) < 0x100000000, "NM:!accounts");
_accounts.push().addr = addr;
}
return index;
}
/// @dev Gets the address corresponding to the given index number
/// @param index The index number of the specified address
/// @return The address corresponding to the given index number
function indexAddress(uint index) override public view returns (address) {
return _accounts[index].addr;
}
/// @dev Gets the registration index number of the specified address
/// @param addr Destination address
/// @return 0 means nonexistent, non-0 means index number
function getAccountIndex(address addr) override external view returns (uint) {
return _accountMapping[addr];
}
/// @dev Get the length of registered account array
/// @return The length of registered account array
function getAccountCount() override external view returns (uint) {
return _accounts.length;
}
/* ========== Asset management ========== */
/// @dev Freeze token
/// @param balances Balances ledger
/// @param tokenAddress Destination token address
/// @param value token amount
function _freeze(mapping(address=>UINT) storage balances, address tokenAddress, uint value) private {
UINT storage balance = balances[tokenAddress];
uint balanceValue = balance.value;
if (balanceValue < value) {
balance.value = 0;
TransferHelper.safeTransferFrom(tokenAddress, msg.sender, address(this), value - balanceValue);
} else {
balance.value = balanceValue - value;
}
}
/// @dev Unfreeze token
/// @param balances Balances ledgerBalances ledger
/// @param tokenAddress Destination token address
/// @param value token amount
function _unfreeze(mapping(address=>UINT) storage balances, address tokenAddress, uint value) private {
UINT storage balance = balances[tokenAddress];
balance.value += value;
}
/// @dev freeze token and nest
/// @param balances Balances ledger
/// @param tokenAddress Destination token address
/// @param tokenValue token amount
/// @param nestValue nest amount
function _freeze2(
mapping(address=>UINT) storage balances,
address tokenAddress,
uint tokenValue,
uint nestValue
) private {
UINT storage balance;
uint balanceValue;
// If tokenAddress is NEST_TOKEN_ADDRESS, add it to nestValue
if (NEST_TOKEN_ADDRESS == tokenAddress) {
nestValue += tokenValue;
}
// tokenAddress is not NEST_TOKEN_ADDRESS, unfreeze it
else {
balance = balances[tokenAddress];
balanceValue = balance.value;
if (balanceValue < tokenValue) {
balance.value = 0;
TransferHelper.safeTransferFrom(tokenAddress, msg.sender, address(this), tokenValue - balanceValue);
} else {
balance.value = balanceValue - tokenValue;
}
}
// Unfreeze nest
balance = balances[NEST_TOKEN_ADDRESS];
balanceValue = balance.value;
if (balanceValue < nestValue) {
balance.value = 0;
TransferHelper.safeTransferFrom(NEST_TOKEN_ADDRESS, msg.sender, address(this), nestValue - balanceValue);
} else {
balance.value = balanceValue - nestValue;
}
}
/// @dev Unfreeze token, ntoken and nest
/// @param balances Balances ledger
/// @param tokenAddress Destination token address
/// @param tokenValue token amount
/// @param ntokenAddress Destination ntoken address
/// @param ntokenValue ntoken amount
/// @param nestValue nest amount
function _unfreeze3(
mapping(address=>UINT) storage balances,
address tokenAddress,
uint tokenValue,
address ntokenAddress,
uint ntokenValue,
uint nestValue
) private {
UINT storage balance;
// If tokenAddress is ntokenAddress, add it to ntokenValue
if (ntokenAddress == tokenAddress) {
ntokenValue += tokenValue;
}
// tokenAddress is not ntokenAddress, unfreeze it
else {
balance = balances[tokenAddress];
balance.value += tokenValue;
}
// If ntokenAddress is NEST_TOKEN_ADDRESS, add it to nestValue
if (NEST_TOKEN_ADDRESS == ntokenAddress) {
nestValue += ntokenValue;
}
// ntokenAddress is NEST_TOKEN_ADDRESS, unfreeze it
else {
balance = balances[ntokenAddress];
balance.value += ntokenValue;
}
// Unfreeze nest
balance = balances[NEST_TOKEN_ADDRESS];
balance.value += nestValue;
}
/* ========== INestQuery ========== */
// Check msg.sender
function _check() private view {
require(msg.sender == _nestPriceFacadeAddress || msg.sender == tx.origin);
}
/// @dev Get the latest trigger price
/// @param tokenAddress Destination token address
/// @return blockNumber The block number of price
/// @return price The token price. (1eth equivalent to (price) token)
function triggeredPrice(address tokenAddress) override public view returns (uint blockNumber, uint price) {
_check();
PriceInfo memory priceInfo = _channels[tokenAddress].price;
if (uint(priceInfo.remainNum) > 0) {
return (uint(priceInfo.height) + uint(_config.priceEffectSpan), decodeFloat(priceInfo.priceFloat));
}
return (0, 0);
}
/// @dev Get the full information of latest trigger price
/// @param tokenAddress Destination token address
/// @return blockNumber The block number of price
/// @return price The token price. (1eth equivalent to (price) token)
/// @return avgPrice Average price
/// @return sigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that
/// the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447,
/// it means that the volatility has exceeded the range that can be expressed
function triggeredPriceInfo(address tokenAddress) override public view returns (
uint blockNumber,
uint price,
uint avgPrice,
uint sigmaSQ
) {
_check();
PriceInfo memory priceInfo = _channels[tokenAddress].price;
if (uint(priceInfo.remainNum) > 0) {
return (
uint(priceInfo.height) + uint(_config.priceEffectSpan),
decodeFloat(priceInfo.priceFloat),
decodeFloat(priceInfo.avgFloat),
(uint(priceInfo.sigmaSQ) * 1 ether) >> 48
);
}
return (0, 0, 0, 0);
}
/// @dev Find the price at block number
/// @param tokenAddress Destination token address
/// @param height Destination block number
/// @return blockNumber The block number of price
/// @return price The token price. (1eth equivalent to (price) token)
function findPrice(
address tokenAddress,
uint height
) override external view returns (uint blockNumber, uint price) {
_check();
PriceSheet[] storage sheets = _channels[tokenAddress].sheets;
uint priceEffectSpan = uint(_config.priceEffectSpan);
uint length = sheets.length;
uint index = 0;
uint sheetHeight;
height -= priceEffectSpan;
{
// If there is no sheet in this channel, length is 0, length - 1 will overflow,
uint right = length - 1;
uint left = 0;
// Find the index use Binary Search
while (left < right) {
index = (left + right) >> 1;
sheetHeight = uint(sheets[index].height);
if (height > sheetHeight) {
left = ++index;
} else if (height < sheetHeight) {
// When index = 0, this statement will have an underflow exception, which usually
// indicates that the effective block height passed during the call is lower than
// the block height of the first quotation
right = --index;
} else {
break;
}
}
}
// Calculate price
uint totalEthNum = 0;
uint totalTokenValue = 0;
uint h = 0;
uint remainNum;
PriceSheet memory sheet;
// Find sheets forward
for (uint i = index; i < length;) {
sheet = sheets[i++];
sheetHeight = uint(sheet.height);
if (height < sheetHeight) {
break;
}
remainNum = uint(sheet.remainNum);
if (remainNum > 0) {
if (h == 0) {
h = sheetHeight;
} else if (h != sheetHeight) {
break;
}
totalEthNum += remainNum;
totalTokenValue += decodeFloat(sheet.priceFloat) * remainNum;
}
}
// Find sheets backward
while (index > 0) {
sheet = sheets[--index];
remainNum = uint(sheet.remainNum);
if (remainNum > 0) {
sheetHeight = uint(sheet.height);
if (h == 0) {
h = sheetHeight;
} else if (h != sheetHeight) {
break;
}
totalEthNum += remainNum;
totalTokenValue += decodeFloat(sheet.priceFloat) * remainNum;
}
}
if (totalEthNum > 0) {
return (h + priceEffectSpan, totalTokenValue / totalEthNum);
}
return (0, 0);
}
/// @dev Get the latest effective price
/// @param tokenAddress Destination token address
/// @return blockNumber The block number of price
/// @return price The token price. (1eth equivalent to (price) token)
function latestPrice(address tokenAddress) override public view returns (uint blockNumber, uint price) {
_check();
PriceSheet[] storage sheets = _channels[tokenAddress].sheets;
PriceSheet memory sheet;
uint priceEffectSpan = uint(_config.priceEffectSpan);
uint h = block.number - priceEffectSpan;
uint index = sheets.length;
uint totalEthNum = 0;
uint totalTokenValue = 0;
uint height = 0;
for (; ; ) {
bool flag = index == 0;
if (flag || height != uint((sheet = sheets[--index]).height)) {
if (totalEthNum > 0 && height <= h) {
return (height + priceEffectSpan, totalTokenValue / totalEthNum);
}
if (flag) {
break;
}
totalEthNum = 0;
totalTokenValue = 0;
height = uint(sheet.height);
}
uint remainNum = uint(sheet.remainNum);
totalEthNum += remainNum;
totalTokenValue += decodeFloat(sheet.priceFloat) * remainNum;
}
return (0, 0);
}
/// @dev Get the last (num) effective price
/// @param tokenAddress Destination token address
/// @param count The number of prices that want to return
/// @return An array which length is num * 2, each two element expresses one price like blockNumber|price
function lastPriceList(address tokenAddress, uint count) override external view returns (uint[] memory) {
_check();
PriceSheet[] storage sheets = _channels[tokenAddress].sheets;
PriceSheet memory sheet;
uint[] memory array = new uint[](count <<= 1);
uint priceEffectSpan = uint(_config.priceEffectSpan);
uint h = block.number - priceEffectSpan;
uint index = sheets.length;
uint totalEthNum = 0;
uint totalTokenValue = 0;
uint height = 0;
for (uint i = 0; i < count;) {
bool flag = index == 0;
if (flag || height != uint((sheet = sheets[--index]).height)) {
if (totalEthNum > 0 && height <= h) {
array[i++] = height + priceEffectSpan;
array[i++] = totalTokenValue / totalEthNum;
}
if (flag) {
break;
}
totalEthNum = 0;
totalTokenValue = 0;
height = uint(sheet.height);
}
uint remainNum = uint(sheet.remainNum);
totalEthNum += remainNum;
totalTokenValue += decodeFloat(sheet.priceFloat) * remainNum;
}
return array;
}
/// @dev Returns the results of latestPrice() and triggeredPriceInfo()
/// @param tokenAddress Destination token address
/// @return latestPriceBlockNumber The block number of latest price
/// @return latestPriceValue The token latest price. (1eth equivalent to (price) token)
/// @return triggeredPriceBlockNumber The block number of triggered price
/// @return triggeredPriceValue The token triggered price. (1eth equivalent to (price) token)
/// @return triggeredAvgPrice Average price
/// @return triggeredSigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that
/// the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447,
/// it means that the volatility has exceeded the range that can be expressed
function latestPriceAndTriggeredPriceInfo(address tokenAddress) override external view
returns (
uint latestPriceBlockNumber,
uint latestPriceValue,
uint triggeredPriceBlockNumber,
uint triggeredPriceValue,
uint triggeredAvgPrice,
uint triggeredSigmaSQ
) {
(latestPriceBlockNumber, latestPriceValue) = latestPrice(tokenAddress);
(
triggeredPriceBlockNumber,
triggeredPriceValue,
triggeredAvgPrice,
triggeredSigmaSQ
) = triggeredPriceInfo(tokenAddress);
}
/// @dev Get the latest trigger price. (token and ntoken)
/// @param tokenAddress Destination token address
/// @return blockNumber The block number of price
/// @return price The token price. (1eth equivalent to (price) token)
/// @return ntokenBlockNumber The block number of ntoken price
/// @return ntokenPrice The ntoken price. (1eth equivalent to (price) ntoken)
function triggeredPrice2(address tokenAddress) override external view returns (
uint blockNumber,
uint price,
uint ntokenBlockNumber,
uint ntokenPrice
) {
(blockNumber, price) = triggeredPrice(tokenAddress);
(ntokenBlockNumber, ntokenPrice) = triggeredPrice(_addressCache[tokenAddress]);
}
/// @dev Get the full information of latest trigger price. (token and ntoken)
/// @param tokenAddress Destination token address
/// @return blockNumber The block number of price
/// @return price The token price. (1eth equivalent to (price) token)
/// @return avgPrice Average price
/// @return sigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that
/// the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447,
/// it means that the volatility has exceeded the range that can be expressed
/// @return ntokenBlockNumber The block number of ntoken price
/// @return ntokenPrice The ntoken price. (1eth equivalent to (price) ntoken)
/// @return ntokenAvgPrice Average price of ntoken
/// @return ntokenSigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that
/// the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447,
/// it means that the volatility has exceeded the range that can be expressed
function triggeredPriceInfo2(address tokenAddress) override external view returns (
uint blockNumber,
uint price,
uint avgPrice,
uint sigmaSQ,
uint ntokenBlockNumber,
uint ntokenPrice,
uint ntokenAvgPrice,
uint ntokenSigmaSQ
) {
(blockNumber, price, avgPrice, sigmaSQ) = triggeredPriceInfo(tokenAddress);
(
ntokenBlockNumber,
ntokenPrice,
ntokenAvgPrice,
ntokenSigmaSQ
) = triggeredPriceInfo(_addressCache[tokenAddress]);
}
/// @dev Get the latest effective price. (token and ntoken)
/// @param tokenAddress Destination token address
/// @return blockNumber The block number of price
/// @return price The token price. (1eth equivalent to (price) token)
/// @return ntokenBlockNumber The block number of ntoken price
/// @return ntokenPrice The ntoken price. (1eth equivalent to (price) ntoken)
function latestPrice2(address tokenAddress) override external view returns (
uint blockNumber,
uint price,
uint ntokenBlockNumber,
uint ntokenPrice
) {
(blockNumber, price) = latestPrice(tokenAddress);
(ntokenBlockNumber, ntokenPrice) = latestPrice(_addressCache[tokenAddress]);
}
/* ========== Tools and methods ========== */
/// @dev Encode the uint value as a floating-point representation in the form of fraction * 16 ^ exponent
/// @param value Destination uint value
/// @return float format
function encodeFloat(uint value) private pure returns (uint56) {
uint exponent = 0;
while (value > 0x3FFFFFFFFFFFF) {
value >>= 4;
++exponent;
}
return uint56((value << 6) | exponent);
}
/// @dev Decode the floating-point representation of fraction * 16 ^ exponent to uint
/// @param floatValue fraction value
/// @return decode format
function decodeFloat(uint56 floatValue) private pure returns (uint) {
return (uint(floatValue) >> 6) << ((uint(floatValue) & 0x3F) << 2);
}
} | Get the last (num) effective price tokenAddress Destination token address count The number of prices that want to return return An array which length is num 2, each two element expresses one price like blockNumber|price | function lastPriceList(address tokenAddress, uint count) override external view returns (uint[] memory) {
_check();
PriceSheet[] storage sheets = _channels[tokenAddress].sheets;
PriceSheet memory sheet;
uint[] memory array = new uint[](count <<= 1);
uint priceEffectSpan = uint(_config.priceEffectSpan);
uint h = block.number - priceEffectSpan;
uint index = sheets.length;
uint totalEthNum = 0;
uint totalTokenValue = 0;
uint height = 0;
for (uint i = 0; i < count;) {
bool flag = index == 0;
if (flag || height != uint((sheet = sheets[--index]).height)) {
if (totalEthNum > 0 && height <= h) {
array[i++] = height + priceEffectSpan;
array[i++] = totalTokenValue / totalEthNum;
}
if (flag) {
break;
}
totalEthNum = 0;
totalTokenValue = 0;
height = uint(sheet.height);
}
uint remainNum = uint(sheet.remainNum);
totalEthNum += remainNum;
totalTokenValue += decodeFloat(sheet.priceFloat) * remainNum;
}
return array;
}
| 10,045,510 |
pragma ton-solidity >= 0.52.0;
pragma AbiHeader time;
pragma AbiHeader pubkey;
pragma AbiHeader expire;
//================================================================================
//
import "../interfaces/ILiquidFTRoot.sol";
import "../interfaces/IOwnable.sol";
import "../contracts/LiquidFTWallet.sol";
//================================================================================
//
abstract contract LiquidFTRootBase is IOwnable, ILiquidFTRoot
{
//========================================
// Error codes
uint constant ERROR_WALLET_ADDRESS_INVALID = 301;
//========================================
// Variables
TvmCell static _walletCode; //
string static _name; //
string static _symbol; //
uint8 static _decimals; //
uint128 _totalSupply; //
string _metadata; //
//========================================
// Modifiers
//========================================
// Getters
function getWalletCode() external view override returns (TvmCell) { return (_walletCode); }
function callWalletCode() external view responsible override reserve returns (TvmCell) { return {value: 0, flag: 128}(_walletCode); }
function getWalletAddress(address ownerAddress) external view override returns (address) { (address addr, ) = _getWalletInit(ownerAddress); return (addr); }
function callWalletAddress(address ownerAddress) external view responsible override reserve returns (address) { (address addr, ) = _getWalletInit(ownerAddress); return {value: 0, flag: 128}(addr); }
function getInfo(bool includeMetadata) external view override returns (string name,
string symbol,
uint8 decimals,
uint128 totalSupply,
string metadata)
{
return (_name,
_symbol,
_decimals,
_totalSupply,
includeMetadata ? _metadata : metadata);
}
function callInfo(bool includeMetadata) external view responsible override reserve returns (string name,
string symbol,
uint8 decimals,
uint128 totalSupply,
string metadata)
{
return {value: 0, flag: 128}(_name,
_symbol,
_decimals,
_totalSupply,
includeMetadata ? _metadata : metadata);
}
//========================================
//
function setMetadata(string metadata) external onlyOwner reserve returnChange
{
_metadata = metadata;
}
//========================================
//
function _getWalletInit(address ownerAddress) private inline view returns (address, TvmCell)
{
TvmCell stateInit = tvm.buildStateInit({
contr: LiquidFTWallet,
varInit: {
_rootAddress: address(this),
_ownerAddress: ownerAddress
},
code: _walletCode
});
return (address(tvm.hash(stateInit)), stateInit);
}
//========================================
//
function _createWallet(address ownerAddress, address notifyOnReceiveAddress, uint128 tokensAmount, uint128 value, uint16 flag, bool emitCreateWallet) internal returns (address)
{
if(tokensAmount > 0)
{
require(senderIsOwner(), ERROR_MESSAGE_SENDER_IS_NOT_MY_OWNER);
_totalSupply += tokensAmount;
}
(address walletAddress, TvmCell stateInit) = _getWalletInit(ownerAddress);
if(emitCreateWallet)
{
// Event
emit walletCreated(ownerAddress, walletAddress);
}
new LiquidFTWallet{value: value, flag: flag, bounce: false, stateInit: stateInit, wid: address(this).wid}(addressZero, msg.sender, notifyOnReceiveAddress, tokensAmount);
return walletAddress;
}
//========================================
// No returnChange here because 0 (flag 128) TONs are sent to the new wallet
//
function createWallet(address ownerAddress, address notifyOnReceiveAddress, uint128 tokensAmount) external override reserve returns (address)
{
address walletAddress = _createWallet(ownerAddress, notifyOnReceiveAddress, tokensAmount, 0, 128, true);
return(walletAddress);
}
function callCreateWallet(address ownerAddress, address notifyOnReceiveAddress, uint128 tokensAmount) external responsible override reserve returns (address)
{
address walletAddress = _createWallet(ownerAddress, notifyOnReceiveAddress, tokensAmount, msg.value / 2, 0, true);
return{value: 0, flag: 128}(walletAddress);
}
//========================================
//
function burn(uint128 amount, address senderOwnerAddress, address initiatorAddress) external override reserve returnChangeTo(initiatorAddress)
{
(address walletAddress, ) = _getWalletInit(senderOwnerAddress);
require(walletAddress == msg.sender, ERROR_WALLET_ADDRESS_INVALID);
_totalSupply -= amount;
// Event
emit tokensBurned(amount, senderOwnerAddress);
}
//========================================
//
function mint(uint128 amount, address targetOwnerAddress, address notifyAddress, TvmCell body) external override onlyOwner reserve
{
address walletAddress = _createWallet(targetOwnerAddress, addressZero, 0, msg.value / 3, 0, false);
// Event
emit tokensMinted(amount, targetOwnerAddress, body);
if(notifyAddress != addressZero)
{
iFTNotify(notifyAddress).receiveNotification{value: msg.value / 3, flag: 0}(amount, targetOwnerAddress, msg.sender, body);
}
// Mint adds balance to root total supply
_totalSupply += amount;
ILiquidFTWallet(walletAddress).receiveTransfer{value: 0, flag: 128}(amount, addressZero, _ownerAddress, notifyAddress, false, body);
}
//========================================
//
onBounce(TvmSlice slice) external
{
uint32 functionId = slice.decode(uint32);
if (functionId == tvm.functionId(LiquidFTWallet.receiveTransfer))
{
uint128 amount = slice.decode(uint128);
_totalSupply -= amount;
// We know for sure that initiator in "mint" process is RTW owner;
_ownerAddress.transfer(0, true, 128);
}
}
}
//================================================================================
// | ======================================== | function setMetadata(string metadata) external onlyOwner reserve returnChange
{
_metadata = metadata;
}
| 14,086,925 |
pragma solidity ^0.4.25;
// ----------------------------------------------------------------------------
// Fxxx Land Rush Contract - Purchase land parcels with GZE and ETH
//
// Deployed to : {TBA}
//
// Enjoy.
//
// (c) BokkyPooBah / Bok Consulting Pty Ltd for GazeCoin 2018. The MIT Licence.
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// Owned contract
// ----------------------------------------------------------------------------
contract Owned {
address public owner;
address public newOwner;
bool private initialised;
event OwnershipTransferred(address indexed _from, address indexed _to);
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function initOwned(address _owner) internal {
require(!initialised);
owner = _owner;
initialised = true;
}
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner);
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
function transferOwnershipImmediately(address _newOwner) public onlyOwner {
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
// ----------------------------------------------------------------------------
// Safe maths
// ----------------------------------------------------------------------------
library SafeMath {
function add(uint a, uint b) internal pure returns (uint c) {
c = a + b;
require(c >= a);
}
function sub(uint a, uint b) internal pure returns (uint c) {
require(b <= a);
c = a - b;
}
function mul(uint a, uint b) internal pure returns (uint c) {
c = a * b;
require(a == 0 || c / a == b);
}
function div(uint a, uint b) internal pure returns (uint c) {
require(b > 0);
c = a / b;
}
function max(uint a, uint b) internal pure returns (uint c) {
c = a >= b ? a : b;
}
function min(uint a, uint b) internal pure returns (uint c) {
c = a <= b ? a : b;
}
}
// ----------------------------------------------------------------------------
// BokkyPooBah's Token Teleportation Service Interface v1.10
//
// https://github.com/bokkypoobah/BokkyPooBahsTokenTeleportationServiceSmartContract
//
// Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018. The MIT Licence.
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ERC Token Standard #20 Interface
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// ----------------------------------------------------------------------------
contract ERC20Interface {
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
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);
}
// ----------------------------------------------------------------------------
// Contracts that can have tokens approved, and then a function executed
// ----------------------------------------------------------------------------
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 tokens, address token, bytes data) public;
}
// ----------------------------------------------------------------------------
// BokkyPooBah's Token Teleportation Service Interface v1.10
//
// Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018. The MIT Licence.
// ----------------------------------------------------------------------------
contract BTTSTokenInterface is ERC20Interface {
uint public constant bttsVersion = 110;
bytes public constant signingPrefix = "\x19Ethereum Signed Message:\n32";
bytes4 public constant signedTransferSig = "\x75\x32\xea\xac";
bytes4 public constant signedApproveSig = "\xe9\xaf\xa7\xa1";
bytes4 public constant signedTransferFromSig = "\x34\x4b\xcc\x7d";
bytes4 public constant signedApproveAndCallSig = "\xf1\x6f\x9b\x53";
event OwnershipTransferred(address indexed from, address indexed to);
event MinterUpdated(address from, address to);
event Mint(address indexed tokenOwner, uint tokens, bool lockAccount);
event MintingDisabled();
event TransfersEnabled();
event AccountUnlocked(address indexed tokenOwner);
function symbol() public view returns (string);
function name() public view returns (string);
function decimals() public view returns (uint8);
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success);
// ------------------------------------------------------------------------
// signed{X} functions
// ------------------------------------------------------------------------
function signedTransferHash(address tokenOwner, address to, uint tokens, uint fee, uint nonce) public view returns (bytes32 hash);
function signedTransferCheck(address tokenOwner, address to, uint tokens, uint fee, uint nonce, bytes sig, address feeAccount) public view returns (CheckResult result);
function signedTransfer(address tokenOwner, address to, uint tokens, uint fee, uint nonce, bytes sig, address feeAccount) public returns (bool success);
function signedApproveHash(address tokenOwner, address spender, uint tokens, uint fee, uint nonce) public view returns (bytes32 hash);
function signedApproveCheck(address tokenOwner, address spender, uint tokens, uint fee, uint nonce, bytes sig, address feeAccount) public view returns (CheckResult result);
function signedApprove(address tokenOwner, address spender, uint tokens, uint fee, uint nonce, bytes sig, address feeAccount) public returns (bool success);
function signedTransferFromHash(address spender, address from, address to, uint tokens, uint fee, uint nonce) public view returns (bytes32 hash);
function signedTransferFromCheck(address spender, address from, address to, uint tokens, uint fee, uint nonce, bytes sig, address feeAccount) public view returns (CheckResult result);
function signedTransferFrom(address spender, address from, address to, uint tokens, uint fee, uint nonce, bytes sig, address feeAccount) public returns (bool success);
function signedApproveAndCallHash(address tokenOwner, address spender, uint tokens, bytes _data, uint fee, uint nonce) public view returns (bytes32 hash);
function signedApproveAndCallCheck(address tokenOwner, address spender, uint tokens, bytes _data, uint fee, uint nonce, bytes sig, address feeAccount) public view returns (CheckResult result);
function signedApproveAndCall(address tokenOwner, address spender, uint tokens, bytes _data, uint fee, uint nonce, bytes sig, address feeAccount) public returns (bool success);
function mint(address tokenOwner, uint tokens, bool lockAccount) public returns (bool success);
function unlockAccount(address tokenOwner) public;
function disableMinting() public;
function enableTransfers() public;
// ------------------------------------------------------------------------
// signed{X}Check return status
// ------------------------------------------------------------------------
enum CheckResult {
Success, // 0 Success
NotTransferable, // 1 Tokens not transferable yet
AccountLocked, // 2 Account locked
SignerMismatch, // 3 Mismatch in signing account
InvalidNonce, // 4 Invalid nonce
InsufficientApprovedTokens, // 5 Insufficient approved tokens
InsufficientApprovedTokensForFees, // 6 Insufficient approved tokens for fees
InsufficientTokens, // 7 Insufficient tokens
InsufficientTokensForFees, // 8 Insufficient tokens for fees
OverflowError // 9 Overflow error
}
}
// ----------------------------------------------------------------------------
// PriceFeed Interface - _live is true if the rate is valid, false if invalid
// ----------------------------------------------------------------------------
contract PriceFeedInterface {
function getRate() public view returns (uint _rate, bool _live);
}
// ----------------------------------------------------------------------------
// Bonus List interface
// ----------------------------------------------------------------------------
contract BonusListInterface {
function isInBonusList(address account) public view returns (bool);
}
// ----------------------------------------------------------------------------
// FxxxLandRush Contract
// ----------------------------------------------------------------------------
contract FxxxLandRush is Owned, ApproveAndCallFallBack {
using SafeMath for uint;
uint private constant TENPOW18 = 10 ** 18;
BTTSTokenInterface public parcelToken;
BTTSTokenInterface public gzeToken;
PriceFeedInterface public ethUsdPriceFeed;
PriceFeedInterface public gzeEthPriceFeed;
BonusListInterface public bonusList;
address public wallet;
uint public startDate;
uint public endDate;
uint public maxParcels;
uint public parcelUsd; // USD per parcel, e.g., USD 1,500 * 10^18
uint public usdLockAccountThreshold; // e.g., USD 7,000 * 10^18
uint public gzeBonusOffList; // e.g., 20 = 20% bonus
uint public gzeBonusOnList; // e.g., 30 = 30% bonus
uint public parcelsSold;
uint public contributedGze;
uint public contributedEth;
bool public finalised;
event WalletUpdated(address indexed oldWallet, address indexed newWallet);
event StartDateUpdated(uint oldStartDate, uint newStartDate);
event EndDateUpdated(uint oldEndDate, uint newEndDate);
event MaxParcelsUpdated(uint oldMaxParcels, uint newMaxParcels);
event ParcelUsdUpdated(uint oldParcelUsd, uint newParcelUsd);
event UsdLockAccountThresholdUpdated(uint oldUsdLockAccountThreshold, uint newUsdLockAccountThreshold);
event GzeBonusOffListUpdated(uint oldGzeBonusOffList, uint newGzeBonusOffList);
event GzeBonusOnListUpdated(uint oldGzeBonusOnList, uint newGzeBonusOnList);
event Purchased(address indexed addr, uint parcels, uint gzeToTransfer, uint ethToTransfer, uint parcelsSold, uint contributedGze, uint contributedEth, bool lockAccount);
constructor(address _parcelToken, address _gzeToken, address _ethUsdPriceFeed, address _gzeEthPriceFeed, address _bonusList, address _wallet, uint _startDate, uint _endDate, uint _maxParcels, uint _parcelUsd, uint _usdLockAccountThreshold, uint _gzeBonusOffList, uint _gzeBonusOnList) public {
require(_parcelToken != address(0) && _gzeToken != address(0));
require(_ethUsdPriceFeed != address(0) && _gzeEthPriceFeed != address(0) && _bonusList != address(0));
require(_wallet != address(0));
require(_startDate >= now && _endDate > _startDate);
require(_maxParcels > 0 && _parcelUsd > 0);
initOwned(msg.sender);
parcelToken = BTTSTokenInterface(_parcelToken);
gzeToken = BTTSTokenInterface(_gzeToken);
ethUsdPriceFeed = PriceFeedInterface(_ethUsdPriceFeed);
gzeEthPriceFeed = PriceFeedInterface(_gzeEthPriceFeed);
bonusList = BonusListInterface(_bonusList);
wallet = _wallet;
startDate = _startDate;
endDate = _endDate;
maxParcels = _maxParcels;
parcelUsd = _parcelUsd;
usdLockAccountThreshold = _usdLockAccountThreshold;
gzeBonusOffList = _gzeBonusOffList;
gzeBonusOnList = _gzeBonusOnList;
}
function setWallet(address _wallet) public onlyOwner {
require(!finalised);
require(_wallet != address(0));
emit WalletUpdated(wallet, _wallet);
wallet = _wallet;
}
function setStartDate(uint _startDate) public onlyOwner {
require(!finalised);
require(_startDate >= now);
emit StartDateUpdated(startDate, _startDate);
startDate = _startDate;
}
function setEndDate(uint _endDate) public onlyOwner {
require(!finalised);
require(_endDate > startDate);
emit EndDateUpdated(endDate, _endDate);
endDate = _endDate;
}
function setMaxParcels(uint _maxParcels) public onlyOwner {
require(!finalised);
require(_maxParcels >= parcelsSold);
emit MaxParcelsUpdated(maxParcels, _maxParcels);
maxParcels = _maxParcels;
}
function setParcelUsd(uint _parcelUsd) public onlyOwner {
require(!finalised);
require(_parcelUsd > 0);
emit ParcelUsdUpdated(parcelUsd, _parcelUsd);
parcelUsd = _parcelUsd;
}
function setUsdLockAccountThreshold(uint _usdLockAccountThreshold) public onlyOwner {
require(!finalised);
emit UsdLockAccountThresholdUpdated(usdLockAccountThreshold, _usdLockAccountThreshold);
usdLockAccountThreshold = _usdLockAccountThreshold;
}
function setGzeBonusOffList(uint _gzeBonusOffList) public onlyOwner {
require(!finalised);
emit GzeBonusOffListUpdated(gzeBonusOffList, _gzeBonusOffList);
gzeBonusOffList = _gzeBonusOffList;
}
function setGzeBonusOnList(uint _gzeBonusOnList) public onlyOwner {
require(!finalised);
emit GzeBonusOnListUpdated(gzeBonusOnList, _gzeBonusOnList);
gzeBonusOnList = _gzeBonusOnList;
}
function symbol() public view returns (string _symbol) {
_symbol = parcelToken.symbol();
}
function name() public view returns (string _name) {
_name = parcelToken.name();
}
// USD per ETH, e.g., 221.99 * 10^18
function ethUsd() public view returns (uint _rate, bool _live) {
return ethUsdPriceFeed.getRate();
}
// ETH per GZE, e.g., 0.00004366 * 10^18
function gzeEth() public view returns (uint _rate, bool _live) {
return gzeEthPriceFeed.getRate();
}
// USD per GZE, e.g., 0.0096920834 * 10^18
function gzeUsd() public view returns (uint _rate, bool _live) {
uint _ethUsd;
bool _ethUsdLive;
(_ethUsd, _ethUsdLive) = ethUsdPriceFeed.getRate();
uint _gzeEth;
bool _gzeEthLive;
(_gzeEth, _gzeEthLive) = gzeEthPriceFeed.getRate();
if (_ethUsdLive && _gzeEthLive) {
_live = true;
_rate = _ethUsd.mul(_gzeEth).div(TENPOW18);
}
}
// ETH per parcel, e.g., 6.757061128879679264 * 10^18
function parcelEth() public view returns (uint _rate, bool _live) {
uint _ethUsd;
(_ethUsd, _live) = ethUsd();
if (_live) {
_rate = parcelUsd.mul(TENPOW18).div(_ethUsd);
}
}
// GZE per parcel, without bonus, e.g., 154765.486231783766945298 * 10^18
function parcelGzeWithoutBonus() public view returns (uint _rate, bool _live) {
uint _gzeUsd;
(_gzeUsd, _live) = gzeUsd();
if (_live) {
_rate = parcelUsd.mul(TENPOW18).div(_gzeUsd);
}
}
// GZE per parcel, with bonus but not on bonus list, e.g., 128971.238526486472454415 * 10^18
function parcelGzeWithBonusOffList() public view returns (uint _rate, bool _live) {
uint _parcelGzeWithoutBonus;
(_parcelGzeWithoutBonus, _live) = parcelGzeWithoutBonus();
if (_live) {
_rate = _parcelGzeWithoutBonus.mul(100).div(gzeBonusOffList.add(100));
}
}
// GZE per parcel, with bonus and on bonus list, e.g., 119050.374024449051496383 * 10^18
function parcelGzeWithBonusOnList() public view returns (uint _rate, bool _live) {
uint _parcelGzeWithoutBonus;
(_parcelGzeWithoutBonus, _live) = parcelGzeWithoutBonus();
if (_live) {
_rate = _parcelGzeWithoutBonus.mul(100).div(gzeBonusOnList.add(100));
}
}
// Account contributes by:
// 1. calling GZE.approve(landRushAddress, tokens)
// 2. calling this.purchaseWithGze(tokens)
function purchaseWithGze(uint256 tokens) public {
require(gzeToken.allowance(msg.sender, this) >= tokens);
receiveApproval(msg.sender, tokens, gzeToken, "");
}
// Account contributes by calling GZE.approveAndCall(landRushAddress, tokens, "")
function receiveApproval(address from, uint256 tokens, address token, bytes /* data */) public {
require(now >= startDate && now <= endDate);
require(token == address(gzeToken));
uint _parcelGze;
bool _live;
if (bonusList.isInBonusList(from)) {
(_parcelGze, _live) = parcelGzeWithBonusOnList();
} else {
(_parcelGze, _live) = parcelGzeWithBonusOffList();
}
require(_live);
uint parcels = tokens.div(_parcelGze);
if (parcelsSold.add(parcels) >= maxParcels) {
parcels = maxParcels.sub(parcelsSold);
}
uint gzeToTransfer = parcels.mul(_parcelGze);
contributedGze = contributedGze.add(gzeToTransfer);
require(ERC20Interface(token).transferFrom(from, wallet, gzeToTransfer));
bool lock = mintParcelTokens(from, parcels);
emit Purchased(from, parcels, gzeToTransfer, 0, parcelsSold, contributedGze, contributedEth, lock);
}
// Account contributes by sending ETH
function () public payable {
require(now >= startDate && now <= endDate);
uint _parcelEth;
bool _live;
(_parcelEth, _live) = parcelEth();
require(_live);
uint parcels = msg.value.div(_parcelEth);
if (parcelsSold.add(parcels) >= maxParcels) {
parcels = maxParcels.sub(parcelsSold);
}
uint ethToTransfer = parcels.mul(_parcelEth);
contributedEth = contributedEth.add(ethToTransfer);
uint ethToRefund = msg.value.sub(ethToTransfer);
if (ethToRefund > 0) {
msg.sender.transfer(ethToRefund);
}
bool lock = mintParcelTokens(msg.sender, parcels);
emit Purchased(msg.sender, parcels, 0, ethToTransfer, parcelsSold, contributedGze, contributedEth, lock);
}
// Contract owner allocates parcels to tokenOwner for offline purchase
function offlinePurchase(address tokenOwner, uint parcels) public onlyOwner {
require(!finalised);
if (parcelsSold.add(parcels) >= maxParcels) {
parcels = maxParcels.sub(parcelsSold);
}
bool lock = mintParcelTokens(tokenOwner, parcels);
emit Purchased(tokenOwner, parcels, 0, 0, parcelsSold, contributedGze, contributedEth, lock);
}
// Internal function to mint tokens and disable minting if maxParcels sold
function mintParcelTokens(address account, uint parcels) internal returns (bool _lock) {
require(parcels > 0);
parcelsSold = parcelsSold.add(parcels);
_lock = parcelToken.balanceOf(account).add(parcelUsd.mul(parcels)) >= usdLockAccountThreshold;
require(parcelToken.mint(account, parcelUsd.mul(parcels), _lock));
if (parcelsSold >= maxParcels) {
parcelToken.disableMinting();
finalised = true;
}
}
// Contract owner finalises to disable parcel minting
function finalise() public onlyOwner {
require(!finalised);
require(now > endDate || parcelsSold >= maxParcels);
parcelToken.disableMinting();
finalised = true;
}
}
| GZE per parcel, with bonus but not on bonus list, e.g., 128971.238526486472454415 10^18 | function parcelGzeWithBonusOffList() public view returns (uint _rate, bool _live) {
uint _parcelGzeWithoutBonus;
(_parcelGzeWithoutBonus, _live) = parcelGzeWithoutBonus();
if (_live) {
_rate = _parcelGzeWithoutBonus.mul(100).div(gzeBonusOffList.add(100));
}
}
| 2,548,898 |
/**
* @authors: [@unknownunknown1]
* @reviewers: []
* @auditors: []
* @bounties: []
* @deployments: []
*/
/* solium-disable security/no-block-members */
/* solium-disable max-len*/
pragma solidity ^0.4.24;
import "@kleros/kleros-interaction/contracts/standard/arbitration/Arbitrable.sol";
import "@kleros/kleros-interaction/contracts/libraries/CappedMath.sol";
contract KlerosGovernor is Arbitrable{
using CappedMath for uint;
/* *** Contract variables *** */
enum Status {NoDispute, DisputeCreated}
struct Transaction{
address target; // The address to call.
uint value; // Value paid by governor contract that will be used as msg.value in the execution.
bytes data; // Calldata of the transaction.
bool executed; // Whether the transaction was already executed or not.
}
struct TransactionList{
address sender; // Submitter.
uint deposit; // Value of a deposit paid upon submission of the list.
Transaction[] txs; // Transactions stored in the list. txs[_transactionIndex].
bytes32 listHash; // A hash chain of all transactions stored in the list. Is needed to catch duplicates.
uint submissionTime; // Time the list was submitted.
bool approved; // Whether the list was approved for execution or not.
}
Status public status; // Status showing whether the contract has an ongoing dispute or not.
address public governor; // The address that can make governance changes to the parameters.
uint public submissionDeposit; // Value in wei that needs to be paid in order to submit the list.
uint public submissionTimeout; // Time in seconds allowed for submitting the lists. Once it's passed the contract enters the approval period.
uint public withdrawTimeout; // Time in seconds allowed to withdraw a submitted list.
uint public sharedMultiplier; // Multiplier for calculating the appeal fee that must be paid by submitter in the case where there is no winner/loser (e.g. when the arbitrator ruled "refuse to arbitrate").
uint public winnerMultiplier; // Multiplier for calculating the appeal fee of the party that won the previous round.
uint public loserMultiplier; // Multiplier for calculating the appeal fee of the party that lost the previous round.
uint public constant MULTIPLIER_DIVISOR = 10000; // Divisor parameter for multipliers.
uint public sumDeposit; // Sum of all submission deposits in a current submission period (minus arbitration fees). Is needed for calculating a reward.
uint public lastAction; // The time of the last approval of a transaction list.
uint public disputeID; // The ID of the dispute created in arbitrator contract.
uint public shadowWinner = uint(-1); // Submission index of the first list that paid appeal fees. If it stays the only list that paid appeal fees it will win regardless of the final ruling.
TransactionList[] public txLists; // Stores all created transaction lists. txLists[_listID].
uint[] public submittedLists; // Stores all lists submitted in a current submission period. Is cleared after each submitting session. submittedLists[_submissionID].
/* *** Modifiers *** */
modifier duringSubmissionPeriod() {require(now - lastAction <= submissionTimeout, "Submission time has ended"); _;}
modifier duringApprovalPeriod() {require(now - lastAction > submissionTimeout, "Approval time has not started yet"); _;}
modifier onlyByGovernor() {require(governor == msg.sender, "Only the governor can execute this"); _;}
/** @dev Constructor.
* @param _arbitrator The arbitrator of the contract.
* @param _extraData Extra data for the arbitrator.
* @param _submissionDeposit The deposit required for submission.
* @param _submissionTimeout Time in seconds allocated for submitting transaction list.
* @param _withdrawTimeout Time in seconds after submission that allows to withdraw submitted list.
* @param _sharedMultiplier Multiplier of the appeal cost that submitter has to pay for a round when there is no winner/loser in the previous round. In basis points.
* @param _winnerMultiplier Multiplier of the appeal cost that the winner has to pay for a round. In basis points.
* @param _loserMultiplier Multiplier of the appeal cost that the loser has to pay for a round. In basis points.
*/
constructor(
Arbitrator _arbitrator,
bytes _extraData,
uint _submissionDeposit,
uint _submissionTimeout,
uint _withdrawTimeout,
uint _sharedMultiplier,
uint _winnerMultiplier,
uint _loserMultiplier
) public Arbitrable(_arbitrator, _extraData){
lastAction = now;
submissionDeposit = _submissionDeposit;
submissionTimeout = _submissionTimeout;
withdrawTimeout = _withdrawTimeout;
sharedMultiplier = _sharedMultiplier;
winnerMultiplier = _winnerMultiplier;
loserMultiplier = _loserMultiplier;
governor = address(this);
}
/** @dev Changes the value of the deposit required for submitting a list.
* @param _submissionDeposit The new value of a required deposit. In wei.
*/
function changeSubmissionDeposit(uint _submissionDeposit) public onlyByGovernor {
submissionDeposit = _submissionDeposit;
}
/** @dev Changes the time allocated for submission.
* @param _submissionTimeout The new duration of submission time. In seconds.
*/
function changeSubmissionTimeout(uint _submissionTimeout) public onlyByGovernor {
submissionTimeout = _submissionTimeout;
}
/** @dev Changes the time allowed for list withdrawal.
* @param _withdrawTimeout The new duration of withdraw timeout. In seconds.
*/
function changeWithdrawTimeout(uint _withdrawTimeout) public onlyByGovernor {
withdrawTimeout = _withdrawTimeout;
}
/** @dev Changes the percentage of appeal fees that must be added to appeal cost when there is no winner or loser.
* @param _sharedMultiplier The new shared mulitplier value.
*/
function changeSharedMultiplier(uint _sharedMultiplier) public onlyByGovernor {
sharedMultiplier = _sharedMultiplier;
}
/** @dev Changes the percentage of appeal fees that must be added to appeal cost for the winning party.
* @param _winnerMultiplier The new winner mulitplier value.
*/
function changeWinnerMultiplier(uint _winnerMultiplier) public onlyByGovernor {
winnerMultiplier = _winnerMultiplier;
}
/** @dev Changes the percentage of appeal fees that must be added to appeal cost for the losing party.
* @param _loserMultiplier The new loser mulitplier value.
*/
function changeLoserMultiplier(uint _loserMultiplier) public onlyByGovernor {
loserMultiplier = _loserMultiplier;
}
/** @dev Creates transaction list based on input parameters and submits it for potential approval and execution.
* @param _target List of addresses to call.
* @param _value List of values required for respective addresses.
* @param _data Concatenated calldata of all transactions of this list.
* @param _dataSize List of lengths in bytes required to split calldata for its respective targets.
* @return submissionID The ID that was given to the list upon submission. Starts with 0.
*/
function submitList(address[] _target, uint[] _value, bytes _data, uint[] _dataSize) public payable duringSubmissionPeriod returns(uint submissionID){
require(_target.length == _value.length, "Incorrect input. Target and value arrays must be of the same length");
require(_target.length == _dataSize.length, "Incorrect input. Target and datasize arrays must be of the same length");
require(msg.value >= submissionDeposit, "Submission deposit must be paid");
txLists.length++;
uint listID = txLists.length - 1;
TransactionList storage txList = txLists[listID];
txList.sender = msg.sender;
txList.deposit = submissionDeposit;
bytes32 listHash;
uint pointer;
for (uint i = 0; i < _target.length; i++){
bytes memory tempData = new bytes(_dataSize[i]);
Transaction storage transaction = txList.txs[txList.txs.length++];
transaction.target = _target[i];
transaction.value = _value[i];
for (uint j = 0; j < _dataSize[i]; j++){
tempData[j] = _data[j + pointer];
}
transaction.data = tempData;
pointer += _dataSize[i];
if (i == 0) {
listHash = keccak256(abi.encodePacked(transaction.target, transaction.value, transaction.data));
} else {
listHash = keccak256(abi.encodePacked(keccak256(abi.encodePacked(transaction.target, transaction.value, transaction.data)), listHash));
}
}
txList.listHash = listHash;
txList.submissionTime = now;
sumDeposit += submissionDeposit;
submissionID = submittedLists.push(listID);
uint remainder = msg.value - submissionDeposit;
if (remainder > 0) msg.sender.send(remainder);
}
/** @dev Withdraws submitted transaction list. Reimburses submission deposit.
* @param _submissionID The ID that was given to the list upon submission.
*/
function withdrawTransactionList(uint _submissionID) public duringSubmissionPeriod{
TransactionList storage txList = txLists[submittedLists[_submissionID]];
require(txList.sender == msg.sender, "Can't withdraw the list created by someone else");
require(now - txList.submissionTime <= withdrawTimeout, "Withdrawing time has passed");
submittedLists[_submissionID] = submittedLists[submittedLists.length - 1];
submittedLists.length--;
sumDeposit = sumDeposit.subCap(txList.deposit);
msg.sender.transfer(txList.deposit);
}
/** @dev Approves a transaction list or creates a dispute if more than one list was submitted.
* If nothing was submitted resets the period of the contract to the submission period.
*/
function approveTransactionList() public duringApprovalPeriod{
require(status == Status.NoDispute, "Can't execute transaction list while dispute is active");
if (submittedLists.length == 0){
lastAction = now;
} else if (submittedLists.length == 1){
TransactionList storage txList = txLists[submittedLists[0]];
txList.approved = true;
txList.sender.send(sumDeposit);
submittedLists.length--;
sumDeposit = 0;
lastAction = now;
} else {
status = Status.DisputeCreated;
uint arbitrationCost = arbitrator.arbitrationCost(arbitratorExtraData);
disputeID = arbitrator.createDispute.value(arbitrationCost)(submittedLists.length, arbitratorExtraData);
sumDeposit = sumDeposit.subCap(arbitrationCost);
lastAction = 0;
}
}
/** @dev Takes up to the total amount required to fund a side of an appeal. Reimburses the rest. Creates an appeal if at least two lists are funded.
* @param _submissionID The ID that was given to the list upon submission.
*/
function fundAppeal(uint _submissionID) public payable{
require(status == Status.DisputeCreated, "No dispute to appeal");
require(arbitrator.disputeStatus(disputeID) == Arbitrator.DisputeStatus.Appealable, "Dispute is not appealable.");
(uint appealPeriodStart, uint appealPeriodEnd) = arbitrator.appealPeriod(disputeID);
require(
now >= appealPeriodStart && now < appealPeriodEnd,
"Appeal fees must be paid within the appeal period."
);
TransactionList storage txList = txLists[submittedLists[_submissionID]];
require(txList.sender == msg.sender, "Can't fund the list created by someone else");
require(_submissionID != shadowWinner, "Appeal fee has already been paid");
if(shadowWinner == uint(-1)) shadowWinner = _submissionID;
uint winner = arbitrator.currentRuling(disputeID);
uint multiplier;
// Unlike in submittedLists, in arbitrator "0" is reserved for "refuse to arbitrate" option. So we need to add 1 to map submission IDs with choices correctly.
if (winner == _submissionID + 1){
multiplier = winnerMultiplier;
} else if (winner == 0){
multiplier = sharedMultiplier;
} else {
require(now - appealPeriodStart < (appealPeriodEnd - appealPeriodStart)/2, "The loser must pay during the first half of the appeal period.");
multiplier = loserMultiplier;
}
uint appealCost = arbitrator.appealCost(disputeID, arbitratorExtraData);
uint totalCost = appealCost.addCap((appealCost.mulCap(multiplier)) / MULTIPLIER_DIVISOR);
sumDeposit += totalCost;
require(msg.value >= totalCost, "Not enough ETH to cover appeal cost");
uint remainder = msg.value - totalCost;
if (remainder > 0) txList.sender.send(remainder);
if(shadowWinner != uint(-1) && shadowWinner != _submissionID){
shadowWinner = uint(-1);
arbitrator.appeal.value(appealCost)(disputeID, arbitratorExtraData);
sumDeposit = sumDeposit.subCap(appealCost);
}
}
/** @dev Gives a ruling for a dispute. Must be called by the arbitrator.
* The purpose of this function is to ensure that the address calling it has the right to rule on the contract.
* @param _disputeID ID of the dispute in the Arbitrator contract.
* @param _ruling Ruling given by the arbitrator. Note that 0 is reserved for "Refuse to arbitrate".
*/
function rule(uint _disputeID, uint _ruling) public {
require(msg.sender == address(arbitrator), "Must be called by the arbitrator");
require(status == Status.DisputeCreated, "The dispute has already been resolved");
require(_ruling <= submittedLists.length, "Ruling is out of bounds");
uint ruling = _ruling;
if(shadowWinner != uint(-1)){
ruling = shadowWinner + 1;
} else if (ruling != 0){
// If winning list has a duplicate with lower submission time, the duplicate will win. Queries only through first 10 submitted lists to prevent going out of gas.
for (uint i = 0; (i < submittedLists.length) && i < 10; i++){
if (txLists[submittedLists[i]].listHash == txLists[submittedLists[ruling - 1]].listHash &&
txLists[submittedLists[i]].submissionTime < txLists[submittedLists[ruling - 1]].submissionTime){
ruling = i + 1;
}
}
}
executeRuling(_disputeID, ruling);
}
/** @dev Executes a ruling of a dispute.
* @param _disputeID ID of the dispute in the Arbitrator contract.
* @param _ruling Ruling given by the arbitrator. Note that 0 is reserved for "Refuse to arbitrate".
* If the final ruling is "0" nothing is approved and deposits will stay locked in the contract.
*/
function executeRuling(uint _disputeID, uint _ruling) internal{
if(_ruling != 0){
TransactionList storage txList = txLists[submittedLists[_ruling - 1]];
txList.approved = true;
uint reward = sumDeposit.subCap(txList.deposit);
txList.sender.send(reward);
}
sumDeposit = 0;
disputeID = 0;
shadowWinner = uint(-1);
delete submittedLists;
lastAction = now;
status = Status.NoDispute;
}
/** @dev Executes selected transactions of the list.
* @param _listID The index of the transaction list in the array of lists.
* @param _cursor Index of the transaction from which to start executing.
* @param _count Number of transactions to execute. Executes until the end if set to "0" or number higher than number of transactions in the list.
*/
function executeTransactionList(uint _listID, uint _cursor, uint _count) public {
TransactionList storage txList = txLists[_listID];
require(txList.approved, "Can't execute list that wasn't approved");
for (uint i = _cursor; i < txList.txs.length && (_count == 0 || i < _cursor + _count) ; i++){
Transaction storage transaction = txList.txs[i];
if (transaction.executed || transaction.value > address(this).balance) continue;
transaction.executed = true;
transaction.target.call.value(transaction.value)(transaction.data); // solium-disable-line security/no-call-value
}
}
/** @dev Gets the info of the specified transaction in the specified list.
* @param _listID The index of the transaction list in the array of lists.
* @param _transactionIndex The index of the transaction.
* @return The transaction info.
*/
function getTransactionInfo(uint _listID, uint _transactionIndex)
public
view
returns (
address target,
uint value,
bytes data,
bool executed
)
{
TransactionList storage txList = txLists[_listID];
Transaction storage transaction = txList.txs[_transactionIndex];
return (
transaction.target,
transaction.value,
transaction.data,
transaction.executed
);
}
/** @dev Gets the number of transactions in the list.
* @param _listID The index of the transaction list in the array of lists.
* @return txCount The number of transactions in the list.
*/
function getNumberOfTransactions(uint _listID) public view returns (uint txCount){
TransactionList storage txList = txLists[_listID];
return txList.txs.length;
}
/** @dev Gets the number of lists submitted in this session.
* @return The number of submitted lists.
*/
function getNumberOfSubmittedLists() public view returns (uint){
return submittedLists.length;
}
/** @dev Gets the number of lists created in contract's lifetime.
* @return The number of created lists.
*/
function getNumberOfCreatedLists() public view returns (uint){
return txLists.length;
}
} | Changes the percentage of appeal fees that must be added to appeal cost for the winning party. _winnerMultiplier The new winner mulitplier value./ | function changeWinnerMultiplier(uint _winnerMultiplier) public onlyByGovernor {
winnerMultiplier = _winnerMultiplier;
}
| 1,009,207 |
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity ^0.6.12;
import "./Interfaces/LiquidityMathModelInterface.sol";
import "./MToken.sol";
import "./Utils/ErrorReporter.sol";
import "./Utils/ExponentialNoError.sol";
import "./Utils/AssetHelpers.sol";
import "./Moartroller.sol";
import "./SimplePriceOracle.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
contract LiquidityMathModelV1 is LiquidityMathModelInterface, LiquidityMathModelErrorReporter, ExponentialNoError, Ownable, AssetHelpers {
/**
* @notice get the maximum asset value that can be still optimized.
* @notice if protectionId is supplied, the maxOptimizableValue is increased by the protection lock value'
* which is helpful to recalculate how much of this protection can be optimized again
*/
function getMaxOptimizableValue(LiquidityMathModelInterface.LiquidityMathArgumentsSet memory arguments) external override view returns (uint){
uint returnValue;
uint hypotheticalOptimizableValue = getHypotheticalOptimizableValue(arguments);
uint totalProtectionLockedValue;
(totalProtectionLockedValue, ) = getTotalProtectionLockedValue(arguments);
if(hypotheticalOptimizableValue <= totalProtectionLockedValue){
returnValue = 0;
}
else{
returnValue = sub_(hypotheticalOptimizableValue, totalProtectionLockedValue);
}
return returnValue;
}
/**
* @notice get the maximum value of an asset that can be optimized by protection for the given user
* @dev optimizable = asset value * MPC
* @return the hypothetical optimizable value
* TODO: replace hardcoded 1e18 values
*/
function getHypotheticalOptimizableValue(LiquidityMathModelInterface.LiquidityMathArgumentsSet memory arguments) public override view returns(uint) {
uint assetValue = div_(
mul_(
div_(
mul_(
arguments.asset.balanceOf(arguments.account),
arguments.asset.exchangeRateStored()
),
1e18
),
arguments.oracle.getUnderlyingPrice(arguments.asset)
),
getAssetDecimalsMantissa(arguments.asset.getUnderlying())
);
uint256 hypotheticalOptimizableValue = div_(
mul_(
assetValue,
arguments.asset.maxProtectionComposition()
),
arguments.asset.maxProtectionCompositionMantissa()
);
return hypotheticalOptimizableValue;
}
/**
* @dev gets all locked protections values with mark to market value. Used by Moartroller.
*/
function getTotalProtectionLockedValue(LiquidityMathModelInterface.LiquidityMathArgumentsSet memory arguments) public override view returns(uint, uint) {
uint _lockedValue = 0;
uint _markToMarket = 0;
uint _protectionCount = arguments.cprotection.getUserUnderlyingProtectionTokenIdByCurrencySize(arguments.account, arguments.asset.underlying());
for (uint j = 0; j < _protectionCount; j++) {
uint protectionId = arguments.cprotection.getUserUnderlyingProtectionTokenIdByCurrency(arguments.account, arguments.asset.underlying(), j);
bool protectionIsAlive = arguments.cprotection.isProtectionAlive(protectionId);
if(protectionIsAlive){
_lockedValue = add_(_lockedValue, arguments.cprotection.getUnderlyingProtectionLockedValue(protectionId));
uint assetSpotPrice = arguments.oracle.getUnderlyingPrice(arguments.asset);
uint protectionStrikePrice = arguments.cprotection.getUnderlyingStrikePrice(protectionId);
if( assetSpotPrice > protectionStrikePrice) {
_markToMarket = _markToMarket + div_(
mul_(
div_(
mul_(
assetSpotPrice - protectionStrikePrice,
arguments.cprotection.getUnderlyingProtectionLockedAmount(protectionId)
),
getAssetDecimalsMantissa(arguments.asset.underlying())
),
arguments.collateralFactorMantissa
),
1e18
);
}
}
}
return (_lockedValue , _markToMarket);
}
}
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity ^0.6.12;
import "../MToken.sol";
import "../MProtection.sol";
import "../Interfaces/PriceOracle.sol";
interface LiquidityMathModelInterface {
struct LiquidityMathArgumentsSet {
MToken asset;
address account;
uint collateralFactorMantissa;
MProtection cprotection;
PriceOracle oracle;
}
function getMaxOptimizableValue(LiquidityMathArgumentsSet memory _arguments) external view returns (uint);
function getHypotheticalOptimizableValue(LiquidityMathArgumentsSet memory _arguments) external view returns(uint);
function getTotalProtectionLockedValue(LiquidityMathArgumentsSet memory _arguments) external view returns(uint, uint);
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.6.12;
import "./Utils/ErrorReporter.sol";
import "./Utils/Exponential.sol";
import "./Interfaces/EIP20Interface.sol";
import "./MTokenStorage.sol";
import "./Interfaces/MTokenInterface.sol";
import "./Interfaces/MProxyInterface.sol";
import "./Moartroller.sol";
import "./AbstractInterestRateModel.sol";
/**
* @title MOAR's MToken Contract
* @notice Abstract base for MTokens
* @author MOAR
*/
abstract contract MToken is MTokenInterface, Exponential, TokenErrorReporter, MTokenStorage {
/**
* @notice Indicator that this is a MToken contract (for inspection)
*/
bool public constant isMToken = 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 MTokenCollateral, 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 moartroller is changed
*/
event NewMoartroller(Moartroller oldMoartroller, Moartroller newMoartroller);
/**
* @notice Event emitted when interestRateModel is changed
*/
event NewMarketInterestRateModel(InterestRateModelInterface oldInterestRateModel, InterestRateModelInterface 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);
/**
* @notice Max protection composition value updated event
*/
event MpcUpdated(uint newValue);
/**
* @notice Initialize the money market
* @param moartroller_ The address of the Moartroller
* @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 init(Moartroller moartroller_,
AbstractInterestRateModel interestRateModel_,
uint initialExchangeRateMantissa_,
string memory name_,
string memory symbol_,
uint8 decimals_) public {
require(msg.sender == admin, "not_admin");
require(accrualBlockNumber == 0 && borrowIndex == 0, "already_init");
// Set initial exchange rate
initialExchangeRateMantissa = initialExchangeRateMantissa_;
require(initialExchangeRateMantissa > 0, "too_low");
// Set the moartroller
uint err = _setMoartroller(moartroller_);
require(err == uint(Error.NO_ERROR), "setting moartroller failed");
// Initialize block number and borrow index (block number mocks depend on moartroller 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 IRM 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;
maxProtectionComposition = 5000;
maxProtectionCompositionMantissa = 1e4;
reserveFactorMaxMantissa = 1e18;
borrowRateMaxMantissa = 0.0005e16;
}
/**
* @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 = moartroller.transferAllowed(address(this), src, dst, tokens);
if (allowed != 0) {
return failOpaque(Error.MOARTROLLER_REJECTION, FailureInfo.TRANSFER_MOARTROLLER_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 srmTokensNew;
uint dstTokensNew;
(mathErr, allowanceNew) = subUInt(startingAllowance, tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ALLOWED);
}
(mathErr, srmTokensNew) = 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] = srmTokensNew;
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);
// unused function
// moartroller.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 virtual override 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 virtual override 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 virtual 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 virtual 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 virtual override 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 virtual override returns (uint) {
Exp memory exchangeRate = Exp({mantissa: exchangeRateCurrent()});
(MathError mErr, uint balance) = mulScalarTruncate(exchangeRate, accountTokens[owner]);
require(mErr == MathError.NO_ERROR, "balance_calculation_failed");
return balance;
}
/**
* @notice Get a snapshot of the account's balances, and the cached exchange rate
* @dev This is used by moartroller 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 virtual override view returns (uint, uint, uint, uint) {
uint mTokenBalance = 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), mTokenBalance, 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 mToken
* @return The borrow interest rate per block, scaled by 1e18
*/
function borrowRatePerBlock() external virtual override view returns (uint) {
return interestRateModel.getBorrowRate(getCashPrior(), totalBorrows, totalReserves);
}
/**
* @notice Returns the current per-block supply interest rate for this mToken
* @return The supply interest rate per block, scaled by 1e18
*/
function supplyRatePerBlock() external virtual override 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 virtual override 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 virtual override 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 virtual view returns (uint) {
(MathError err, uint result) = borrowBalanceStoredInternal(account);
require(err == MathError.NO_ERROR, "borrowBalanceStored 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 virtual nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return exchangeRateStored();
}
/**
* @notice Calculates the exchange rate from the underlying to the MToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateStored() public virtual view returns (uint) {
(MathError err, uint result) = exchangeRateStoredInternal();
require(err == MathError.NO_ERROR, "exchangeRateStored failed");
return result;
}
/**
* @notice Calculates the exchange rate from the underlying to the MToken
* @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 mToken in the underlying asset
* @return The quantity of underlying asset owned by this contract
*/
function getCash() external virtual override view returns (uint) {
return getCashPrior();
}
function getRealBorrowIndex() public view returns (uint) {
uint currentBlockNumber = getBlockNumber();
uint accrualBlockNumberPrior = accrualBlockNumber;
uint cashPrior = getCashPrior();
uint borrowsPrior = totalBorrows;
uint reservesPrior = totalReserves;
uint borrowIndexPrior = borrowIndex;
uint borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, borrowsPrior, reservesPrior);
require(borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate too high");
(MathError mathErr, uint blockDelta) = subUInt(currentBlockNumber, accrualBlockNumberPrior);
require(mathErr == MathError.NO_ERROR, "could not calc block delta");
Exp memory simpleInterestFactor;
uint borrowIndexNew;
(mathErr, simpleInterestFactor) = mulScalar(Exp({mantissa: borrowRateMantissa}), blockDelta);
require(mathErr == MathError.NO_ERROR, "could not calc simpleInterestFactor");
(mathErr, borrowIndexNew) = mulScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior);
require(mathErr == MathError.NO_ERROR, "could not calc borrowIndex");
return borrowIndexNew;
}
/**
* @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 virtual 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 too 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 calc 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;
AccrueInterestTempStorage memory temp;
(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, temp.interestAccumulated) = mulScalarTruncate(simpleInterestFactor, borrowsPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, temp.totalBorrowsNew) = addUInt(temp.interestAccumulated, borrowsPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, temp.reservesAdded) = mulScalarTruncate(Exp({mantissa: reserveFactorMantissa}), temp.interestAccumulated);
if(mathErr != MathError.NO_ERROR){
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, temp.splitedReserves_2) = mulScalarTruncate(Exp({mantissa: reserveSplitFactorMantissa}), temp.reservesAdded);
if(mathErr != MathError.NO_ERROR){
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, temp.splitedReserves_1) = subUInt(temp.reservesAdded, temp.splitedReserves_2);
if(mathErr != MathError.NO_ERROR){
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, temp.totalReservesNew) = addUInt(temp.splitedReserves_1, reservesPrior);
if(mathErr != MathError.NO_ERROR){
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, temp.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 = temp.borrowIndexNew;
totalBorrows = temp.totalBorrowsNew;
totalReserves = temp.totalReservesNew;
if(temp.splitedReserves_2 > 0){
address mProxy = moartroller.mProxy();
EIP20Interface(underlying).approve(mProxy, temp.splitedReserves_2);
MProxyInterface(mProxy).proxySplitReserves(underlying, temp.splitedReserves_2);
}
/* We emit an AccrueInterest event */
emit AccrueInterest(cashPrior, temp.interestAccumulated, temp.borrowIndexNew, temp.totalBorrowsNew);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender supplies assets into the market and receives mTokens 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 mTokens 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 = moartroller.mintAllowed(address(this), minter, mintAmount);
if (allowed != 0) {
return (failOpaque(Error.MOARTROLLER_REJECTION, FailureInfo.MINT_MOARTROLLER_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 mToken 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 mToken holds an additional `actualMintAmount`
* of cash.
*/
vars.actualMintAmount = doTransferIn(minter, mintAmount);
/*
* We get the current exchange rate and calculate the number of mTokens to be minted:
* mintTokens = actualMintAmount / exchangeRate
*/
(vars.mathErr, vars.mintTokens) = divScalarByExpTruncate(vars.actualMintAmount, Exp({mantissa: vars.exchangeRateMantissa}));
require(vars.mathErr == MathError.NO_ERROR, "MINT_E");
/*
* We calculate the new total supply of mTokens 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_E");
(vars.mathErr, vars.accountTokensNew) = addUInt(accountTokens[minter], vars.mintTokens);
require(vars.mathErr == MathError.NO_ERROR, "MINT_E");
/* 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 */
// unused function
// moartroller.mintVerify(address(this), minter, vars.actualMintAmount, vars.mintTokens);
return (uint(Error.NO_ERROR), vars.actualMintAmount);
}
/**
* @notice Sender redeems mTokens in exchange for the underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemTokens The number of mTokens 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 mTokens 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 mTokens
* @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 mTokens 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 mTokens 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 mTokens (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, "redeemFresh_missing_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 = moartroller.redeemAllowed(address(this), redeemer, vars.redeemTokens);
if (allowed != 0) {
return failOpaque(Error.MOARTROLLER_REJECTION, FailureInfo.REDEEM_MOARTROLLER_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);
}
/* Fail if user tries to redeem more than he has locked with c-op*/
// TODO: update error codes
uint newTokensAmount = div_(mul_(vars.accountTokensNew, vars.exchangeRateMantissa), 1e18);
if (newTokensAmount < moartroller.getUserLockedAmount(this, redeemer)) {
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 mToken must handle variations between ERC-20 and ETH underlying.
* On success, the mToken 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 */
moartroller.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);
}
function borrowForInternal(address payable borrower, uint borrowAmount) internal nonReentrant returns (uint) {
require(moartroller.isPrivilegedAddress(msg.sender), "permission_missing");
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(borrower, 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 = moartroller.borrowAllowed(address(this), borrower, borrowAmount);
if (allowed != 0) {
return failOpaque(Error.MOARTROLLER_REJECTION, FailureInfo.BORROW_MOARTROLLER_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 mToken must handle variations between ERC-20 and ETH underlying.
* On success, the mToken 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 */
//unused function
// moartroller.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 = moartroller.repayBorrowAllowed(address(this), payer, borrower, repayAmount);
if (allowed != 0) {
return (failOpaque(Error.MOARTROLLER_REJECTION, FailureInfo.REPAY_BORROW_MOARTROLLER_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 the borrow is repaid by another user -1 cannot be used to prevent borrow front-running */
if (repayAmount == uint(-1)) {
require(tx.origin == borrower, "specify a precise amount");
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 mToken must handle variations between ERC-20 and ETH underlying.
* On success, the mToken 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, "BORROW_BALANCE_CALCULATION_FAILED");
(vars.mathErr, vars.totalBorrowsNew) = subUInt(totalBorrows, vars.actualRepayAmount);
require(vars.mathErr == MathError.NO_ERROR, "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 */
// unused function
// moartroller.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 mToken to be liquidated
* @param mTokenCollateral 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, MToken mTokenCollateral) 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 = mTokenCollateral.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, mTokenCollateral);
}
/**
* @notice The liquidator liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this mToken to be liquidated
* @param liquidator The address repaying the borrow and seizing collateral
* @param mTokenCollateral 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, MToken mTokenCollateral) internal returns (uint, uint) {
/* Fail if liquidate not allowed */
uint allowed = moartroller.liquidateBorrowAllowed(address(this), address(mTokenCollateral), liquidator, borrower, repayAmount);
if (allowed != 0) {
return (failOpaque(Error.MOARTROLLER_REJECTION, FailureInfo.LIQUIDATE_MOARTROLLER_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 mTokenCollateral market's block number equals current block number */
if (mTokenCollateral.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) = moartroller.liquidateCalculateSeizeUserTokens(address(this), address(mTokenCollateral), actualRepayAmount, borrower);
require(amountSeizeError == uint(Error.NO_ERROR), "CALCULATE_AMOUNT_SEIZE_FAILED");
/* Revert if borrower collateral token balance < seizeTokens */
require(mTokenCollateral.balanceOf(borrower) >= seizeTokens, "TOO_MUCH");
// If this is also the collateral, run seizeInternal to avoid re-entrancy, otherwise make an external call
uint seizeError;
if (address(mTokenCollateral) == address(this)) {
seizeError = seizeInternal(address(this), liquidator, borrower, seizeTokens);
} else {
seizeError = mTokenCollateral.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(mTokenCollateral), seizeTokens);
/* We call the defense hook */
// unused function
// moartroller.liquidateBorrowVerify(address(this), address(mTokenCollateral), 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 mToken during the process of liquidation.
* Its absolutely critical to use msg.sender as the borrowed mToken and not a parameter.
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of mTokens to seize
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function seize(address liquidator, address borrower, uint seizeTokens) external virtual 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 MToken.
* Its absolutely critical to use msg.sender as the seizer mToken and not a parameter.
* @param seizerToken The contract seizing the collateral (i.e. borrowed mToken)
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of mTokens 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 = moartroller.seizeAllowed(address(this), seizerToken, liquidator, borrower, seizeTokens);
if (allowed != 0) {
return failOpaque(Error.MOARTROLLER_REJECTION, FailureInfo.LIQUIDATE_SEIZE_MOARTROLLER_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 */
// unused function
// moartroller.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 virtual override 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 virtual override 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 moartroller for the market
* @dev Admin function to set a new moartroller
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setMoartroller(Moartroller newMoartroller) public virtual returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_MOARTROLLER_OWNER_CHECK);
}
Moartroller oldMoartroller = moartroller;
// Ensure invoke moartroller.isMoartroller() returns true
require(newMoartroller.isMoartroller(), "not_moartroller");
// Set market's moartroller to newMoartroller
moartroller = newMoartroller;
// Emit NewMoartroller(oldMoartroller, newMoartroller)
emit NewMoartroller(oldMoartroller, newMoartroller);
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 virtual override 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);
}
function _setReserveSplitFactor(uint newReserveSplitFactorMantissa) external nonReentrant returns (uint) {
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK);
}
reserveSplitFactorMantissa = newReserveSplitFactorMantissa;
return uint(Error.NO_ERROR);
}
/**
* @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 mToken must handle variations between ERC-20 and ETH underlying.
* On success, the mToken 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, "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 virtual override 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, "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(AbstractInterestRateModel newInterestRateModel) public virtual 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(AbstractInterestRateModel newInterestRateModel) internal returns (uint) {
// Used to store old model for use in the event that is emitted on success
InterestRateModelInterface 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(), "not_interest_model");
// Set the interest rate model to newInterestRateModel
interestRateModel = newInterestRateModel;
// Emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel)
emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets new value for max protection composition parameter
* @param newMPC New value of MPC
* @return uint 0=success, otherwise a failure
*/
function _setMaxProtectionComposition(uint256 newMPC) external returns(uint){
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_INTEREST_RATE_MODEL_OWNER_CHECK);
}
maxProtectionComposition = newMPC;
emit MpcUpdated(newMPC);
return uint(Error.NO_ERROR);
}
/**
* @notice Returns address of underlying token
* @return address of underlying token
*/
function getUnderlying() external override view returns(address){
return underlying;
}
/*** 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 virtual 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 virtual 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 virtual;
/*** 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
}
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.6.12;
contract MoartrollerErrorReporter {
enum Error {
NO_ERROR,
UNAUTHORIZED,
MOARTROLLER_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,
SUPPORT_PROTECTION_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,
MOARTROLLER_REJECTION,
MOARTROLLER_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_MOARTROLLER_REJECTION,
LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED,
LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED,
LIQUIDATE_COLLATERAL_FRESHNESS_CHECK,
LIQUIDATE_MOARTROLLER_REJECTION,
LIQUIDATE_MOARTROLLER_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_MOARTROLLER_REJECTION,
LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER,
LIQUIDATE_SEIZE_TOO_MUCH,
MINT_ACCRUE_INTEREST_FAILED,
MINT_MOARTROLLER_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_MOARTROLLER_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_MOARTROLLER_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_MOARTROLLER_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_MOARTROLLER_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);
}
}
contract LiquidityMathModelErrorReporter {
enum Error {
NO_ERROR,
UNAUTHORIZED,
PRICE_ERROR,
SNAPSHOT_ERROR
}
enum FailureInfo {
ORACLE_PRICE_CHECK_FAILED
}
/**
* @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);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
/**
* @title Exponential module for storing fixed-precision decimals
* @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)});
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
import "../Interfaces/EIP20Interface.sol";
contract AssetHelpers {
/**
* @dev return asset decimals mantissa. Returns 1e18 if ETH
*/
function getAssetDecimalsMantissa(address assetAddress) public view returns (uint256){
uint assetDecimals = 1e18;
if (assetAddress != address(0)) {
EIP20Interface token = EIP20Interface(assetAddress);
assetDecimals = 10 ** uint256(token.decimals());
}
return assetDecimals;
}
}
// SPDX-License-Identifier: BSD-3-Clause
// Thanks to Compound for their foundational work in DeFi and open-sourcing their code from which we build upon.
pragma solidity ^0.6.12;
pragma experimental ABIEncoderV2;
// import "hardhat/console.sol";
import "./MToken.sol";
import "./Utils/ErrorReporter.sol";
import "./Utils/ExponentialNoError.sol";
import "./Interfaces/PriceOracle.sol";
import "./Interfaces/MoartrollerInterface.sol";
import "./Interfaces/Versionable.sol";
import "./Interfaces/MProxyInterface.sol";
import "./MoartrollerStorage.sol";
import "./Governance/UnionGovernanceToken.sol";
import "./MProtection.sol";
import "./Interfaces/LiquidityMathModelInterface.sol";
import "./LiquidityMathModelV1.sol";
import "./Utils/SafeEIP20.sol";
import "./Interfaces/EIP20Interface.sol";
import "./Interfaces/LiquidationModelInterface.sol";
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
/**
* @title MOAR's Moartroller Contract
* @author MOAR
*/
contract Moartroller is MoartrollerV6Storage, MoartrollerInterface, MoartrollerErrorReporter, ExponentialNoError, Versionable, Initializable {
using SafeEIP20 for EIP20Interface;
/// @notice Indicator that this is a Moartroller contract (for inspection)
bool public constant isMoartroller = true;
/// @notice Emitted when an admin supports a market
event MarketListed(MToken mToken);
/// @notice Emitted when an account enters a market
event MarketEntered(MToken mToken, address account);
/// @notice Emitted when an account exits a market
event MarketExited(MToken mToken, address account);
/// @notice Emitted when close factor is changed by admin
event NewCloseFactor(uint oldCloseFactorMantissa, uint newCloseFactorMantissa);
/// @notice Emitted when a collateral factor is changed by admin
event NewCollateralFactor(MToken mToken, uint oldCollateralFactorMantissa, uint newCollateralFactorMantissa);
/// @notice Emitted when liquidation incentive is changed by admin
event NewLiquidationIncentive(uint oldLiquidationIncentiveMantissa, uint newLiquidationIncentiveMantissa);
/// @notice Emitted when price oracle is changed
event NewPriceOracle(PriceOracle oldPriceOracle, PriceOracle newPriceOracle);
/// @notice Emitted when protection is changed
event NewCProtection(MProtection oldCProtection, MProtection newCProtection);
/// @notice Emitted when pause guardian is changed
event NewPauseGuardian(address oldPauseGuardian, address newPauseGuardian);
/// @notice Emitted when an action is paused globally
event ActionPaused(string action, bool pauseState);
/// @notice Emitted when an action is paused on a market
event ActionPausedMToken(MToken mToken, string action, bool pauseState);
/// @notice Emitted when a new MOAR speed is calculated for a market
event MoarSpeedUpdated(MToken indexed mToken, uint newSpeed);
/// @notice Emitted when a new MOAR speed is set for a contributor
event ContributorMoarSpeedUpdated(address indexed contributor, uint newSpeed);
/// @notice Emitted when MOAR is distributed to a supplier
event DistributedSupplierMoar(MToken indexed mToken, address indexed supplier, uint moarDelta, uint moarSupplyIndex);
/// @notice Emitted when MOAR is distributed to a borrower
event DistributedBorrowerMoar(MToken indexed mToken, address indexed borrower, uint moarDelta, uint moarBorrowIndex);
/// @notice Emitted when borrow cap for a mToken is changed
event NewBorrowCap(MToken indexed mToken, uint newBorrowCap);
/// @notice Emitted when borrow cap guardian is changed
event NewBorrowCapGuardian(address oldBorrowCapGuardian, address newBorrowCapGuardian);
/// @notice Emitted when MOAR is granted by admin
event MoarGranted(address recipient, uint amount);
event NewLiquidityMathModel(address oldLiquidityMathModel, address newLiquidityMathModel);
event NewLiquidationModel(address oldLiquidationModel, address newLiquidationModel);
/// @notice The initial MOAR index for a market
uint224 public constant moarInitialIndex = 1e36;
// closeFactorMantissa must be strictly greater than this value
uint internal constant closeFactorMinMantissa = 0.05e18; // 0.05
// closeFactorMantissa must not exceed this value
uint internal constant closeFactorMaxMantissa = 0.9e18; // 0.9
// No collateralFactorMantissa may exceed this value
uint internal constant collateralFactorMaxMantissa = 0.9e18; // 0.9
// Custom initializer
function initialize(LiquidityMathModelInterface mathModel, LiquidationModelInterface lqdModel) public initializer {
admin = msg.sender;
liquidityMathModel = mathModel;
liquidationModel = lqdModel;
rewardClaimEnabled = false;
}
/*** Assets You Are In ***/
/**
* @notice Returns the assets an account has entered
* @param account The address of the account to pull assets for
* @return A dynamic list with the assets the account has entered
*/
function getAssetsIn(address account) external view returns (MToken[] memory) {
MToken[] memory assetsIn = accountAssets[account];
return assetsIn;
}
/**
* @notice Returns whether the given account is entered in the given asset
* @param account The address of the account to check
* @param mToken The mToken to check
* @return True if the account is in the asset, otherwise false.
*/
function checkMembership(address account, MToken mToken) external view returns (bool) {
return markets[address(mToken)].accountMembership[account];
}
/**
* @notice Add assets to be included in account liquidity calculation
* @param mTokens The list of addresses of the mToken markets to be enabled
* @return Success indicator for whether each corresponding market was entered
*/
function enterMarkets(address[] memory mTokens) public override returns (uint[] memory) {
uint len = mTokens.length;
uint[] memory results = new uint[](len);
for (uint i = 0; i < len; i++) {
MToken mToken = MToken(mTokens[i]);
results[i] = uint(addToMarketInternal(mToken, msg.sender));
}
return results;
}
/**
* @notice Add the market to the borrower's "assets in" for liquidity calculations
* @param mToken The market to enter
* @param borrower The address of the account to modify
* @return Success indicator for whether the market was entered
*/
function addToMarketInternal(MToken mToken, address borrower) internal returns (Error) {
Market storage marketToJoin = markets[address(mToken)];
if (!marketToJoin.isListed) {
// market is not listed, cannot join
return Error.MARKET_NOT_LISTED;
}
if (marketToJoin.accountMembership[borrower] == true) {
// already joined
return Error.NO_ERROR;
}
// survived the gauntlet, add to list
// NOTE: we store these somewhat redundantly as a significant optimization
// this avoids having to iterate through the list for the most common use cases
// that is, only when we need to perform liquidity checks
// and not whenever we want to check if an account is in a particular market
marketToJoin.accountMembership[borrower] = true;
accountAssets[borrower].push(mToken);
emit MarketEntered(mToken, borrower);
return Error.NO_ERROR;
}
/**
* @notice Removes asset from sender's account liquidity calculation
* @dev Sender must not have an outstanding borrow balance in the asset,
* or be providing necessary collateral for an outstanding borrow.
* @param mTokenAddress The address of the asset to be removed
* @return Whether or not the account successfully exited the market
*/
function exitMarket(address mTokenAddress) external override returns (uint) {
MToken mToken = MToken(mTokenAddress);
/* Get sender tokensHeld and amountOwed underlying from the mToken */
(uint oErr, uint tokensHeld, uint amountOwed, ) = mToken.getAccountSnapshot(msg.sender);
require(oErr == 0, "exitMarket: getAccountSnapshot failed"); // semi-opaque error code
/* Fail if the sender has a borrow balance */
if (amountOwed != 0) {
return fail(Error.NONZERO_BORROW_BALANCE, FailureInfo.EXIT_MARKET_BALANCE_OWED);
}
/* Fail if the sender is not permitted to redeem all of their tokens */
uint allowed = redeemAllowedInternal(mTokenAddress, msg.sender, tokensHeld);
if (allowed != 0) {
return failOpaque(Error.REJECTION, FailureInfo.EXIT_MARKET_REJECTION, allowed);
}
Market storage marketToExit = markets[address(mToken)];
/* Return true if the sender is not already ‘in’ the market */
if (!marketToExit.accountMembership[msg.sender]) {
return uint(Error.NO_ERROR);
}
/* Set mToken account membership to false */
delete marketToExit.accountMembership[msg.sender];
/* Delete mToken from the account’s list of assets */
// load into memory for faster iteration
MToken[] memory userAssetList = accountAssets[msg.sender];
uint len = userAssetList.length;
uint assetIndex = len;
for (uint i = 0; i < len; i++) {
if (userAssetList[i] == mToken) {
assetIndex = i;
break;
}
}
// We *must* have found the asset in the list or our redundant data structure is broken
assert(assetIndex < len);
// copy last item in list to location of item to be removed, reduce length by 1
MToken[] storage storedList = accountAssets[msg.sender];
storedList[assetIndex] = storedList[storedList.length - 1];
storedList.pop();
emit MarketExited(mToken, msg.sender);
return uint(Error.NO_ERROR);
}
/*** Policy Hooks ***/
/**
* @notice Checks if the account should be allowed to mint tokens in the given market
* @param mToken The market to verify the mint against
* @param minter The account which would get the minted tokens
* @param mintAmount The amount of underlying being supplied to the market in exchange for tokens
* @return 0 if the mint is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function mintAllowed(address mToken, address minter, uint mintAmount) external override returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!mintGuardianPaused[mToken], "mint is paused");
// Shh - currently unused
minter;
mintAmount;
if (!markets[mToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
// Keep the flywheel moving
updateMoarSupplyIndex(mToken);
distributeSupplierMoar(mToken, minter);
return uint(Error.NO_ERROR);
}
/**
* @notice Checks if the account should be allowed to redeem tokens in the given market
* @param mToken The market to verify the redeem against
* @param redeemer The account which would redeem the tokens
* @param redeemTokens The number of mTokens to exchange for the underlying asset in the market
* @return 0 if the redeem is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function redeemAllowed(address mToken, address redeemer, uint redeemTokens) external override returns (uint) {
uint allowed = redeemAllowedInternal(mToken, redeemer, redeemTokens);
if (allowed != uint(Error.NO_ERROR)) {
return allowed;
}
// Keep the flywheel moving
updateMoarSupplyIndex(mToken);
distributeSupplierMoar(mToken, redeemer);
return uint(Error.NO_ERROR);
}
function redeemAllowedInternal(address mToken, address redeemer, uint redeemTokens) internal view returns (uint) {
if (!markets[mToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
/* If the redeemer is not 'in' the market, then we can bypass the liquidity check */
if (!markets[mToken].accountMembership[redeemer]) {
return uint(Error.NO_ERROR);
}
/* Otherwise, perform a hypothetical liquidity check to guard against shortfall */
(Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(redeemer, MToken(mToken), redeemTokens, 0);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall > 0) {
return uint(Error.INSUFFICIENT_LIQUIDITY);
}
return uint(Error.NO_ERROR);
}
/**
* @notice Validates redeem and reverts on rejection. May emit logs.
* @param mToken Asset being redeemed
* @param redeemer The address redeeming the tokens
* @param redeemAmount The amount of the underlying asset being redeemed
* @param redeemTokens The number of tokens being redeemed
*/
function redeemVerify(address mToken, address redeemer, uint redeemAmount, uint redeemTokens) external override {
// Shh - currently unused
mToken;
redeemer;
// Require tokens is zero or amount is also zero
if (redeemTokens == 0 && redeemAmount > 0) {
revert("redeemTokens zero");
}
}
/**
* @notice Checks if the account should be allowed to borrow the underlying asset of the given market
* @param mToken The market to verify the borrow against
* @param borrower The account which would borrow the asset
* @param borrowAmount The amount of underlying the account would borrow
* @return 0 if the borrow is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function borrowAllowed(address mToken, address borrower, uint borrowAmount) external override returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!borrowGuardianPaused[mToken], "borrow is paused");
if (!markets[mToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
if (!markets[mToken].accountMembership[borrower]) {
// only mTokens may call borrowAllowed if borrower not in market
require(msg.sender == mToken, "sender must be mToken");
// attempt to add borrower to the market
Error err = addToMarketInternal(MToken(msg.sender), borrower);
if (err != Error.NO_ERROR) {
return uint(err);
}
// it should be impossible to break the important invariant
assert(markets[mToken].accountMembership[borrower]);
}
if (oracle.getUnderlyingPrice(MToken(mToken)) == 0) {
return uint(Error.PRICE_ERROR);
}
uint borrowCap = borrowCaps[mToken];
// Borrow cap of 0 corresponds to unlimited borrowing
if (borrowCap != 0) {
uint totalBorrows = MToken(mToken).totalBorrows();
uint nextTotalBorrows = add_(totalBorrows, borrowAmount);
require(nextTotalBorrows < borrowCap, "market borrow cap reached");
}
(Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(borrower, MToken(mToken), 0, borrowAmount);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall > 0) {
return uint(Error.INSUFFICIENT_LIQUIDITY);
}
// Keep the flywheel moving
Exp memory borrowIndex = Exp({mantissa: MToken(mToken).borrowIndex()});
updateMoarBorrowIndex(mToken, borrowIndex);
distributeBorrowerMoar(mToken, borrower, borrowIndex);
return uint(Error.NO_ERROR);
}
/**
* @notice Checks if the account should be allowed to repay a borrow in the given market
* @param mToken The market to verify the repay against
* @param payer The account which would repay the asset
* @param borrower The account which would borrowed the asset
* @param repayAmount The amount of the underlying asset the account would repay
* @return 0 if the repay is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function repayBorrowAllowed(
address mToken,
address payer,
address borrower,
uint repayAmount) external override returns (uint) {
// Shh - currently unused
payer;
borrower;
repayAmount;
if (!markets[mToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
// Keep the flywheel moving
Exp memory borrowIndex = Exp({mantissa: MToken(mToken).borrowIndex()});
updateMoarBorrowIndex(mToken, borrowIndex);
distributeBorrowerMoar(mToken, borrower, borrowIndex);
return uint(Error.NO_ERROR);
}
/**
* @notice Checks if the liquidation should be allowed to occur
* @param mTokenBorrowed Asset which was borrowed by the borrower
* @param mTokenCollateral Asset which was used as collateral and will be seized
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param repayAmount The amount of underlying being repaid
*/
function liquidateBorrowAllowed(
address mTokenBorrowed,
address mTokenCollateral,
address liquidator,
address borrower,
uint repayAmount) external override returns (uint) {
// Shh - currently unused
liquidator;
if (!markets[mTokenBorrowed].isListed || !markets[mTokenCollateral].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
/* The borrower must have shortfall in order to be liquidatable */
(Error err, , uint shortfall) = getAccountLiquidityInternal(borrower);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall == 0) {
return uint(Error.INSUFFICIENT_SHORTFALL);
}
/* The liquidator may not repay more than what is allowed by the closeFactor */
uint borrowBalance = MToken(mTokenBorrowed).borrowBalanceStored(borrower);
uint maxClose = mul_ScalarTruncate(Exp({mantissa: closeFactorMantissa}), borrowBalance);
if (repayAmount > maxClose) {
return uint(Error.TOO_MUCH_REPAY);
}
return uint(Error.NO_ERROR);
}
/**
* @notice Checks if the seizing of assets should be allowed to occur
* @param mTokenCollateral Asset which was used as collateral and will be seized
* @param mTokenBorrowed Asset which was borrowed by the borrower
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param seizeTokens The number of collateral tokens to seize
*/
function seizeAllowed(
address mTokenCollateral,
address mTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external override returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!seizeGuardianPaused, "seize is paused");
// Shh - currently unused
seizeTokens;
if (!markets[mTokenCollateral].isListed || !markets[mTokenBorrowed].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
if (MToken(mTokenCollateral).moartroller() != MToken(mTokenBorrowed).moartroller()) {
return uint(Error.MOARTROLLER_MISMATCH);
}
// Keep the flywheel moving
updateMoarSupplyIndex(mTokenCollateral);
distributeSupplierMoar(mTokenCollateral, borrower);
distributeSupplierMoar(mTokenCollateral, liquidator);
return uint(Error.NO_ERROR);
}
/**
* @notice Checks if the account should be allowed to transfer tokens in the given market
* @param mToken The market to verify the transfer against
* @param src The account which sources the tokens
* @param dst The account which receives the tokens
* @param transferTokens The number of mTokens to transfer
* @return 0 if the transfer is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function transferAllowed(address mToken, address src, address dst, uint transferTokens) external override returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!transferGuardianPaused, "transfer is paused");
// Currently the only consideration is whether or not
// the src is allowed to redeem this many tokens
uint allowed = redeemAllowedInternal(mToken, src, transferTokens);
if (allowed != uint(Error.NO_ERROR)) {
return allowed;
}
// Keep the flywheel moving
updateMoarSupplyIndex(mToken);
distributeSupplierMoar(mToken, src);
distributeSupplierMoar(mToken, dst);
return uint(Error.NO_ERROR);
}
/*** Liquidity/Liquidation Calculations ***/
/**
* @notice Determine the current account liquidity wrt collateral requirements
* @return (possible error code (semi-opaque),
account liquidity in excess of collateral requirements,
* account shortfall below collateral requirements)
*/
function getAccountLiquidity(address account) public view returns (uint, uint, uint) {
(Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, MToken(0), 0, 0);
return (uint(err), liquidity, shortfall);
}
/**
* @notice Determine the current account liquidity wrt collateral requirements
* @return (possible error code,
account liquidity in excess of collateral requirements,
* account shortfall below collateral requirements)
*/
function getAccountLiquidityInternal(address account) internal view returns (Error, uint, uint) {
return getHypotheticalAccountLiquidityInternal(account, MToken(0), 0, 0);
}
/**
* @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed
* @param mTokenModify The market to hypothetically redeem/borrow in
* @param account The account to determine liquidity for
* @param redeemTokens The number of tokens to hypothetically redeem
* @param borrowAmount The amount of underlying to hypothetically borrow
* @return (possible error code (semi-opaque),
hypothetical account liquidity in excess of collateral requirements,
* hypothetical account shortfall below collateral requirements)
*/
function getHypotheticalAccountLiquidity(
address account,
address mTokenModify,
uint redeemTokens,
uint borrowAmount) public view returns (uint, uint, uint) {
(Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, MToken(mTokenModify), redeemTokens, borrowAmount);
return (uint(err), liquidity, shortfall);
}
/**
* @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed
* @param mTokenModify The market to hypothetically redeem/borrow in
* @param account The account to determine liquidity for
* @param redeemTokens The number of tokens to hypothetically redeem
* @param borrowAmount The amount of underlying to hypothetically borrow
* @dev Note that we calculate the exchangeRateStored for each collateral mToken using stored data,
* without calculating accumulated interest.
* @return (possible error code,
hypothetical account liquidity in excess of collateral requirements,
* hypothetical account shortfall below collateral requirements)
*/
function getHypotheticalAccountLiquidityInternal(
address account,
MToken mTokenModify,
uint redeemTokens,
uint borrowAmount) internal view returns (Error, uint, uint) {
AccountLiquidityLocalVars memory vars; // Holds all our calculation results
uint oErr;
// For each asset the account is in
MToken[] memory assets = accountAssets[account];
for (uint i = 0; i < assets.length; i++) {
MToken asset = assets[i];
address _account = account;
// Read the balances and exchange rate from the mToken
(oErr, vars.mTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa) = asset.getAccountSnapshot(_account);
if (oErr != 0) { // semi-opaque error code, we assume NO_ERROR == 0 is invariant between upgrades
return (Error.SNAPSHOT_ERROR, 0, 0);
}
vars.collateralFactor = Exp({mantissa: markets[address(asset)].collateralFactorMantissa});
vars.exchangeRate = Exp({mantissa: vars.exchangeRateMantissa});
// Get the normalized price of the asset
vars.oraclePriceMantissa = oracle.getUnderlyingPrice(asset);
if (vars.oraclePriceMantissa == 0) {
return (Error.PRICE_ERROR, 0, 0);
}
vars.oraclePrice = mul_(Exp({mantissa: vars.oraclePriceMantissa}), 10**uint256(18 - EIP20Interface(asset.getUnderlying()).decimals()));
// Pre-compute a conversion factor from tokens -> dai (normalized price value)
vars.tokensToDenom = mul_(mul_(vars.collateralFactor, vars.exchangeRate), vars.oraclePrice);
// sumCollateral += tokensToDenom * mTokenBalance
vars.sumCollateral = mul_ScalarTruncateAddUInt(vars.tokensToDenom, vars.mTokenBalance, vars.sumCollateral);
// Protection value calculation sumCollateral += protectionValueLocked
// Mark to market value calculation sumCollateral += markToMarketValue
uint protectionValueLocked;
uint markToMarketValue;
(protectionValueLocked, markToMarketValue) = liquidityMathModel.getTotalProtectionLockedValue(LiquidityMathModelInterface.LiquidityMathArgumentsSet(asset, _account, markets[address(asset)].collateralFactorMantissa, cprotection, oracle));
if (vars.sumCollateral < mul_( protectionValueLocked, vars.collateralFactor)) {
vars.sumCollateral = 0;
} else {
vars.sumCollateral = sub_(vars.sumCollateral, mul_( protectionValueLocked, vars.collateralFactor));
}
vars.sumCollateral = add_(vars.sumCollateral, protectionValueLocked);
vars.sumCollateral = add_(vars.sumCollateral, markToMarketValue);
// sumBorrowPlusEffects += oraclePrice * borrowBalance
vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects);
// Calculate effects of interacting with mTokenModify
if (asset == mTokenModify) {
// redeem effect
// sumBorrowPlusEffects += tokensToDenom * redeemTokens
vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects);
// borrow effect
// sumBorrowPlusEffects += oraclePrice * borrowAmount
vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(vars.oraclePrice, borrowAmount, vars.sumBorrowPlusEffects);
_account = account;
}
}
// These are safe, as the underflow condition is checked first
if (vars.sumCollateral > vars.sumBorrowPlusEffects) {
return (Error.NO_ERROR, vars.sumCollateral - vars.sumBorrowPlusEffects, 0);
} else {
return (Error.NO_ERROR, 0, vars.sumBorrowPlusEffects - vars.sumCollateral);
}
}
/**
* @notice Returns the value of possible optimization left for asset
* @param asset The MToken address
* @param account The owner of asset
* @return The value of possible optimization
*/
function getMaxOptimizableValue(MToken asset, address account) public view returns(uint){
return liquidityMathModel.getMaxOptimizableValue(
LiquidityMathModelInterface.LiquidityMathArgumentsSet(
asset, account, markets[address(asset)].collateralFactorMantissa, cprotection, oracle
)
);
}
/**
* @notice Returns the value of hypothetical optimization (ignoring existing optimization used) for asset
* @param asset The MToken address
* @param account The owner of asset
* @return The amount of hypothetical optimization
*/
function getHypotheticalOptimizableValue(MToken asset, address account) public view returns(uint){
return liquidityMathModel.getHypotheticalOptimizableValue(
LiquidityMathModelInterface.LiquidityMathArgumentsSet(
asset, account, markets[address(asset)].collateralFactorMantissa, cprotection, oracle
)
);
}
function liquidateCalculateSeizeUserTokens(address mTokenBorrowed, address mTokenCollateral, uint actualRepayAmount, address account) external override view returns (uint, uint) {
return LiquidationModelInterface(liquidationModel).liquidateCalculateSeizeUserTokens(
LiquidationModelInterface.LiquidateCalculateSeizeUserTokensArgumentsSet(
oracle,
this,
mTokenBorrowed,
mTokenCollateral,
actualRepayAmount,
account,
liquidationIncentiveMantissa
)
);
}
/**
* @notice Returns the amount of a specific asset that is locked under all c-ops
* @param asset The MToken address
* @param account The owner of asset
* @return The amount of asset locked under c-ops
*/
function getUserLockedAmount(MToken asset, address account) public override view returns(uint) {
uint protectionLockedAmount;
address currency = asset.underlying();
uint256 numOfProtections = cprotection.getUserUnderlyingProtectionTokenIdByCurrencySize(account, currency);
for (uint i = 0; i < numOfProtections; i++) {
uint cProtectionId = cprotection.getUserUnderlyingProtectionTokenIdByCurrency(account, currency, i);
if(cprotection.isProtectionAlive(cProtectionId)){
protectionLockedAmount = protectionLockedAmount + cprotection.getUnderlyingProtectionLockedAmount(cProtectionId);
}
}
return protectionLockedAmount;
}
/*** Admin Functions ***/
/**
* @notice Sets a new price oracle for the moartroller
* @dev Admin function to set a new price oracle
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setPriceOracle(PriceOracle newOracle) public returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PRICE_ORACLE_OWNER_CHECK);
}
// Track the old oracle for the moartroller
PriceOracle oldOracle = oracle;
// Set moartroller's oracle to newOracle
oracle = newOracle;
// Emit NewPriceOracle(oldOracle, newOracle)
emit NewPriceOracle(oldOracle, newOracle);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets a new CProtection that is allowed to use as a collateral optimisation
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setProtection(address newCProtection) public returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PRICE_ORACLE_OWNER_CHECK);
}
MProtection oldCProtection = cprotection;
cprotection = MProtection(newCProtection);
// Emit NewPriceOracle(oldOracle, newOracle)
emit NewCProtection(oldCProtection, cprotection);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets the closeFactor used when liquidating borrows
* @dev Admin function to set closeFactor
* @param newCloseFactorMantissa New close factor, scaled by 1e18
* @return uint 0=success, otherwise a failure
*/
function _setCloseFactor(uint newCloseFactorMantissa) external returns (uint) {
// Check caller is admin
require(msg.sender == admin, "only admin can set close factor");
uint oldCloseFactorMantissa = closeFactorMantissa;
closeFactorMantissa = newCloseFactorMantissa;
emit NewCloseFactor(oldCloseFactorMantissa, closeFactorMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets the collateralFactor for a market
* @dev Admin function to set per-market collateralFactor
* @param mToken The market to set the factor on
* @param newCollateralFactorMantissa The new collateral factor, scaled by 1e18
* @return uint 0=success, otherwise a failure. (See ErrorReporter for details)
*/
function _setCollateralFactor(MToken mToken, uint newCollateralFactorMantissa) external returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_COLLATERAL_FACTOR_OWNER_CHECK);
}
// Verify market is listed
Market storage market = markets[address(mToken)];
if (!market.isListed) {
return fail(Error.MARKET_NOT_LISTED, FailureInfo.SET_COLLATERAL_FACTOR_NO_EXISTS);
}
// TODO: this check is temporary switched off. we can make exception for UNN later
// Exp memory newCollateralFactorExp = Exp({mantissa: newCollateralFactorMantissa});
//
//
// Check collateral factor <= 0.9
// Exp memory highLimit = Exp({mantissa: collateralFactorMaxMantissa});
// if (lessThanExp(highLimit, newCollateralFactorExp)) {
// return fail(Error.INVALID_COLLATERAL_FACTOR, FailureInfo.SET_COLLATERAL_FACTOR_VALIDATION);
// }
// If collateral factor != 0, fail if price == 0
if (newCollateralFactorMantissa != 0 && oracle.getUnderlyingPrice(mToken) == 0) {
return fail(Error.PRICE_ERROR, FailureInfo.SET_COLLATERAL_FACTOR_WITHOUT_PRICE);
}
// Set market's collateral factor to new collateral factor, remember old value
uint oldCollateralFactorMantissa = market.collateralFactorMantissa;
market.collateralFactorMantissa = newCollateralFactorMantissa;
// Emit event with asset, old collateral factor, and new collateral factor
emit NewCollateralFactor(mToken, oldCollateralFactorMantissa, newCollateralFactorMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets liquidationIncentive
* @dev Admin function to set liquidationIncentive
* @param newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18
* @return uint 0=success, otherwise a failure. (See ErrorReporter for details)
*/
function _setLiquidationIncentive(uint newLiquidationIncentiveMantissa) external returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_LIQUIDATION_INCENTIVE_OWNER_CHECK);
}
// Save current value for use in log
uint oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa;
// Set liquidation incentive to new incentive
liquidationIncentiveMantissa = newLiquidationIncentiveMantissa;
// Emit event with old incentive, new incentive
emit NewLiquidationIncentive(oldLiquidationIncentiveMantissa, newLiquidationIncentiveMantissa);
return uint(Error.NO_ERROR);
}
function _setRewardClaimEnabled(bool status) external returns (uint) {
// Check caller is admin
require(msg.sender == admin, "only admin can set close factor");
rewardClaimEnabled = status;
return uint(Error.NO_ERROR);
}
/**
* @notice Add the market to the markets mapping and set it as listed
* @dev Admin function to set isListed and add support for the market
* @param mToken The address of the market (token) to list
* @return uint 0=success, otherwise a failure. (See enum Error for details)
*/
function _supportMarket(MToken mToken) external returns (uint) {
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SUPPORT_MARKET_OWNER_CHECK);
}
if (markets[address(mToken)].isListed) {
return fail(Error.MARKET_ALREADY_LISTED, FailureInfo.SUPPORT_MARKET_EXISTS);
}
mToken.isMToken(); // Sanity check to make sure its really a MToken
// Note that isMoared is not in active use anymore
markets[address(mToken)] = Market({isListed: true, isMoared: false, collateralFactorMantissa: 0});
tokenAddressToMToken[address(mToken.underlying())] = mToken;
_addMarketInternal(address(mToken));
emit MarketListed(mToken);
return uint(Error.NO_ERROR);
}
function _addMarketInternal(address mToken) internal {
for (uint i = 0; i < allMarkets.length; i ++) {
require(allMarkets[i] != MToken(mToken), "market already added");
}
allMarkets.push(MToken(mToken));
}
/**
* @notice Set the given borrow caps for the given mToken markets. Borrowing that brings total borrows to or above borrow cap will revert.
* @dev Admin or borrowCapGuardian function to set the borrow caps. A borrow cap of 0 corresponds to unlimited borrowing.
* @param mTokens The addresses of the markets (tokens) to change the borrow caps for
* @param newBorrowCaps The new borrow cap values in underlying to be set. A value of 0 corresponds to unlimited borrowing.
*/
function _setMarketBorrowCaps(MToken[] calldata mTokens, uint[] calldata newBorrowCaps) external {
require(msg.sender == admin || msg.sender == borrowCapGuardian, "only admin or borrow cap guardian can set borrow caps");
uint numMarkets = mTokens.length;
uint numBorrowCaps = newBorrowCaps.length;
require(numMarkets != 0 && numMarkets == numBorrowCaps, "invalid input");
for(uint i = 0; i < numMarkets; i++) {
borrowCaps[address(mTokens[i])] = newBorrowCaps[i];
emit NewBorrowCap(mTokens[i], newBorrowCaps[i]);
}
}
/**
* @notice Admin function to change the Borrow Cap Guardian
* @param newBorrowCapGuardian The address of the new Borrow Cap Guardian
*/
function _setBorrowCapGuardian(address newBorrowCapGuardian) external {
require(msg.sender == admin, "only admin can set borrow cap guardian");
// Save current value for inclusion in log
address oldBorrowCapGuardian = borrowCapGuardian;
// Store borrowCapGuardian with value newBorrowCapGuardian
borrowCapGuardian = newBorrowCapGuardian;
// Emit NewBorrowCapGuardian(OldBorrowCapGuardian, NewBorrowCapGuardian)
emit NewBorrowCapGuardian(oldBorrowCapGuardian, newBorrowCapGuardian);
}
/**
* @notice Admin function to change the Pause Guardian
* @param newPauseGuardian The address of the new Pause Guardian
* @return uint 0=success, otherwise a failure. (See enum Error for details)
*/
function _setPauseGuardian(address newPauseGuardian) public returns (uint) {
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PAUSE_GUARDIAN_OWNER_CHECK);
}
// Save current value for inclusion in log
address oldPauseGuardian = pauseGuardian;
// Store pauseGuardian with value newPauseGuardian
pauseGuardian = newPauseGuardian;
// Emit NewPauseGuardian(OldPauseGuardian, NewPauseGuardian)
emit NewPauseGuardian(oldPauseGuardian, pauseGuardian);
return uint(Error.NO_ERROR);
}
function _setMintPaused(MToken mToken, bool state) public returns (bool) {
require(markets[address(mToken)].isListed, "cannot pause a market that is not listed");
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "only admin can unpause");
mintGuardianPaused[address(mToken)] = state;
emit ActionPausedMToken(mToken, "Mint", state);
return state;
}
function _setBorrowPaused(MToken mToken, bool state) public returns (bool) {
require(markets[address(mToken)].isListed, "cannot pause a market that is not listed");
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "only admin can unpause");
borrowGuardianPaused[address(mToken)] = state;
emit ActionPausedMToken(mToken, "Borrow", state);
return state;
}
function _setTransferPaused(bool state) public returns (bool) {
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "only admin can unpause");
transferGuardianPaused = state;
emit ActionPaused("Transfer", state);
return state;
}
function _setSeizePaused(bool state) public returns (bool) {
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "only admin can unpause");
seizeGuardianPaused = state;
emit ActionPaused("Seize", state);
return state;
}
/**
* @notice Checks caller is admin, or this contract is becoming the new implementation
*/
function adminOrInitializing() internal view returns (bool) {
return msg.sender == admin || msg.sender == moartrollerImplementation;
}
/*** MOAR Distribution ***/
/**
* @notice Set MOAR speed for a single market
* @param mToken The market whose MOAR speed to update
* @param moarSpeed New MOAR speed for market
*/
function setMoarSpeedInternal(MToken mToken, uint moarSpeed) internal {
uint currentMoarSpeed = moarSpeeds[address(mToken)];
if (currentMoarSpeed != 0) {
// note that MOAR speed could be set to 0 to halt liquidity rewards for a market
Exp memory borrowIndex = Exp({mantissa: mToken.borrowIndex()});
updateMoarSupplyIndex(address(mToken));
updateMoarBorrowIndex(address(mToken), borrowIndex);
} else if (moarSpeed != 0) {
// Add the MOAR market
Market storage market = markets[address(mToken)];
require(market.isListed == true, "MOAR market is not listed");
if (moarSupplyState[address(mToken)].index == 0 && moarSupplyState[address(mToken)].block == 0) {
moarSupplyState[address(mToken)] = MoarMarketState({
index: moarInitialIndex,
block: safe32(getBlockNumber(), "block number exceeds 32 bits")
});
}
if (moarBorrowState[address(mToken)].index == 0 && moarBorrowState[address(mToken)].block == 0) {
moarBorrowState[address(mToken)] = MoarMarketState({
index: moarInitialIndex,
block: safe32(getBlockNumber(), "block number exceeds 32 bits")
});
}
}
if (currentMoarSpeed != moarSpeed) {
moarSpeeds[address(mToken)] = moarSpeed;
emit MoarSpeedUpdated(mToken, moarSpeed);
}
}
/**
* @notice Accrue MOAR to the market by updating the supply index
* @param mToken The market whose supply index to update
*/
function updateMoarSupplyIndex(address mToken) internal {
MoarMarketState storage supplyState = moarSupplyState[mToken];
uint supplySpeed = moarSpeeds[mToken];
uint blockNumber = getBlockNumber();
uint deltaBlocks = sub_(blockNumber, uint(supplyState.block));
if (deltaBlocks > 0 && supplySpeed > 0) {
uint supplyTokens = MToken(mToken).totalSupply();
uint moarAccrued = mul_(deltaBlocks, supplySpeed);
Double memory ratio = supplyTokens > 0 ? fraction(moarAccrued, supplyTokens) : Double({mantissa: 0});
Double memory index = add_(Double({mantissa: supplyState.index}), ratio);
moarSupplyState[mToken] = MoarMarketState({
index: safe224(index.mantissa, "new index exceeds 224 bits"),
block: safe32(blockNumber, "block number exceeds 32 bits")
});
} else if (deltaBlocks > 0) {
supplyState.block = safe32(blockNumber, "block number exceeds 32 bits");
}
}
/**
* @notice Accrue MOAR to the market by updating the borrow index
* @param mToken The market whose borrow index to update
*/
function updateMoarBorrowIndex(address mToken, Exp memory marketBorrowIndex) internal {
MoarMarketState storage borrowState = moarBorrowState[mToken];
uint borrowSpeed = moarSpeeds[mToken];
uint blockNumber = getBlockNumber();
uint deltaBlocks = sub_(blockNumber, uint(borrowState.block));
if (deltaBlocks > 0 && borrowSpeed > 0) {
uint borrowAmount = div_(MToken(mToken).totalBorrows(), marketBorrowIndex);
uint moarAccrued = mul_(deltaBlocks, borrowSpeed);
Double memory ratio = borrowAmount > 0 ? fraction(moarAccrued, borrowAmount) : Double({mantissa: 0});
Double memory index = add_(Double({mantissa: borrowState.index}), ratio);
moarBorrowState[mToken] = MoarMarketState({
index: safe224(index.mantissa, "new index exceeds 224 bits"),
block: safe32(blockNumber, "block number exceeds 32 bits")
});
} else if (deltaBlocks > 0) {
borrowState.block = safe32(blockNumber, "block number exceeds 32 bits");
}
}
/**
* @notice Calculate MOAR accrued by a supplier and possibly transfer it to them
* @param mToken The market in which the supplier is interacting
* @param supplier The address of the supplier to distribute MOAR to
*/
function distributeSupplierMoar(address mToken, address supplier) internal {
MoarMarketState storage supplyState = moarSupplyState[mToken];
Double memory supplyIndex = Double({mantissa: supplyState.index});
Double memory supplierIndex = Double({mantissa: moarSupplierIndex[mToken][supplier]});
moarSupplierIndex[mToken][supplier] = supplyIndex.mantissa;
if (supplierIndex.mantissa == 0 && supplyIndex.mantissa > 0) {
supplierIndex.mantissa = moarInitialIndex;
}
Double memory deltaIndex = sub_(supplyIndex, supplierIndex);
uint supplierTokens = MToken(mToken).balanceOf(supplier);
uint supplierDelta = mul_(supplierTokens, deltaIndex);
uint supplierAccrued = add_(moarAccrued[supplier], supplierDelta);
moarAccrued[supplier] = supplierAccrued;
emit DistributedSupplierMoar(MToken(mToken), supplier, supplierDelta, supplyIndex.mantissa);
}
/**
* @notice Calculate MOAR accrued by a borrower and possibly transfer it to them
* @dev Borrowers will not begin to accrue until after the first interaction with the protocol.
* @param mToken The market in which the borrower is interacting
* @param borrower The address of the borrower to distribute MOAR to
*/
function distributeBorrowerMoar(address mToken, address borrower, Exp memory marketBorrowIndex) internal {
MoarMarketState storage borrowState = moarBorrowState[mToken];
Double memory borrowIndex = Double({mantissa: borrowState.index});
Double memory borrowerIndex = Double({mantissa: moarBorrowerIndex[mToken][borrower]});
moarBorrowerIndex[mToken][borrower] = borrowIndex.mantissa;
if (borrowerIndex.mantissa > 0) {
Double memory deltaIndex = sub_(borrowIndex, borrowerIndex);
uint borrowerAmount = div_(MToken(mToken).borrowBalanceStored(borrower), marketBorrowIndex);
uint borrowerDelta = mul_(borrowerAmount, deltaIndex);
uint borrowerAccrued = add_(moarAccrued[borrower], borrowerDelta);
moarAccrued[borrower] = borrowerAccrued;
emit DistributedBorrowerMoar(MToken(mToken), borrower, borrowerDelta, borrowIndex.mantissa);
}
}
/**
* @notice Calculate additional accrued MOAR for a contributor since last accrual
* @param contributor The address to calculate contributor rewards for
*/
function updateContributorRewards(address contributor) public {
uint moarSpeed = moarContributorSpeeds[contributor];
uint blockNumber = getBlockNumber();
uint deltaBlocks = sub_(blockNumber, lastContributorBlock[contributor]);
if (deltaBlocks > 0 && moarSpeed > 0) {
uint newAccrued = mul_(deltaBlocks, moarSpeed);
uint contributorAccrued = add_(moarAccrued[contributor], newAccrued);
moarAccrued[contributor] = contributorAccrued;
lastContributorBlock[contributor] = blockNumber;
}
}
/**
* @notice Claim all the MOAR accrued by holder in all markets
* @param holder The address to claim MOAR for
*/
function claimMoarReward(address holder) public {
return claimMoar(holder, allMarkets);
}
/**
* @notice Claim all the MOAR accrued by holder in the specified markets
* @param holder The address to claim MOAR for
* @param mTokens The list of markets to claim MOAR in
*/
function claimMoar(address holder, MToken[] memory mTokens) public {
address[] memory holders = new address[](1);
holders[0] = holder;
claimMoar(holders, mTokens, true, true);
}
/**
* @notice Claim all MOAR accrued by the holders
* @param holders The addresses to claim MOAR for
* @param mTokens The list of markets to claim MOAR in
* @param borrowers Whether or not to claim MOAR earned by borrowing
* @param suppliers Whether or not to claim MOAR earned by supplying
*/
function claimMoar(address[] memory holders, MToken[] memory mTokens, bool borrowers, bool suppliers) public {
require(rewardClaimEnabled, "reward claim is disabled");
for (uint i = 0; i < mTokens.length; i++) {
MToken mToken = mTokens[i];
require(markets[address(mToken)].isListed, "market must be listed");
if (borrowers == true) {
Exp memory borrowIndex = Exp({mantissa: mToken.borrowIndex()});
updateMoarBorrowIndex(address(mToken), borrowIndex);
for (uint j = 0; j < holders.length; j++) {
distributeBorrowerMoar(address(mToken), holders[j], borrowIndex);
moarAccrued[holders[j]] = grantMoarInternal(holders[j], moarAccrued[holders[j]]);
}
}
if (suppliers == true) {
updateMoarSupplyIndex(address(mToken));
for (uint j = 0; j < holders.length; j++) {
distributeSupplierMoar(address(mToken), holders[j]);
moarAccrued[holders[j]] = grantMoarInternal(holders[j], moarAccrued[holders[j]]);
}
}
}
}
/**
* @notice Transfer MOAR to the user
* @dev Note: If there is not enough MOAR, we do not perform the transfer all.
* @param user The address of the user to transfer MOAR to
* @param amount The amount of MOAR to (possibly) transfer
* @return The amount of MOAR which was NOT transferred to the user
*/
function grantMoarInternal(address user, uint amount) internal returns (uint) {
EIP20Interface moar = EIP20Interface(getMoarAddress());
uint moarRemaining = moar.balanceOf(address(this));
if (amount > 0 && amount <= moarRemaining) {
moar.approve(mProxy, amount);
MProxyInterface(mProxy).proxyClaimReward(getMoarAddress(), user, amount);
return 0;
}
return amount;
}
/*** MOAR Distribution Admin ***/
/**
* @notice Transfer MOAR to the recipient
* @dev Note: If there is not enough MOAR, we do not perform the transfer all.
* @param recipient The address of the recipient to transfer MOAR to
* @param amount The amount of MOAR to (possibly) transfer
*/
function _grantMoar(address recipient, uint amount) public {
require(adminOrInitializing(), "only admin can grant MOAR");
uint amountLeft = grantMoarInternal(recipient, amount);
require(amountLeft == 0, "insufficient MOAR for grant");
emit MoarGranted(recipient, amount);
}
/**
* @notice Set MOAR speed for a single market
* @param mToken The market whose MOAR speed to update
* @param moarSpeed New MOAR speed for market
*/
function _setMoarSpeed(MToken mToken, uint moarSpeed) public {
require(adminOrInitializing(), "only admin can set MOAR speed");
setMoarSpeedInternal(mToken, moarSpeed);
}
/**
* @notice Set MOAR speed for a single contributor
* @param contributor The contributor whose MOAR speed to update
* @param moarSpeed New MOAR speed for contributor
*/
function _setContributorMoarSpeed(address contributor, uint moarSpeed) public {
require(adminOrInitializing(), "only admin can set MOAR speed");
// note that MOAR speed could be set to 0 to halt liquidity rewards for a contributor
updateContributorRewards(contributor);
if (moarSpeed == 0) {
// release storage
delete lastContributorBlock[contributor];
} else {
lastContributorBlock[contributor] = getBlockNumber();
}
moarContributorSpeeds[contributor] = moarSpeed;
emit ContributorMoarSpeedUpdated(contributor, moarSpeed);
}
/**
* @notice Set liquidity math model implementation
* @param mathModel the math model implementation
*/
function _setLiquidityMathModel(LiquidityMathModelInterface mathModel) public {
require(msg.sender == admin, "only admin can set liquidity math model implementation");
LiquidityMathModelInterface oldLiquidityMathModel = liquidityMathModel;
liquidityMathModel = mathModel;
emit NewLiquidityMathModel(address(oldLiquidityMathModel), address(liquidityMathModel));
}
/**
* @notice Set liquidation model implementation
* @param newLiquidationModel the liquidation model implementation
*/
function _setLiquidationModel(LiquidationModelInterface newLiquidationModel) public {
require(msg.sender == admin, "only admin can set liquidation model implementation");
LiquidationModelInterface oldLiquidationModel = liquidationModel;
liquidationModel = newLiquidationModel;
emit NewLiquidationModel(address(oldLiquidationModel), address(liquidationModel));
}
function _setMoarToken(address moarTokenAddress) public {
require(msg.sender == admin, "only admin can set MOAR token address");
moarToken = moarTokenAddress;
}
function _setMProxy(address mProxyAddress) public {
require(msg.sender == admin, "only admin can set MProxy address");
mProxy = mProxyAddress;
}
/**
* @notice Add new privileged address
* @param privilegedAddress address to add
*/
function _addPrivilegedAddress(address privilegedAddress) public {
require(msg.sender == admin, "only admin can set liquidity math model implementation");
privilegedAddresses[privilegedAddress] = 1;
}
/**
* @notice Remove privileged address
* @param privilegedAddress address to remove
*/
function _removePrivilegedAddress(address privilegedAddress) public {
require(msg.sender == admin, "only admin can set liquidity math model implementation");
delete privilegedAddresses[privilegedAddress];
}
/**
* @notice Check if address if privileged
* @param privilegedAddress address to check
*/
function isPrivilegedAddress(address privilegedAddress) public view returns (bool) {
return privilegedAddresses[privilegedAddress] == 1;
}
/**
* @notice Return all of the markets
* @dev The automatic getter may be used to access an individual market.
* @return The list of market addresses
*/
function getAllMarkets() public view returns (MToken[] memory) {
return allMarkets;
}
function getBlockNumber() public view returns (uint) {
return block.number;
}
/**
* @notice Return the address of the MOAR token
* @return The address of MOAR
*/
function getMoarAddress() public view returns (address) {
return moarToken;
}
function getContractVersion() external override pure returns(string memory){
return "V1";
}
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.6.12;
import "./Interfaces/PriceOracle.sol";
import "./CErc20.sol";
/**
* Temporary simple price feed
*/
contract SimplePriceOracle is PriceOracle {
/// @notice Indicator that this is a PriceOracle contract (for inspection)
bool public constant isPriceOracle = true;
mapping(address => uint) prices;
event PricePosted(address asset, uint previousPriceMantissa, uint requestedPriceMantissa, uint newPriceMantissa);
function getUnderlyingPrice(MToken mToken) public override view returns (uint) {
if (compareStrings(mToken.symbol(), "mDAI")) {
return 1e18;
} else {
return prices[address(MErc20(address(mToken)).underlying())];
}
}
function setUnderlyingPrice(MToken mToken, uint underlyingPriceMantissa) public {
address asset = address(MErc20(address(mToken)).underlying());
emit PricePosted(asset, prices[asset], underlyingPriceMantissa, underlyingPriceMantissa);
prices[asset] = underlyingPriceMantissa;
}
function setDirectPrice(address asset, uint price) public {
emit PricePosted(asset, prices[asset], price, price);
prices[asset] = price;
}
// v1 price oracle interface for use as backing of proxy
function assetPrices(address asset) external view returns (uint) {
return prices[asset];
}
function compareStrings(string memory a, string memory b) internal pure returns (bool) {
return (keccak256(abi.encodePacked((a))) == keccak256(abi.encodePacked((b))));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
import "./Interfaces/CopMappingInterface.sol";
import "./Interfaces/Versionable.sol";
import "./Moartroller.sol";
import "./Utils/ExponentialNoError.sol";
import "./Utils/ErrorReporter.sol";
import "./Utils/AssetHelpers.sol";
import "./MToken.sol";
import "./Interfaces/EIP20Interface.sol";
import "./Utils/SafeEIP20.sol";
/**
* @title MOAR's MProtection Contract
* @notice Collateral optimization ERC-721 wrapper
* @author MOAR
*/
contract MProtection is ERC721Upgradeable, OwnableUpgradeable, ExponentialNoError, AssetHelpers, Versionable {
using Counters for Counters.Counter;
using EnumerableSet for EnumerableSet.UintSet;
/**
* @notice Event emitted when new MProtection token is minted
*/
event Mint(address minter, uint tokenId, uint underlyingTokenId, address asset, uint amount, uint strikePrice, uint expirationTime);
/**
* @notice Event emitted when MProtection token is redeemed
*/
event Redeem(address redeemer, uint tokenId, uint underlyingTokenId);
/**
* @notice Event emitted when MProtection token changes its locked value
*/
event LockValue(uint tokenId, uint underlyingTokenId, uint optimizationValue);
/**
* @notice Event emitted when maturity window parameter is changed
*/
event MaturityWindowUpdated(uint newMaturityWindow);
Counters.Counter private _tokenIds;
address private _copMappingAddress;
address private _moartrollerAddress;
mapping (uint256 => uint256) private _underlyingProtectionTokensMapping;
mapping (uint256 => uint256) private _underlyingProtectionLockedValue;
mapping (address => mapping (address => EnumerableSet.UintSet)) private _protectionCurrencyMapping;
uint256 public _maturityWindow;
struct ProtectionMappedData{
address pool;
address underlyingAsset;
uint256 amount;
uint256 strike;
uint256 premium;
uint256 lockedValue;
uint256 totalValue;
uint issueTime;
uint expirationTime;
bool isProtectionAlive;
}
/**
* @notice Constructor for MProtection contract
* @param copMappingAddress The address of data mapper for C-OP
* @param moartrollerAddress The address of the Moartroller
*/
function initialize(address copMappingAddress, address moartrollerAddress) public initializer {
__Ownable_init();
__ERC721_init("c-uUNN OC-Protection", "c-uUNN");
_copMappingAddress = copMappingAddress;
_moartrollerAddress = moartrollerAddress;
_setMaturityWindow(10800); // 3 hours default
}
/**
* @notice Returns C-OP mapping contract
*/
function copMapping() private view returns (CopMappingInterface){
return CopMappingInterface(_copMappingAddress);
}
/**
* @notice Mint new MProtection token
* @param underlyingTokenId Id of C-OP token that will be deposited
* @return ID of minted MProtection token
*/
function mint(uint256 underlyingTokenId) public returns (uint256)
{
return mintFor(underlyingTokenId, msg.sender);
}
/**
* @notice Mint new MProtection token for specified address
* @param underlyingTokenId Id of C-OP token that will be deposited
* @param receiver Address that will receive minted Mprotection token
* @return ID of minted MProtection token
*/
function mintFor(uint256 underlyingTokenId, address receiver) public returns (uint256)
{
CopMappingInterface copMappingInstance = copMapping();
ERC721Upgradeable(copMappingInstance.getTokenAddress()).transferFrom(msg.sender, address(this), underlyingTokenId);
_tokenIds.increment();
uint256 newItemId = _tokenIds.current();
_mint(receiver, newItemId);
addUProtectionIndexes(receiver, newItemId, underlyingTokenId);
emit Mint(
receiver,
newItemId,
underlyingTokenId,
copMappingInstance.getUnderlyingAsset(underlyingTokenId),
copMappingInstance.getUnderlyingAmount(underlyingTokenId),
copMappingInstance.getUnderlyingStrikePrice(underlyingTokenId),
copMappingInstance.getUnderlyingDeadline(underlyingTokenId)
);
return newItemId;
}
/**
* @notice Redeem C-OP token
* @param tokenId Id of MProtection token that will be withdrawn
* @return ID of redeemed C-OP token
*/
function redeem(uint256 tokenId) external returns (uint256) {
require(_isApprovedOrOwner(_msgSender(), tokenId), "cuUNN: caller is not owner nor approved");
uint256 underlyingTokenId = getUnderlyingProtectionTokenId(tokenId);
ERC721Upgradeable(copMapping().getTokenAddress()).transferFrom(address(this), msg.sender, underlyingTokenId);
removeProtectionIndexes(tokenId);
_burn(tokenId);
emit Redeem(msg.sender, tokenId, underlyingTokenId);
return underlyingTokenId;
}
/**
* @notice Returns set of C-OP data
* @param tokenId Id of MProtection token
* @return ProtectionMappedData struct filled with C-OP data
*/
function getMappedProtectionData(uint256 tokenId) public view returns (ProtectionMappedData memory){
ProtectionMappedData memory data;
(address pool, uint256 amount, uint256 strike, uint256 premium, uint issueTime , uint expirationTime) = getProtectionData(tokenId);
data = ProtectionMappedData(pool, getUnderlyingAsset(tokenId), amount, strike, premium, getUnderlyingProtectionLockedValue(tokenId), getUnderlyingProtectionTotalValue(tokenId), issueTime, expirationTime, isProtectionAlive(tokenId));
return data;
}
/**
* @notice Returns underlying token ID
* @param tokenId Id of MProtection token
*/
function getUnderlyingProtectionTokenId(uint256 tokenId) public view returns (uint256){
return _underlyingProtectionTokensMapping[tokenId];
}
/**
* @notice Returns size of C-OPs filtered by asset address
* @param owner Address of wallet holding C-OPs
* @param currency Address of asset used to filter C-OPs
*/
function getUserUnderlyingProtectionTokenIdByCurrencySize(address owner, address currency) public view returns (uint256){
return _protectionCurrencyMapping[owner][currency].length();
}
/**
* @notice Returns list of C-OP IDs filtered by asset address
* @param owner Address of wallet holding C-OPs
* @param currency Address of asset used to filter C-OPs
*/
function getUserUnderlyingProtectionTokenIdByCurrency(address owner, address currency, uint256 index) public view returns (uint256){
return _protectionCurrencyMapping[owner][currency].at(index);
}
/**
* @notice Checks if address is owner of MProtection
* @param owner Address of potential owner to check
* @param tokenId ID of MProtection to check
*/
function isUserProtection(address owner, uint256 tokenId) public view returns(bool) {
if(Moartroller(_moartrollerAddress).isPrivilegedAddress(msg.sender)){
return true;
}
return owner == ownerOf(tokenId);
}
/**
* @notice Checks if MProtection is stil alive
* @param tokenId ID of MProtection to check
*/
function isProtectionAlive(uint256 tokenId) public view returns(bool) {
uint256 deadline = getUnderlyingDeadline(tokenId);
return (deadline - _maturityWindow) > now;
}
/**
* @notice Creates appropriate indexes for C-OP
* @param owner C-OP owner address
* @param tokenId ID of MProtection
* @param underlyingTokenId ID of C-OP
*/
function addUProtectionIndexes(address owner, uint256 tokenId, uint256 underlyingTokenId) private{
address currency = copMapping().getUnderlyingAsset(underlyingTokenId);
_underlyingProtectionTokensMapping[tokenId] = underlyingTokenId;
_protectionCurrencyMapping[owner][currency].add(tokenId);
}
/**
* @notice Remove indexes for C-OP
* @param tokenId ID of MProtection
*/
function removeProtectionIndexes(uint256 tokenId) private{
address owner = ownerOf(tokenId);
address currency = getUnderlyingAsset(tokenId);
_underlyingProtectionTokensMapping[tokenId] = 0;
_protectionCurrencyMapping[owner][currency].remove(tokenId);
}
/**
* @notice Returns C-OP total value
* @param tokenId ID of MProtection
*/
function getUnderlyingProtectionTotalValue(uint256 tokenId) public view returns(uint256){
address underlyingAsset = getUnderlyingAsset(tokenId);
uint256 assetDecimalsMantissa = getAssetDecimalsMantissa(underlyingAsset);
return div_(
mul_(
getUnderlyingStrikePrice(tokenId),
getUnderlyingAmount(tokenId)
),
assetDecimalsMantissa
);
}
/**
* @notice Returns C-OP locked value
* @param tokenId ID of MProtection
*/
function getUnderlyingProtectionLockedValue(uint256 tokenId) public view returns(uint256){
return _underlyingProtectionLockedValue[tokenId];
}
/**
* @notice get the amount of underlying asset that is locked
* @param tokenId CProtection tokenId
* @return amount locked
*/
function getUnderlyingProtectionLockedAmount(uint256 tokenId) public view returns(uint256){
address underlyingAsset = getUnderlyingAsset(tokenId);
uint256 assetDecimalsMantissa = getAssetDecimalsMantissa(underlyingAsset);
// calculates total protection value
uint256 protectionValue = div_(
mul_(
getUnderlyingAmount(tokenId),
getUnderlyingStrikePrice(tokenId)
),
assetDecimalsMantissa
);
// return value is lockedValue / totalValue * amount
return div_(
mul_(
getUnderlyingAmount(tokenId),
div_(
mul_(
_underlyingProtectionLockedValue[tokenId],
1e18
),
protectionValue
)
),
1e18
);
}
/**
* @notice Locks the given protection value as collateral optimization
* @param tokenId The MProtection token id
* @param value The value in stablecoin of protection to be locked as collateral optimization. 0 = max available optimization
* @return locked protection value
* TODO: convert semantic errors to standarized error codes
*/
function lockProtectionValue(uint256 tokenId, uint value) external returns(uint) {
//check if the protection belongs to the caller
require(isUserProtection(msg.sender, tokenId), "ERROR: CALLER IS NOT THE OWNER OF PROTECTION");
address currency = getUnderlyingAsset(tokenId);
Moartroller moartroller = Moartroller(_moartrollerAddress);
MToken mToken = moartroller.tokenAddressToMToken(currency);
require(moartroller.oracle().getUnderlyingPrice(mToken) <= getUnderlyingStrikePrice(tokenId), "ERROR: C-OP STRIKE PRICE IS LOWER THAN ASSET SPOT PRICE");
uint protectionTotalValue = getUnderlyingProtectionTotalValue(tokenId);
uint maxOptimizableValue = moartroller.getMaxOptimizableValue(mToken, ownerOf(tokenId));
// add protection locked value if any
uint protectionLockedValue = getUnderlyingProtectionLockedValue(tokenId);
if ( protectionLockedValue > 0) {
maxOptimizableValue = add_(maxOptimizableValue, protectionLockedValue);
}
uint valueToLock;
if (value != 0) {
// check if lock value is at most max optimizable value
require(value <= maxOptimizableValue, "ERROR: VALUE TO BE LOCKED EXCEEDS ALLOWED OPTIMIZATION VALUE");
// check if lock value is at most protection total value
require( value <= protectionTotalValue, "ERROR: VALUE TO BE LOCKED EXCEEDS PROTECTION TOTAL VALUE");
valueToLock = value;
} else {
// if we want to lock maximum protection value let's lock the value that is at most max optimizable value
if (protectionTotalValue > maxOptimizableValue) {
valueToLock = maxOptimizableValue;
} else {
valueToLock = protectionTotalValue;
}
}
_underlyingProtectionLockedValue[tokenId] = valueToLock;
emit LockValue(tokenId, getUnderlyingProtectionTokenId(tokenId), valueToLock);
return valueToLock;
}
function _setCopMapping(address newMapping) public onlyOwner {
_copMappingAddress = newMapping;
}
function _setMoartroller(address newMoartroller) public onlyOwner {
_moartrollerAddress = newMoartroller;
}
function _setMaturityWindow(uint256 maturityWindow) public onlyOwner {
emit MaturityWindowUpdated(maturityWindow);
_maturityWindow = maturityWindow;
}
// MAPPINGS
function getProtectionData(uint256 tokenId) public view returns (address, uint256, uint256, uint256, uint, uint){
uint256 underlyingTokenId = getUnderlyingProtectionTokenId(tokenId);
return copMapping().getProtectionData(underlyingTokenId);
}
function getUnderlyingAsset(uint256 tokenId) public view returns (address){
uint256 underlyingTokenId = getUnderlyingProtectionTokenId(tokenId);
return copMapping().getUnderlyingAsset(underlyingTokenId);
}
function getUnderlyingAmount(uint256 tokenId) public view returns (uint256){
uint256 underlyingTokenId = getUnderlyingProtectionTokenId(tokenId);
return copMapping().getUnderlyingAmount(underlyingTokenId);
}
function getUnderlyingStrikePrice(uint256 tokenId) public view returns (uint){
uint256 underlyingTokenId = getUnderlyingProtectionTokenId(tokenId);
return copMapping().getUnderlyingStrikePrice(underlyingTokenId);
}
function getUnderlyingDeadline(uint256 tokenId) public view returns (uint){
uint256 underlyingTokenId = getUnderlyingProtectionTokenId(tokenId);
return copMapping().getUnderlyingDeadline(underlyingTokenId);
}
function getContractVersion() external override pure returns(string memory){
return "V1";
}
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.6.12;
import "../MToken.sol";
interface PriceOracle {
/**
* @notice Get the underlying price of a mToken asset
* @param mToken The mToken to get the underlying price of
* @return The underlying asset price mantissa (scaled by 1e18).
* Zero means the price is unavailable.
*/
function getUnderlyingPrice(MToken mToken) external view returns (uint);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
import "./CarefulMath.sol";
import "./ExponentialNoError.sol";
/**
* @title Exponential module for storing fixed-precision decimals
* @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);
}
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.6.12;
/**
* @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 balance The balance
*/
function balanceOf(address owner) external view returns (uint256);
/**
* @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 success Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 amount) external returns (bool);
/**
* @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 success Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint256 amount) external returns (bool);
/**
* @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 success Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @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 remaining The number of tokens allowed to be spent (-1 means infinite)
*/
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.6.12;
import "./Moartroller.sol";
import "./AbstractInterestRateModel.sol";
abstract contract MTokenStorage {
/**
* @dev Guard variable for re-entrancy checks
*/
bool internal _notEntered;
/**
* @dev EIP-20 token name for this token
*/
string public name;
/**
* @dev EIP-20 token symbol for this token
*/
string public symbol;
/**
* @dev EIP-20 token decimals for this token
*/
uint8 public decimals;
/**
* @notice Underlying asset for this MToken
*/
address public underlying;
/**
* @dev Maximum borrow rate that can ever be applied (.0005% / block)
*/
uint internal borrowRateMaxMantissa;
/**
* @dev Maximum fraction of interest that can be set aside for reserves
*/
uint internal reserveFactorMaxMantissa;
/**
* @dev Administrator for this contract
*/
address payable public admin;
/**
* @dev Pending administrator for this contract
*/
address payable public pendingAdmin;
/**
* @dev Contract which oversees inter-mToken operations
*/
Moartroller public moartroller;
/**
* @dev Model which tells what the current interest rate should be
*/
AbstractInterestRateModel public interestRateModel;
/**
* @dev Initial exchange rate used when minting the first MTokens (used when totalSupply = 0)
*/
uint internal initialExchangeRateMantissa;
/**
* @dev Fraction of interest currently set aside for reserves
*/
uint public reserveFactorMantissa;
/**
* @dev Fraction of reserves currently set aside for other usage
*/
uint public reserveSplitFactorMantissa;
/**
* @dev Block number that interest was last accrued at
*/
uint public accrualBlockNumber;
/**
* @dev Accumulator of the total earned interest rate since the opening of the market
*/
uint public borrowIndex;
/**
* @dev Total amount of outstanding borrows of the underlying in this market
*/
uint public totalBorrows;
/**
* @dev Total amount of reserves of the underlying held in this market
*/
uint public totalReserves;
/**
* @dev Total number of tokens in circulation
*/
uint public totalSupply;
/**
* @dev The Maximum Protection Moarosition (MPC) factor for collateral optimisation, default: 50% = 5000
*/
uint public maxProtectionComposition;
/**
* @dev The Maximum Protection Moarosition (MPC) mantissa, default: 1e5
*/
uint public maxProtectionCompositionMantissa;
/**
* @dev Official record of token balances for each account
*/
mapping (address => uint) internal accountTokens;
/**
* @dev Approved token transfer amounts on behalf of others
*/
mapping (address => mapping (address => uint)) internal transferAllowances;
struct ProtectionUsage {
uint256 protectionValueUsed;
}
/**
* @dev 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;
mapping (uint256 => ProtectionUsage) protectionsUsed;
}
struct AccrueInterestTempStorage{
uint interestAccumulated;
uint reservesAdded;
uint splitedReserves_1;
uint splitedReserves_2;
uint totalBorrowsNew;
uint totalReservesNew;
uint borrowIndexNew;
}
/**
* @dev Mapping of account addresses to outstanding borrow balances
*/
mapping(address => BorrowSnapshot) public accountBorrows;
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.6.12;
import "./EIP20Interface.sol";
interface MTokenInterface {
/*** User contract ***/
function transfer(address dst, uint256 amount) external returns (bool);
function transferFrom(address src, address dst, uint256 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 getCash() external view returns (uint);
function seize(address liquidator, address borrower, uint seizeTokens) external returns (uint);
function getUnderlying() external view returns(address);
function sweepToken(EIP20Interface token) external;
/*** Admin Functions ***/
function _setPendingAdmin(address payable newPendingAdmin) external returns (uint);
function _acceptAdmin() external returns (uint);
function _setReserveFactor(uint newReserveFactorMantissa) external returns (uint);
function _reduceReserves(uint reduceAmount) external returns (uint);
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.6.12;
interface MProxyInterface {
function proxyClaimReward(address asset, address recipient, uint amount) external;
function proxySplitReserves(address asset, uint amount) external;
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.6.12;
import "./Interfaces/InterestRateModelInterface.sol";
abstract contract AbstractInterestRateModel is InterestRateModelInterface {
/// @notice Indicator that this is an InterestRateModel contract (for inspection)
bool public constant isInterestRateModel = true;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
/**
* @title Careful Math
* @author MOAR
* @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);
}
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.6.12;
import "../MToken.sol";
import "../Utils/ExponentialNoError.sol";
interface MoartrollerInterface {
/**
* @dev Local vars for avoiding stack-depth limits in calculating account liquidity.
* Note that `mTokenBalance` is the number of mTokens the account owns in the market,
* whereas `borrowBalance` is the amount of underlying that the account has borrowed.
*/
struct AccountLiquidityLocalVars {
uint sumCollateral;
uint sumBorrowPlusEffects;
uint mTokenBalance;
uint borrowBalance;
uint exchangeRateMantissa;
uint oraclePriceMantissa;
ExponentialNoError.Exp collateralFactor;
ExponentialNoError.Exp exchangeRate;
ExponentialNoError.Exp oraclePrice;
ExponentialNoError.Exp tokensToDenom;
}
/*** Assets You Are In ***/
function enterMarkets(address[] calldata mTokens) external returns (uint[] memory);
function exitMarket(address mToken) external returns (uint);
/*** Policy Hooks ***/
function mintAllowed(address mToken, address minter, uint mintAmount) external returns (uint);
function redeemAllowed(address mToken, address redeemer, uint redeemTokens) external returns (uint);
function redeemVerify(address mToken, address redeemer, uint redeemAmount, uint redeemTokens) external;
function borrowAllowed(address mToken, address borrower, uint borrowAmount) external returns (uint);
function repayBorrowAllowed(
address mToken,
address payer,
address borrower,
uint repayAmount) external returns (uint);
function liquidateBorrowAllowed(
address mTokenBorrowed,
address mTokenCollateral,
address liquidator,
address borrower,
uint repayAmount) external returns (uint);
function seizeAllowed(
address mTokenCollateral,
address mTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external returns (uint);
function transferAllowed(address mToken, address src, address dst, uint transferTokens) external returns (uint);
/*** Liquidity/Liquidation Calculations ***/
function liquidateCalculateSeizeUserTokens(
address mTokenBorrowed,
address mTokenCollateral,
uint repayAmount,
address account) external view returns (uint, uint);
function getUserLockedAmount(MToken asset, address account) external view returns(uint);
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.6.12;
interface Versionable {
function getContractVersion() external pure returns (string memory);
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.6.12;
import "./MToken.sol";
import "./Interfaces/PriceOracle.sol";
import "./Interfaces/LiquidityMathModelInterface.sol";
import "./Interfaces/LiquidationModelInterface.sol";
import "./MProtection.sol";
abstract contract UnitrollerAdminStorage {
/**
* @dev Administrator for this contract
*/
address public admin;
/**
* @dev Pending administrator for this contract
*/
address public pendingAdmin;
/**
* @dev Active brains of Unitroller
*/
address public moartrollerImplementation;
/**
* @dev Pending brains of Unitroller
*/
address public pendingMoartrollerImplementation;
}
contract MoartrollerV1Storage is UnitrollerAdminStorage {
/**
* @dev Oracle which gives the price of any given asset
*/
PriceOracle public oracle;
/**
* @dev Multiplier used to calculate the maximum repayAmount when liquidating a borrow
*/
uint public closeFactorMantissa;
/**
* @dev Multiplier representing the discount on collateral that a liquidator receives
*/
uint public liquidationIncentiveMantissa;
/**
* @dev Max number of assets a single account can participate in (borrow or use as collateral)
*/
uint public maxAssets;
/**
* @dev Per-account mapping of "assets you are in", capped by maxAssets
*/
mapping(address => MToken[]) public accountAssets;
}
contract MoartrollerV2Storage is MoartrollerV1Storage {
struct Market {
// Whether or not this market is listed
bool isListed;
// Multiplier representing the most one can borrow against their collateral in this market.
// For instance, 0.9 to allow borrowing 90% of collateral value.
// Must be between 0 and 1, and stored as a mantissa.
uint collateralFactorMantissa;
// Per-market mapping of "accounts in this asset"
mapping(address => bool) accountMembership;
// Whether or not this market receives MOAR
bool isMoared;
}
/**
* @dev Official mapping of mTokens -> Market metadata
* @dev Used e.g. to determine if a market is supported
*/
mapping(address => Market) public markets;
/**
* @dev The Pause Guardian can pause certain actions as a safety mechanism.
* Actions which allow users to remove their own assets cannot be paused.
* Liquidation / seizing / transfer can only be paused globally, not by market.
*/
address public pauseGuardian;
bool public _mintGuardianPaused;
bool public _borrowGuardianPaused;
bool public transferGuardianPaused;
bool public seizeGuardianPaused;
mapping(address => bool) public mintGuardianPaused;
mapping(address => bool) public borrowGuardianPaused;
}
contract MoartrollerV3Storage is MoartrollerV2Storage {
struct MoarMarketState {
// The market's last updated moarBorrowIndex or moarSupplyIndex
uint224 index;
// The block number the index was last updated at
uint32 block;
}
/// @dev A list of all markets
MToken[] public allMarkets;
/// @dev The rate at which the flywheel distributes MOAR, per block
uint public moarRate;
/// @dev The portion of moarRate that each market currently receives
mapping(address => uint) public moarSpeeds;
/// @dev The MOAR market supply state for each market
mapping(address => MoarMarketState) public moarSupplyState;
/// @dev The MOAR market borrow state for each market
mapping(address => MoarMarketState) public moarBorrowState;
/// @dev The MOAR borrow index for each market for each supplier as of the last time they accrued MOAR
mapping(address => mapping(address => uint)) public moarSupplierIndex;
/// @dev The MOAR borrow index for each market for each borrower as of the last time they accrued MOAR
mapping(address => mapping(address => uint)) public moarBorrowerIndex;
/// @dev The MOAR accrued but not yet transferred to each user
mapping(address => uint) public moarAccrued;
}
contract MoartrollerV4Storage is MoartrollerV3Storage {
// @dev The borrowCapGuardian can set borrowCaps to any number for any market. Lowering the borrow cap could disable borrowing on the given market.
address public borrowCapGuardian;
// @dev Borrow caps enforced by borrowAllowed for each mToken address. Defaults to zero which corresponds to unlimited borrowing.
mapping(address => uint) public borrowCaps;
}
contract MoartrollerV5Storage is MoartrollerV4Storage {
/// @dev The portion of MOAR that each contributor receives per block
mapping(address => uint) public moarContributorSpeeds;
/// @dev Last block at which a contributor's MOAR rewards have been allocated
mapping(address => uint) public lastContributorBlock;
}
contract MoartrollerV6Storage is MoartrollerV5Storage {
/**
* @dev Moar token address
*/
address public moarToken;
/**
* @dev MProxy address
*/
address public mProxy;
/**
* @dev CProtection contract which can be used for collateral optimisation
*/
MProtection public cprotection;
/**
* @dev Mapping for basic token address to mToken
*/
mapping(address => MToken) public tokenAddressToMToken;
/**
* @dev Math model for liquidity calculation
*/
LiquidityMathModelInterface public liquidityMathModel;
/**
* @dev Liquidation model for liquidation related functions
*/
LiquidationModelInterface public liquidationModel;
/**
* @dev List of addresses with privileged access
*/
mapping(address => uint) public privilegedAddresses;
/**
* @dev Determines if reward claim feature is enabled
*/
bool public rewardClaimEnabled;
}
// Copyright (c) 2020 The UNION Protocol Foundation
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
// import "hardhat/console.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/GSN/Context.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
/**
* @title UNION Protocol Governance Token
* @dev Implementation of the basic standard token.
*/
contract UnionGovernanceToken is AccessControl, IERC20 {
using Address for address;
using SafeMath for uint256;
using EnumerableSet for EnumerableSet.AddressSet;
/**
* @notice Struct for marking number of votes from a given block
* @member from
* @member votes
*/
struct VotingCheckpoint {
uint256 from;
uint256 votes;
}
/**
* @notice Struct for locked tokens
* @member amount
* @member releaseTime
* @member votable
*/
struct LockedTokens{
uint amount;
uint releaseTime;
bool votable;
}
/**
* @notice Struct for EIP712 Domain
* @member name
* @member version
* @member chainId
* @member verifyingContract
* @member salt
*/
struct EIP712Domain {
string name;
string version;
uint256 chainId;
address verifyingContract;
bytes32 salt;
}
/**
* @notice Struct for EIP712 VotingDelegate call
* @member owner
* @member delegate
* @member nonce
* @member expirationTime
*/
struct VotingDelegate {
address owner;
address delegate;
uint256 nonce;
uint256 expirationTime;
}
/**
* @notice Struct for EIP712 Permit call
* @member owner
* @member spender
* @member value
* @member nonce
* @member deadline
*/
struct Permit {
address owner;
address spender;
uint256 value;
uint256 nonce;
uint256 deadline;
}
/**
* @notice Vote Delegation Events
*/
event VotingDelegateChanged(address indexed _owner, address indexed _fromDelegate, address indexed _toDelegate);
event VotingDelegateRemoved(address indexed _owner);
/**
* @notice Vote Balance Events
* Emmitted when a delegate account's vote balance changes at the time of a written checkpoint
*/
event VoteBalanceChanged(address indexed _account, uint256 _oldBalance, uint256 _newBalance);
/**
* @notice Transfer/Allocator Events
*/
event TransferStatusChanged(bool _newTransferStatus);
/**
* @notice Reversion Events
*/
event ReversionStatusChanged(bool _newReversionSetting);
/**
* @notice EIP-20 Approval event
*/
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
/**
* @notice EIP-20 Transfer event
*/
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Burn(address indexed _from, uint256 _value);
event AddressPermitted(address indexed _account);
event AddressRestricted(address indexed _account);
/**
* @dev AccessControl recognized roles
*/
bytes32 public constant ROLE_ADMIN = keccak256("ROLE_ADMIN");
bytes32 public constant ROLE_ALLOCATE = keccak256("ROLE_ALLOCATE");
bytes32 public constant ROLE_GOVERN = keccak256("ROLE_GOVERN");
bytes32 public constant ROLE_MINT = keccak256("ROLE_MINT");
bytes32 public constant ROLE_LOCK = keccak256("ROLE_LOCK");
bytes32 public constant ROLE_TRUSTED = keccak256("ROLE_TRUSTED");
bytes32 public constant ROLE_TEST = keccak256("ROLE_TEST");
bytes32 public constant EIP712DOMAIN_TYPEHASH = keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract,bytes32 salt)"
);
bytes32 public constant DELEGATE_TYPEHASH = keccak256(
"DelegateVote(address owner,address delegate,uint256 nonce,uint256 expirationTime)"
);
//keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
address private constant BURN_ADDRESS = address(0);
address public UPGT_CONTRACT_ADDRESS;
/**
* @dev hashes to support EIP-712 signing and validating, EIP712DOMAIN_SEPARATOR is set at time of contract instantiation and token minting.
*/
bytes32 public immutable EIP712DOMAIN_SEPARATOR;
/**
* @dev EIP-20 token name
*/
string public name = "UNION Protocol Governance Token";
/**
* @dev EIP-20 token symbol
*/
string public symbol = "UNN";
/**
* @dev EIP-20 token decimals
*/
uint8 public decimals = 18;
/**
* @dev Contract version
*/
string public constant version = '0.0.1';
/**
* @dev Initial amount of tokens
*/
uint256 private uint256_initialSupply = 100000000000 * 10**18;
/**
* @dev Total amount of tokens
*/
uint256 private uint256_totalSupply;
/**
* @dev Chain id
*/
uint256 private uint256_chain_id;
/**
* @dev general transfer restricted as function of public sale not complete
*/
bool private b_canTransfer = false;
/**
* @dev private variable that determines if failed EIP-20 functions revert() or return false. Reversion short-circuits the return from these functions.
*/
bool private b_revert = false; //false allows false return values
/**
* @dev Locked destinations list
*/
mapping(address => bool) private m_lockedDestinations;
/**
* @dev EIP-20 allowance and balance maps
*/
mapping(address => mapping(address => uint256)) private m_allowances;
mapping(address => uint256) private m_balances;
mapping(address => LockedTokens[]) private m_lockedBalances;
/**
* @dev nonces used by accounts to this contract for signing and validating signatures under EIP-712
*/
mapping(address => uint256) private m_nonces;
/**
* @dev delegated account may for off-line vote delegation
*/
mapping(address => address) private m_delegatedAccounts;
/**
* @dev delegated account inverse map is needed to live calculate voting power
*/
mapping(address => EnumerableSet.AddressSet) private m_delegatedAccountsInverseMap;
/**
* @dev indexed mapping of vote checkpoints for each account
*/
mapping(address => mapping(uint256 => VotingCheckpoint)) private m_votingCheckpoints;
/**
* @dev mapping of account addrresses to voting checkpoints
*/
mapping(address => uint256) private m_accountVotingCheckpoints;
/**
* @dev Contructor for the token
* @param _owner address of token contract owner
* @param _initialSupply of tokens generated by this contract
* Sets Transfer the total suppply to the owner.
* Sets default admin role to the owner.
* Sets ROLE_ALLOCATE to the owner.
* Sets ROLE_GOVERN to the owner.
* Sets ROLE_MINT to the owner.
* Sets EIP 712 Domain Separator.
*/
constructor(address _owner, uint256 _initialSupply) public {
//set internal contract references
UPGT_CONTRACT_ADDRESS = address(this);
//setup roles using AccessControl
_setupRole(DEFAULT_ADMIN_ROLE, _owner);
_setupRole(ROLE_ADMIN, _owner);
_setupRole(ROLE_ADMIN, _msgSender());
_setupRole(ROLE_ALLOCATE, _owner);
_setupRole(ROLE_ALLOCATE, _msgSender());
_setupRole(ROLE_TRUSTED, _owner);
_setupRole(ROLE_TRUSTED, _msgSender());
_setupRole(ROLE_GOVERN, _owner);
_setupRole(ROLE_MINT, _owner);
_setupRole(ROLE_LOCK, _owner);
_setupRole(ROLE_TEST, _owner);
m_balances[_owner] = _initialSupply;
uint256_totalSupply = _initialSupply;
b_canTransfer = false;
uint256_chain_id = _getChainId();
EIP712DOMAIN_SEPARATOR = _hash(EIP712Domain({
name : name,
version : version,
chainId : uint256_chain_id,
verifyingContract : address(this),
salt : keccak256(abi.encodePacked(name))
}
));
emit Transfer(BURN_ADDRESS, _owner, uint256_totalSupply);
}
/**
* @dev Sets transfer status to lock token transfer
* @param _canTransfer value can be true or false.
* disables transfer when set to false and enables transfer when true
* Only a member of ADMIN role can call to change transfer status
*/
function setCanTransfer(bool _canTransfer) public {
if(hasRole(ROLE_ADMIN, _msgSender())){
b_canTransfer = _canTransfer;
emit TransferStatusChanged(_canTransfer);
}
}
/**
* @dev Gets status of token transfer lock
* @return true or false status of whether the token can be transfered
*/
function getCanTransfer() public view returns (bool) {
return b_canTransfer;
}
/**
* @dev Sets transfer reversion status to either return false or throw on error
* @param _reversion value can be true or false.
* disables return of false values for transfer failures when set to false and enables transfer-related exceptions when true
* Only a member of ADMIN role can call to change transfer reversion status
*/
function setReversion(bool _reversion) public {
if(hasRole(ROLE_ADMIN, _msgSender()) ||
hasRole(ROLE_TEST, _msgSender())
) {
b_revert = _reversion;
emit ReversionStatusChanged(_reversion);
}
}
/**
* @dev Gets status of token transfer reversion
* @return true or false status of whether the token transfer failures return false or are reverted
*/
function getReversion() public view returns (bool) {
return b_revert;
}
/**
* @dev retrieve current chain id
* @return chain id
*/
function getChainId() public pure returns (uint256) {
return _getChainId();
}
/**
* @dev Retrieve current chain id
* @return chain id
*/
function _getChainId() internal pure returns (uint256) {
uint256 id;
assembly {
id := chainid()
}
return id;
}
/**
* @dev Retrieve total supply of tokens
* @return uint256 total supply of tokens
*/
function totalSupply() public view override returns (uint256) {
return uint256_totalSupply;
}
/**
* Balance related functions
*/
/**
* @dev Retrieve balance of a specified account
* @param _account address of account holding balance
* @return uint256 balance of the specified account address
*/
function balanceOf(address _account) public view override returns (uint256) {
return m_balances[_account].add(_calculateReleasedBalance(_account));
}
/**
* @dev Retrieve locked balance of a specified account
* @param _account address of account holding locked balance
* @return uint256 locked balance of the specified account address
*/
function lockedBalanceOf(address _account) public view returns (uint256) {
return _calculateLockedBalance(_account);
}
/**
* @dev Retrieve lenght of locked balance array for specific address
* @param _account address of account holding locked balance
* @return uint256 locked balance array lenght
*/
function getLockedTokensListSize(address _account) public view returns (uint256){
require(_msgSender() == _account || hasRole(ROLE_ADMIN, _msgSender()) || hasRole(ROLE_TRUSTED, _msgSender()), "UPGT_ERROR: insufficient permissions");
return m_lockedBalances[_account].length;
}
/**
* @dev Retrieve locked tokens struct from locked balance array for specific address
* @param _account address of account holding locked tokens
* @param _index index in array with locked tokens position
* @return amount of locked tokens
* @return releaseTime descibes time when tokens will be unlocked
* @return votable flag is describing votability of tokens
*/
function getLockedTokens(address _account, uint256 _index) public view returns (uint256 amount, uint256 releaseTime, bool votable){
require(_msgSender() == _account || hasRole(ROLE_ADMIN, _msgSender()) || hasRole(ROLE_TRUSTED, _msgSender()), "UPGT_ERROR: insufficient permissions");
require(_index < m_lockedBalances[_account].length, "UPGT_ERROR: LockedTokens position doesn't exist on given index");
LockedTokens storage lockedTokens = m_lockedBalances[_account][_index];
return (lockedTokens.amount, lockedTokens.releaseTime, lockedTokens.votable);
}
/**
* @dev Calculates locked balance of a specified account
* @param _account address of account holding locked balance
* @return uint256 locked balance of the specified account address
*/
function _calculateLockedBalance(address _account) private view returns (uint256) {
uint256 lockedBalance = 0;
for (uint i=0; i<m_lockedBalances[_account].length; i++) {
if(m_lockedBalances[_account][i].releaseTime > block.timestamp){
lockedBalance = lockedBalance.add(m_lockedBalances[_account][i].amount);
}
}
return lockedBalance;
}
/**
* @dev Calculates released balance of a specified account
* @param _account address of account holding released balance
* @return uint256 released balance of the specified account address
*/
function _calculateReleasedBalance(address _account) private view returns (uint256) {
uint256 releasedBalance = 0;
for (uint i=0; i<m_lockedBalances[_account].length; i++) {
if(m_lockedBalances[_account][i].releaseTime <= block.timestamp){
releasedBalance = releasedBalance.add(m_lockedBalances[_account][i].amount);
}
}
return releasedBalance;
}
/**
* @dev Calculates locked votable balance of a specified account
* @param _account address of account holding locked votable balance
* @return uint256 locked votable balance of the specified account address
*/
function _calculateLockedVotableBalance(address _account) private view returns (uint256) {
uint256 lockedVotableBalance = 0;
for (uint i=0; i<m_lockedBalances[_account].length; i++) {
if(m_lockedBalances[_account][i].votable == true){
lockedVotableBalance = lockedVotableBalance.add(m_lockedBalances[_account][i].amount);
}
}
return lockedVotableBalance;
}
/**
* @dev Moves released balance to normal balance for a specified account
* @param _account address of account holding released balance
*/
function _moveReleasedBalance(address _account) internal virtual{
uint256 releasedToMove = 0;
for (uint i=0; i<m_lockedBalances[_account].length; i++) {
if(m_lockedBalances[_account][i].releaseTime <= block.timestamp){
releasedToMove = releasedToMove.add(m_lockedBalances[_account][i].amount);
m_lockedBalances[_account][i] = m_lockedBalances[_account][m_lockedBalances[_account].length - 1];
m_lockedBalances[_account].pop();
}
}
m_balances[_account] = m_balances[_account].add(releasedToMove);
}
/**
* Allowance related functinons
*/
/**
* @dev Retrieve the spending allowance for a token holder by a specified account
* @param _owner Token account holder
* @param _spender Account given allowance
* @return uint256 allowance value
*/
function allowance(address _owner, address _spender) public override virtual view returns (uint256) {
return m_allowances[_owner][_spender];
}
/**
* @dev Message sender approval to spend for a specified amount
* @param _spender address of party approved to spend
* @param _value amount of the approval
* @return boolean success status
* public wrapper for _approve, _owner is msg.sender
*/
function approve(address _spender, uint256 _value) public override returns (bool) {
bool success = _approveUNN(_msgSender(), _spender, _value);
if(!success && b_revert){
revert("UPGT_ERROR: APPROVE ERROR");
}
return success;
}
/**
* @dev Token owner approval of amount for specified spender
* @param _owner address of party that owns the tokens being granted approval for spending
* @param _spender address of party that is granted approval for spending
* @param _value amount approved for spending
* @return boolean approval status
* if _spender allownace for a given _owner is greater than 0,
* increaseAllowance/decreaseAllowance should be used to prevent a race condition whereby the spender is able to spend the total value of both the old and new allowance. _spender cannot be burn or this governance token contract address. Addresses github.com/ethereum/EIPs/issues738
*/
function _approveUNN(address _owner, address _spender, uint256 _value) internal returns (bool) {
bool retval = false;
if(_spender != BURN_ADDRESS &&
_spender != UPGT_CONTRACT_ADDRESS &&
(m_allowances[_owner][_spender] == 0 || _value == 0)
){
m_allowances[_owner][_spender] = _value;
emit Approval(_owner, _spender, _value);
retval = true;
}
return retval;
}
/**
* @dev Increase spender allowance by specified incremental value
* @param _spender address of party that is granted approval for spending
* @param _addedValue specified incremental increase
* @return boolean increaseAllowance status
* public wrapper for _increaseAllowance, _owner restricted to msg.sender
*/
function increaseAllowance(address _spender, uint256 _addedValue) public returns (bool) {
bool success = _increaseAllowanceUNN(_msgSender(), _spender, _addedValue);
if(!success && b_revert){
revert("UPGT_ERROR: INCREASE ALLOWANCE ERROR");
}
return success;
}
/**
* @dev Allow owner to increase spender allowance by specified incremental value
* @param _owner address of the token owner
* @param _spender address of the token spender
* @param _addedValue specified incremental increase
* @return boolean return value status
* increase the number of tokens that an _owner provides as allowance to a _spender-- does not requrire the number of tokens allowed to be set first to 0. _spender cannot be either burn or this goverance token contract address.
*/
function _increaseAllowanceUNN(address _owner, address _spender, uint256 _addedValue) internal returns (bool) {
bool retval = false;
if(_spender != BURN_ADDRESS &&
_spender != UPGT_CONTRACT_ADDRESS &&
_addedValue > 0
){
m_allowances[_owner][_spender] = m_allowances[_owner][_spender].add(_addedValue);
retval = true;
emit Approval(_owner, _spender, m_allowances[_owner][_spender]);
}
return retval;
}
/**
* @dev Decrease spender allowance by specified incremental value
* @param _spender address of party that is granted approval for spending
* @param _subtractedValue specified incremental decrease
* @return boolean success status
* public wrapper for _decreaseAllowance, _owner restricted to msg.sender
*/
//public wrapper for _decreaseAllowance, _owner restricted to msg.sender
function decreaseAllowance(address _spender, uint256 _subtractedValue) public returns (bool) {
bool success = _decreaseAllowanceUNN(_msgSender(), _spender, _subtractedValue);
if(!success && b_revert){
revert("UPGT_ERROR: DECREASE ALLOWANCE ERROR");
}
return success;
}
/**
* @dev Allow owner to decrease spender allowance by specified incremental value
* @param _owner address of the token owner
* @param _spender address of the token spender
* @param _subtractedValue specified incremental decrease
* @return boolean return value status
* decrease the number of tokens than an _owner provdes as allowance to a _spender. A _spender cannot have a negative allowance. Does not require existing allowance to be set first to 0. _spender cannot be burn or this governance token contract address.
*/
function _decreaseAllowanceUNN(address _owner, address _spender, uint256 _subtractedValue) internal returns (bool) {
bool retval = false;
if(_spender != BURN_ADDRESS &&
_spender != UPGT_CONTRACT_ADDRESS &&
_subtractedValue > 0 &&
m_allowances[_owner][_spender] >= _subtractedValue
){
m_allowances[_owner][_spender] = m_allowances[_owner][_spender].sub(_subtractedValue);
retval = true;
emit Approval(_owner, _spender, m_allowances[_owner][_spender]);
}
return retval;
}
/**
* LockedDestination related functions
*/
/**
* @dev Adds address as a designated destination for tokens when locked for allocation only
* @param _address Address of approved desitnation for movement during lock
* @return success in setting address as eligible for transfer independent of token lock status
*/
function setAsEligibleLockedDestination(address _address) public returns (bool) {
bool retVal = false;
if(hasRole(ROLE_ADMIN, _msgSender())){
m_lockedDestinations[_address] = true;
retVal = true;
}
return retVal;
}
/**
* @dev removes desitnation as eligible for transfer
* @param _address address being removed
*/
function removeEligibleLockedDestination(address _address) public {
if(hasRole(ROLE_ADMIN, _msgSender())){
require(_address != BURN_ADDRESS, "UPGT_ERROR: address cannot be burn address");
delete(m_lockedDestinations[_address]);
}
}
/**
* @dev checks whether a destination is eligible as recipient of transfer independent of token lock status
* @param _address address being checked
* @return whether desitnation is locked
*/
function checkEligibleLockedDesination(address _address) public view returns (bool) {
return m_lockedDestinations[_address];
}
/**
* @dev Adds address as a designated allocator that can move tokens when they are locked
* @param _address Address receiving the role of ROLE_ALLOCATE
* @return success as true or false
*/
function setAsAllocator(address _address) public returns (bool) {
bool retVal = false;
if(hasRole(ROLE_ADMIN, _msgSender())){
grantRole(ROLE_ALLOCATE, _address);
retVal = true;
}
return retVal;
}
/**
* @dev Removes address as a designated allocator that can move tokens when they are locked
* @param _address Address being removed from the ROLE_ALLOCATE
* @return success as true or false
*/
function removeAsAllocator(address _address) public returns (bool) {
bool retVal = false;
if(hasRole(ROLE_ADMIN, _msgSender())){
if(hasRole(ROLE_ALLOCATE, _address)){
revokeRole(ROLE_ALLOCATE, _address);
retVal = true;
}
}
return retVal;
}
/**
* @dev Checks to see if an address has the role of being an allocator
* @param _address Address being checked for ROLE_ALLOCATE
* @return true or false whether the address has ROLE_ALLOCATE assigned
*/
function checkAsAllocator(address _address) public view returns (bool) {
return hasRole(ROLE_ALLOCATE, _address);
}
/**
* Transfer related functions
*/
/**
* @dev Public wrapper for transfer function to move tokens of specified value to a given address
* @param _to specified recipient
* @param _value amount being transfered to recipient
* @return status of transfer success
*/
function transfer(address _to, uint256 _value) external override returns (bool) {
bool success = _transferUNN(_msgSender(), _to, _value);
if(!success && b_revert){
revert("UPGT_ERROR: ERROR ON TRANSFER");
}
return success;
}
/**
* @dev Transfer token for a specified address, but cannot transfer tokens to either the burn or this governance contract address. Also moves voting delegates as required.
* @param _owner The address owner where transfer originates
* @param _to The address to transfer to
* @param _value The amount to be transferred
* @return status of transfer success
*/
function _transferUNN(address _owner, address _to, uint256 _value) internal returns (bool) {
bool retval = false;
if(b_canTransfer || hasRole(ROLE_ALLOCATE, _msgSender()) || checkEligibleLockedDesination(_to)) {
if(
_to != BURN_ADDRESS &&
_to != UPGT_CONTRACT_ADDRESS &&
(balanceOf(_owner) >= _value) &&
(_value >= 0)
){
_moveReleasedBalance(_owner);
m_balances[_owner] = m_balances[_owner].sub(_value);
m_balances[_to] = m_balances[_to].add(_value);
retval = true;
//need to move voting delegates with transfer of tokens
retval = retval && _moveVotingDelegates(m_delegatedAccounts[_owner], m_delegatedAccounts[_to], _value);
emit Transfer(_owner, _to, _value);
}
}
return retval;
}
/**
* @dev Public wrapper for transferAndLock function to move tokens of specified value to a given address and lock them for a period of time
* @param _to specified recipient
* @param _value amount being transfered to recipient
* @param _releaseTime time in seconds after amount will be released
* @param _votable flag which describes if locked tokens are votable or not
* @return status of transfer success
* Requires ROLE_LOCK
*/
function transferAndLock(address _to, uint256 _value, uint256 _releaseTime, bool _votable) public virtual returns (bool) {
bool retval = false;
if(hasRole(ROLE_LOCK, _msgSender())){
retval = _transferAndLock(msg.sender, _to, _value, _releaseTime, _votable);
}
if(!retval && b_revert){
revert("UPGT_ERROR: ERROR ON TRANSFER AND LOCK");
}
return retval;
}
/**
* @dev Transfers tokens of specified value to a given address and lock them for a period of time
* @param _owner The address owner where transfer originates
* @param _to specified recipient
* @param _value amount being transfered to recipient
* @param _releaseTime time in seconds after amount will be released
* @param _votable flag which describes if locked tokens are votable or not
* @return status of transfer success
*/
function _transferAndLock(address _owner, address _to, uint256 _value, uint256 _releaseTime, bool _votable) internal virtual returns (bool){
bool retval = false;
if(b_canTransfer || hasRole(ROLE_ALLOCATE, _msgSender()) || checkEligibleLockedDesination(_to)) {
if(
_to != BURN_ADDRESS &&
_to != UPGT_CONTRACT_ADDRESS &&
(balanceOf(_owner) >= _value) &&
(_value >= 0)
){
_moveReleasedBalance(_owner);
m_balances[_owner] = m_balances[_owner].sub(_value);
m_lockedBalances[_to].push(LockedTokens(_value, _releaseTime, _votable));
retval = true;
//need to move voting delegates with transfer of tokens
// retval = retval && _moveVotingDelegates(m_delegatedAccounts[_owner], m_delegatedAccounts[_to], _value);
emit Transfer(_owner, _to, _value);
}
}
return retval;
}
/**
* @dev Public wrapper for transferFrom function
* @param _owner The address to transfer from
* @param _spender cannot be the burn address
* @param _value The amount to be transferred
* @return status of transferFrom success
* _spender cannot be either this goverance token contract or burn
*/
function transferFrom(address _owner, address _spender, uint256 _value) external override returns (bool) {
bool success = _transferFromUNN(_owner, _spender, _value);
if(!success && b_revert){
revert("UPGT_ERROR: ERROR ON TRANSFER FROM");
}
return success;
}
/**
* @dev Transfer token for a specified address. _spender cannot be either this goverance token contract or burn
* @param _owner The address to transfer from
* @param _spender cannot be the burn address
* @param _value The amount to be transferred
* @return status of transferFrom success
* _spender cannot be either this goverance token contract or burn
*/
function _transferFromUNN(address _owner, address _spender, uint256 _value) internal returns (bool) {
bool retval = false;
if(b_canTransfer || hasRole(ROLE_ALLOCATE, _msgSender()) || checkEligibleLockedDesination(_spender)) {
if(
_spender != BURN_ADDRESS &&
_spender != UPGT_CONTRACT_ADDRESS &&
(balanceOf(_owner) >= _value) &&
(_value > 0) &&
(m_allowances[_owner][_msgSender()] >= _value)
){
_moveReleasedBalance(_owner);
m_balances[_owner] = m_balances[_owner].sub(_value);
m_balances[_spender] = m_balances[_spender].add(_value);
m_allowances[_owner][_msgSender()] = m_allowances[_owner][_msgSender()].sub(_value);
retval = true;
//need to move delegates that exist for this owner in line with transfer
retval = retval && _moveVotingDelegates(_owner, _spender, _value);
emit Transfer(_owner, _spender, _value);
}
}
return retval;
}
/**
* @dev Public wrapper for transferFromAndLock function to move tokens of specified value from given address to another address and lock them for a period of time
* @param _owner The address owner where transfer originates
* @param _to specified recipient
* @param _value amount being transfered to recipient
* @param _releaseTime time in seconds after amount will be released
* @param _votable flag which describes if locked tokens are votable or not
* @return status of transfer success
* Requires ROLE_LOCK
*/
function transferFromAndLock(address _owner, address _to, uint256 _value, uint256 _releaseTime, bool _votable) public virtual returns (bool) {
bool retval = false;
if(hasRole(ROLE_LOCK, _msgSender())){
retval = _transferFromAndLock(_owner, _to, _value, _releaseTime, _votable);
}
if(!retval && b_revert){
revert("UPGT_ERROR: ERROR ON TRANSFER FROM AND LOCK");
}
return retval;
}
/**
* @dev Transfers tokens of specified value from a given address to another address and lock them for a period of time
* @param _owner The address owner where transfer originates
* @param _to specified recipient
* @param _value amount being transfered to recipient
* @param _releaseTime time in seconds after amount will be released
* @param _votable flag which describes if locked tokens are votable or not
* @return status of transfer success
*/
function _transferFromAndLock(address _owner, address _to, uint256 _value, uint256 _releaseTime, bool _votable) internal returns (bool) {
bool retval = false;
if(b_canTransfer || hasRole(ROLE_ALLOCATE, _msgSender()) || checkEligibleLockedDesination(_to)) {
if(
_to != BURN_ADDRESS &&
_to != UPGT_CONTRACT_ADDRESS &&
(balanceOf(_owner) >= _value) &&
(_value > 0) &&
(m_allowances[_owner][_msgSender()] >= _value)
){
_moveReleasedBalance(_owner);
m_balances[_owner] = m_balances[_owner].sub(_value);
m_lockedBalances[_to].push(LockedTokens(_value, _releaseTime, _votable));
m_allowances[_owner][_msgSender()] = m_allowances[_owner][_msgSender()].sub(_value);
retval = true;
//need to move delegates that exist for this owner in line with transfer
// retval = retval && _moveVotingDelegates(_owner, _to, _value);
emit Transfer(_owner, _to, _value);
}
}
return retval;
}
/**
* @dev Public function to burn tokens
* @param _value number of tokens to be burned
* @return whether tokens were burned
* Only ROLE_MINTER may burn tokens
*/
function burn(uint256 _value) external returns (bool) {
bool success = _burn(_value);
if(!success && b_revert){
revert("UPGT_ERROR: FAILED TO BURN");
}
return success;
}
/**
* @dev Private function Burn tokens
* @param _value number of tokens to be burned
* @return bool whether the tokens were burned
* only a minter may burn tokens, meaning that tokens being burned must be previously send to a ROLE_MINTER wallet.
*/
function _burn(uint256 _value) internal returns (bool) {
bool retval = false;
if(hasRole(ROLE_MINT, _msgSender()) &&
(m_balances[_msgSender()] >= _value)
){
m_balances[_msgSender()] -= _value;
uint256_totalSupply = uint256_totalSupply.sub(_value);
retval = true;
emit Burn(_msgSender(), _value);
}
return retval;
}
/**
* Voting related functions
*/
/**
* @dev Public wrapper for _calculateVotingPower function which calulates voting power
* @dev voting power = balance + locked votable balance + delegations
* @return uint256 voting power
*/
function calculateVotingPower() public view returns (uint256) {
return _calculateVotingPower(_msgSender());
}
/**
* @dev Calulates voting power of specified address
* @param _account address of token holder
* @return uint256 voting power
*/
function _calculateVotingPower(address _account) private view returns (uint256) {
uint256 votingPower = m_balances[_account].add(_calculateLockedVotableBalance(_account));
for (uint i=0; i<m_delegatedAccountsInverseMap[_account].length(); i++) {
if(m_delegatedAccountsInverseMap[_account].at(i) != address(0)){
address delegatedAccount = m_delegatedAccountsInverseMap[_account].at(i);
votingPower = votingPower.add(m_balances[delegatedAccount]).add(_calculateLockedVotableBalance(delegatedAccount));
}
}
return votingPower;
}
/**
* @dev Moves a number of votes from a token holder to a designated representative
* @param _source address of token holder
* @param _destination address of voting delegate
* @param _amount of voting delegation transfered to designated representative
* @return bool whether move was successful
* Requires ROLE_TEST
*/
function moveVotingDelegates(
address _source,
address _destination,
uint256 _amount) public returns (bool) {
require(hasRole(ROLE_TEST, _msgSender()), "UPGT_ERROR: ROLE_TEST Required");
return _moveVotingDelegates(_source, _destination, _amount);
}
/**
* @dev Moves a number of votes from a token holder to a designated representative
* @param _source address of token holder
* @param _destination address of voting delegate
* @param _amount of voting delegation transfered to designated representative
* @return bool whether move was successful
*/
function _moveVotingDelegates(
address _source,
address _destination,
uint256 _amount
) internal returns (bool) {
if(_source != _destination && _amount > 0) {
if(_source != BURN_ADDRESS) {
uint256 sourceNumberOfVotingCheckpoints = m_accountVotingCheckpoints[_source];
uint256 sourceNumberOfVotingCheckpointsOriginal = (sourceNumberOfVotingCheckpoints > 0)? m_votingCheckpoints[_source][sourceNumberOfVotingCheckpoints.sub(1)].votes : 0;
if(sourceNumberOfVotingCheckpointsOriginal >= _amount) {
uint256 sourceNumberOfVotingCheckpointsNew = sourceNumberOfVotingCheckpointsOriginal.sub(_amount);
_writeVotingCheckpoint(_source, sourceNumberOfVotingCheckpoints, sourceNumberOfVotingCheckpointsOriginal, sourceNumberOfVotingCheckpointsNew);
}
}
if(_destination != BURN_ADDRESS) {
uint256 destinationNumberOfVotingCheckpoints = m_accountVotingCheckpoints[_destination];
uint256 destinationNumberOfVotingCheckpointsOriginal = (destinationNumberOfVotingCheckpoints > 0)? m_votingCheckpoints[_source][destinationNumberOfVotingCheckpoints.sub(1)].votes : 0;
uint256 destinationNumberOfVotingCheckpointsNew = destinationNumberOfVotingCheckpointsOriginal.add(_amount);
_writeVotingCheckpoint(_destination, destinationNumberOfVotingCheckpoints, destinationNumberOfVotingCheckpointsOriginal, destinationNumberOfVotingCheckpointsNew);
}
}
return true;
}
/**
* @dev Writes voting checkpoint for a given voting delegate
* @param _votingDelegate exercising votes
* @param _numberOfVotingCheckpoints number of voting checkpoints for current vote
* @param _oldVotes previous number of votes
* @param _newVotes new number of votes
* Public function for writing voting checkpoint
* Requires ROLE_TEST
*/
function writeVotingCheckpoint(
address _votingDelegate,
uint256 _numberOfVotingCheckpoints,
uint256 _oldVotes,
uint256 _newVotes) public {
require(hasRole(ROLE_TEST, _msgSender()), "UPGT_ERROR: ROLE_TEST Required");
_writeVotingCheckpoint(_votingDelegate, _numberOfVotingCheckpoints, _oldVotes, _newVotes);
}
/**
* @dev Writes voting checkpoint for a given voting delegate
* @param _votingDelegate exercising votes
* @param _numberOfVotingCheckpoints number of voting checkpoints for current vote
* @param _oldVotes previous number of votes
* @param _newVotes new number of votes
* Private function for writing voting checkpoint
*/
function _writeVotingCheckpoint(
address _votingDelegate,
uint256 _numberOfVotingCheckpoints,
uint256 _oldVotes,
uint256 _newVotes) internal {
if(_numberOfVotingCheckpoints > 0 && m_votingCheckpoints[_votingDelegate][_numberOfVotingCheckpoints.sub(1)].from == block.number) {
m_votingCheckpoints[_votingDelegate][_numberOfVotingCheckpoints-1].votes = _newVotes;
}
else {
m_votingCheckpoints[_votingDelegate][_numberOfVotingCheckpoints] = VotingCheckpoint(block.number, _newVotes);
_numberOfVotingCheckpoints = _numberOfVotingCheckpoints.add(1);
}
emit VoteBalanceChanged(_votingDelegate, _oldVotes, _newVotes);
}
/**
* @dev Calculate account votes as of a specific block
* @param _account address whose votes are counted
* @param _blockNumber from which votes are being counted
* @return number of votes counted
*/
function getVoteCountAtBlock(
address _account,
uint256 _blockNumber) public view returns (uint256) {
uint256 voteCount = 0;
if(_blockNumber < block.number) {
if(m_accountVotingCheckpoints[_account] != 0) {
if(m_votingCheckpoints[_account][m_accountVotingCheckpoints[_account].sub(1)].from <= _blockNumber) {
voteCount = m_votingCheckpoints[_account][m_accountVotingCheckpoints[_account].sub(1)].votes;
}
else if(m_votingCheckpoints[_account][0].from > _blockNumber) {
voteCount = 0;
}
else {
uint256 lower = 0;
uint256 upper = m_accountVotingCheckpoints[_account].sub(1);
while(upper > lower) {
uint256 center = upper.sub((upper.sub(lower).div(2)));
VotingCheckpoint memory votingCheckpoint = m_votingCheckpoints[_account][center];
if(votingCheckpoint.from == _blockNumber) {
voteCount = votingCheckpoint.votes;
break;
}
else if(votingCheckpoint.from < _blockNumber) {
lower = center;
}
else {
upper = center.sub(1);
}
}
}
}
}
return voteCount;
}
/**
* @dev Vote Delegation Functions
* @param _to address where message sender is assigning votes
* @return success of message sender delegating vote
* delegate function does not allow assignment to burn
*/
function delegateVote(address _to) public returns (bool) {
return _delegateVote(_msgSender(), _to);
}
/**
* @dev Delegate votes from token holder to another address
* @param _from Token holder
* @param _toDelegate Address that will be delegated to for purpose of voting
* @return success as to whether delegation has been a success
*/
function _delegateVote(
address _from,
address _toDelegate) internal returns (bool) {
bool retval = false;
if(_toDelegate != BURN_ADDRESS) {
address currentDelegate = m_delegatedAccounts[_from];
uint256 fromAccountBalance = m_balances[_from].add(_calculateLockedVotableBalance(_from));
address oldToDelegate = m_delegatedAccounts[_from];
m_delegatedAccounts[_from] = _toDelegate;
m_delegatedAccountsInverseMap[oldToDelegate].remove(_from);
if(_from != _toDelegate){
m_delegatedAccountsInverseMap[_toDelegate].add(_from);
}
retval = true;
retval = retval && _moveVotingDelegates(currentDelegate, _toDelegate, fromAccountBalance);
if(retval) {
if(_from == _toDelegate){
emit VotingDelegateRemoved(_from);
}
else{
emit VotingDelegateChanged(_from, currentDelegate, _toDelegate);
}
}
}
return retval;
}
/**
* @dev Revert voting delegate control to owner account
* @param _account The account that has delegated its vote
* @return success of reverting delegation to owner
*/
function _revertVotingDelegationToOwner(address _account) internal returns (bool) {
return _delegateVote(_account, _account);
}
/**
* @dev Used by an message sending account to recall its voting delegates
* @return success of reverting delegation to owner
*/
function recallVotingDelegate() public returns (bool) {
return _revertVotingDelegationToOwner(_msgSender());
}
/**
* @dev Retrieve the voting delegate for a specified account
* @param _account The account that has delegated its vote
*/
function getVotingDelegate(address _account) public view returns (address) {
return m_delegatedAccounts[_account];
}
/**
* EIP-712 related functions
*/
/**
* @dev EIP-712 Ethereum Typed Structured Data Hashing and Signing for Allocation Permit
* @param _owner address of token owner
* @param _spender address of designated spender
* @param _value value permitted for spend
* @param _deadline expiration of signature
* @param _ecv ECDSA v parameter
* @param _ecr ECDSA r parameter
* @param _ecs ECDSA s parameter
*/
function permit(
address _owner,
address _spender,
uint256 _value,
uint256 _deadline,
uint8 _ecv,
bytes32 _ecr,
bytes32 _ecs
) external returns (bool) {
require(block.timestamp <= _deadline, "UPGT_ERROR: wrong timestamp");
require(uint256_chain_id == _getChainId(), "UPGT_ERROR: chain_id is incorrect");
bytes32 digest = keccak256(abi.encodePacked(
"\x19\x01",
EIP712DOMAIN_SEPARATOR,
keccak256(abi.encode(PERMIT_TYPEHASH, _owner, _spender, _value, m_nonces[_owner]++, _deadline))
)
);
require(_owner == _recoverSigner(digest, _ecv, _ecr, _ecs), "UPGT_ERROR: sign does not match user");
require(_owner != BURN_ADDRESS, "UPGT_ERROR: address cannot be burn address");
return _approveUNN(_owner, _spender, _value);
}
/**
* @dev EIP-712 ETH Typed Structured Data Hashing and Signing for Delegate Vote
* @param _owner address of token owner
* @param _delegate address of voting delegate
* @param _expiretimestamp expiration of delegation signature
* @param _ecv ECDSA v parameter
* @param _ecr ECDSA r parameter
* @param _ecs ECDSA s parameter
* @ @return bool true or false depedening on whether vote was successfully delegated
*/
function delegateVoteBySignature(
address _owner,
address _delegate,
uint256 _expiretimestamp,
uint8 _ecv,
bytes32 _ecr,
bytes32 _ecs
) external returns (bool) {
require(block.timestamp <= _expiretimestamp, "UPGT_ERROR: wrong timestamp");
require(uint256_chain_id == _getChainId(), "UPGT_ERROR: chain_id is incorrect");
bytes32 digest = keccak256(abi.encodePacked(
"\x19\x01",
EIP712DOMAIN_SEPARATOR,
_hash(VotingDelegate(
{
owner : _owner,
delegate : _delegate,
nonce : m_nonces[_owner]++,
expirationTime : _expiretimestamp
})
)
)
);
require(_owner == _recoverSigner(digest, _ecv, _ecr, _ecs), "UPGT_ERROR: sign does not match user");
require(_owner!= BURN_ADDRESS, "UPGT_ERROR: address cannot be burn address");
return _delegateVote(_owner, _delegate);
}
/**
* @dev Public hash EIP712Domain struct for EIP-712
* @param _eip712Domain EIP712Domain struct
* @return bytes32 hash of _eip712Domain
* Requires ROLE_TEST
*/
function hashEIP712Domain(EIP712Domain memory _eip712Domain) public view returns (bytes32) {
require(hasRole(ROLE_TEST, _msgSender()), "UPGT_ERROR: ROLE_TEST Required");
return _hash(_eip712Domain);
}
/**
* @dev Hash Delegate struct for EIP-712
* @param _delegate VotingDelegate struct
* @return bytes32 hash of _delegate
* Requires ROLE_TEST
*/
function hashDelegate(VotingDelegate memory _delegate) public view returns (bytes32) {
require(hasRole(ROLE_TEST, _msgSender()), "UPGT_ERROR: ROLE_TEST Required");
return _hash(_delegate);
}
/**
* @dev Public hash Permit struct for EIP-712
* @param _permit Permit struct
* @return bytes32 hash of _permit
* Requires ROLE_TEST
*/
function hashPermit(Permit memory _permit) public view returns (bytes32) {
require(hasRole(ROLE_TEST, _msgSender()), "UPGT_ERROR: ROLE_TEST Required");
return _hash(_permit);
}
/**
* @param _digest signed, hashed message
* @param _ecv ECDSA v parameter
* @param _ecr ECDSA r parameter
* @param _ecs ECDSA s parameter
* @return address of the validated signer
* based on openzeppelin/contracts/cryptography/ECDSA.sol recover() function
* Requires ROLE_TEST
*/
function recoverSigner(bytes32 _digest, uint8 _ecv, bytes32 _ecr, bytes32 _ecs) public view returns (address) {
require(hasRole(ROLE_TEST, _msgSender()), "UPGT_ERROR: ROLE_TEST Required");
return _recoverSigner(_digest, _ecv, _ecr, _ecs);
}
/**
* @dev Private hash EIP712Domain struct for EIP-712
* @param _eip712Domain EIP712Domain struct
* @return bytes32 hash of _eip712Domain
*/
function _hash(EIP712Domain memory _eip712Domain) internal pure returns (bytes32) {
return keccak256(
abi.encode(
EIP712DOMAIN_TYPEHASH,
keccak256(bytes(_eip712Domain.name)),
keccak256(bytes(_eip712Domain.version)),
_eip712Domain.chainId,
_eip712Domain.verifyingContract,
_eip712Domain.salt
)
);
}
/**
* @dev Private hash Delegate struct for EIP-712
* @param _delegate VotingDelegate struct
* @return bytes32 hash of _delegate
*/
function _hash(VotingDelegate memory _delegate) internal pure returns (bytes32) {
return keccak256(
abi.encode(
DELEGATE_TYPEHASH,
_delegate.owner,
_delegate.delegate,
_delegate.nonce,
_delegate.expirationTime
)
);
}
/**
* @dev Private hash Permit struct for EIP-712
* @param _permit Permit struct
* @return bytes32 hash of _permit
*/
function _hash(Permit memory _permit) internal pure returns (bytes32) {
return keccak256(abi.encode(
PERMIT_TYPEHASH,
_permit.owner,
_permit.spender,
_permit.value,
_permit.nonce,
_permit.deadline
));
}
/**
* @dev Recover signer information from provided digest
* @param _digest signed, hashed message
* @param _ecv ECDSA v parameter
* @param _ecr ECDSA r parameter
* @param _ecs ECDSA s parameter
* @return address of the validated signer
* based on openzeppelin/contracts/cryptography/ECDSA.sol recover() function
*/
function _recoverSigner(bytes32 _digest, uint8 _ecv, bytes32 _ecr, bytes32 _ecs) internal pure returns (address) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if(uint256(_ecs) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
revert("ECDSA: invalid signature 's' value");
}
if(_ecv != 27 && _ecv != 28) {
revert("ECDSA: invalid signature 'v' value");
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(_digest, _ecv, _ecr, _ecs);
require(signer != BURN_ADDRESS, "ECDSA: invalid signature");
return signer;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../Interfaces/EIP20Interface.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/Address.sol";
/**
* @title SafeEIP20
* @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.
* This is a forked version of Openzeppelin's SafeERC20 contract but supporting
* EIP20Interface instead of Openzeppelin's IERC20
* 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 SafeEIP20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(EIP20Interface token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(EIP20Interface 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(EIP20Interface 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(EIP20Interface 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(EIP20Interface 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(EIP20Interface 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 experimental ABIEncoderV2;
import "./PriceOracle.sol";
import "./MoartrollerInterface.sol";
pragma solidity ^0.6.12;
interface LiquidationModelInterface {
function liquidateCalculateSeizeUserTokens(LiquidateCalculateSeizeUserTokensArgumentsSet memory arguments) external view returns (uint, uint);
function liquidateCalculateSeizeTokens(LiquidateCalculateSeizeUserTokensArgumentsSet memory arguments) external view returns (uint, uint);
struct LiquidateCalculateSeizeUserTokensArgumentsSet {
PriceOracle oracle;
MoartrollerInterface moartroller;
address mTokenBorrowed;
address mTokenCollateral;
uint actualRepayAmount;
address accountForLiquidation;
uint liquidationIncentiveMantissa;
}
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity >=0.4.24 <0.8.0;
import "../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.6.12;
/**
* @title MOAR's InterestRateModel Interface
* @author MOAR
*/
interface InterestRateModelInterface {
/**
* @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);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../utils/ContextUpgradeable.sol";
import "./IERC721Upgradeable.sol";
import "./IERC721MetadataUpgradeable.sol";
import "./IERC721EnumerableUpgradeable.sol";
import "./IERC721ReceiverUpgradeable.sol";
import "../../introspection/ERC165Upgradeable.sol";
import "../../math/SafeMathUpgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/EnumerableSetUpgradeable.sol";
import "../../utils/EnumerableMapUpgradeable.sol";
import "../../utils/StringsUpgradeable.sol";
import "../../proxy/Initializable.sol";
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable, IERC721EnumerableUpgradeable {
using SafeMathUpgradeable for uint256;
using AddressUpgradeable for address;
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.UintSet;
using EnumerableMapUpgradeable for EnumerableMapUpgradeable.UintToAddressMap;
using StringsUpgradeable for uint256;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
// Mapping from holder address to their (enumerable) set of owned tokens
mapping (address => EnumerableSetUpgradeable.UintSet) private _holderTokens;
// Enumerable mapping from token ids to their owners
EnumerableMapUpgradeable.UintToAddressMap private _tokenOwners;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Optional mapping for token URIs
mapping (uint256 => string) private _tokenURIs;
// Base URI
string private _baseURI;
/*
* bytes4(keccak256('balanceOf(address)')) == 0x70a08231
* bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e
* bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3
* bytes4(keccak256('getApproved(uint256)')) == 0x081812fc
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde
*
* => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^
* 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd
*/
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
/*
* bytes4(keccak256('name()')) == 0x06fdde03
* bytes4(keccak256('symbol()')) == 0x95d89b41
* bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
*
* => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f
*/
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
/*
* bytes4(keccak256('totalSupply()')) == 0x18160ddd
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59
* bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7
*
* => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63
*/
bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
function __ERC721_init(string memory name_, string memory symbol_) internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721_init_unchained(name_, symbol_);
}
function __ERC721_init_unchained(string memory name_, string memory symbol_) internal initializer {
_name = name_;
_symbol = symbol_;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721);
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _holderTokens[owner].length();
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token");
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
// If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
return string(abi.encodePacked(base, tokenId.toString()));
}
/**
* @dev Returns the base URI set via {_setBaseURI}. This will be
* automatically added as a prefix in {tokenURI} to each token's URI, or
* to the token ID if no specific URI is set for that token ID.
*/
function baseURI() public view virtual returns (string memory) {
return _baseURI;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
return _holderTokens[owner].at(index);
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
// _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds
return _tokenOwners.length();
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
(uint256 tokenId, ) = _tokenOwners.at(index);
return tokenId;
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721Upgradeable.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(_msgSender() == owner || ERC721Upgradeable.isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(address from, address to, uint256 tokenId) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _tokenOwners.contains(tokenId);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721Upgradeable.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || ERC721Upgradeable.isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
d*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual {
_mint(to, tokenId);
require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721Upgradeable.ownerOf(tokenId); // internal owner
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
_holderTokens[owner].remove(tokenId);
_tokenOwners.remove(tokenId);
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(address from, address to, uint256 tokenId) internal virtual {
require(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); // internal owner
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_holderTokens[from].remove(tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(from, to, tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Internal function to set the base URI for all token IDs. It is
* automatically added as a prefix to the value returned in {tokenURI},
* or to the token ID if {tokenURI} is empty.
*/
function _setBaseURI(string memory baseURI_) internal virtual {
_baseURI = baseURI_;
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
private returns (bool)
{
if (!to.isContract()) {
return true;
}
bytes memory returndata = to.functionCall(abi.encodeWithSelector(
IERC721ReceiverUpgradeable(to).onERC721Received.selector,
_msgSender(),
from,
tokenId,
_data
), "ERC721: transfer to non ERC721Receiver implementer");
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC721_RECEIVED);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits an {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId); // internal owner
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { }
uint256[41] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../math/SafeMath.sol";
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
* Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath}
* overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never
* directly accessed.
*/
library Counters {
using SafeMath for uint256;
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
// The {SafeMath} overflow check can be skipped here, see the comment at the top
counter._value += 1;
}
function decrement(Counter storage counter) internal {
counter._value = counter._value.sub(1);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
interface CopMappingInterface {
function getTokenAddress() external view returns (address);
function getProtectionData(uint256 underlyingTokenId) external view returns (address, uint256, uint256, uint256, uint, uint);
function getUnderlyingAsset(uint256 underlyingTokenId) external view returns (address);
function getUnderlyingAmount(uint256 underlyingTokenId) external view returns (uint256);
function getUnderlyingStrikePrice(uint256 underlyingTokenId) external view returns (uint);
function getUnderlyingDeadline(uint256 underlyingTokenId) external view returns (uint);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../proxy/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "../../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.6.2 <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.6.2 <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.6.0 <0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface 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.6.0 <0.8.0;
import "./IERC165Upgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
function __ERC165_init() internal initializer {
__ERC165_init_unchained();
}
function __ERC165_init_unchained() internal initializer {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMathUpgradeable {
/**
* @dev Returns the addition of two unsigned integers, 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.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSetUpgradeable {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(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.6.0 <0.8.0;
/**
* @dev Library for managing an enumerable variant of Solidity's
* https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`]
* type.
*
* Maps have the following properties:
*
* - Entries are added, removed, and checked for existence in constant time
* (O(1)).
* - Entries are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableMap for EnumerableMap.UintToAddressMap;
*
* // Declare a set state variable
* EnumerableMap.UintToAddressMap private myMap;
* }
* ```
*
* As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are
* supported.
*/
library EnumerableMapUpgradeable {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// The Map implementation uses private functions, and user-facing
// implementations (such as Uint256ToAddressMap) are just wrappers around
// the underlying Map.
// This means that we can only create new EnumerableMaps for types that fit
// in bytes32.
struct MapEntry {
bytes32 _key;
bytes32 _value;
}
struct Map {
// Storage of map keys and values
MapEntry[] _entries;
// Position of the entry defined by a key in the `entries` array, plus 1
// because index 0 means a key is not in the map.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) { // Equivalent to !contains(map, key)
map._entries.push(MapEntry({ _key: key, _value: value }));
// The entry is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
map._indexes[key] = map._entries.length;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function _remove(Map storage map, bytes32 key) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex != 0) { // Equivalent to contains(map, key)
// To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one
// in the array, and then remove the last entry (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._entries.length - 1;
// When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
MapEntry storage lastEntry = map._entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map._entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
map._entries.pop();
// Delete the index for the deleted slot
delete map._indexes[key];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function _contains(Map storage map, bytes32 key) private view returns (bool) {
return map._indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._entries.length;
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) {
require(map._entries.length > index, "EnumerableMap: index out of bounds");
MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/
function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) {
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key)
return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {_tryGet}.
*/
function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
// UintToAddressMap
struct UintToAddressMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) {
return _remove(map._inner, bytes32(key));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) {
return _contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(UintToAddressMap storage map) internal view returns (uint256) {
return _length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) {
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint256(key), address(uint160(uint256(value))));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*
* _Available since v3.4._
*/
function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) {
(bool success, bytes32 value) = _tryGet(map._inner, bytes32(key));
return (success, address(uint160(uint256(value))));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(UintToAddressMap storage map, uint256 key) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key)))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryGet}.
*/
function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage))));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
/**
* @dev Converts a `uint256` to its ASCII `string` representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
uint256 index = digits - 1;
temp = value;
while (temp != 0) {
buffer[index--] = bytes1(uint8(48 + temp % 10));
temp /= 10;
}
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface 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.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/EnumerableSet.sol";
import "../utils/Address.sol";
import "../utils/Context.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context {
using EnumerableSet for EnumerableSet.AddressSet;
using Address for address;
struct RoleData {
EnumerableSet.AddressSet members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view returns (bool) {
return _roles[role].members.contains(account);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view returns (uint256) {
return _roles[role].members.length();
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view returns (address) {
return _roles[role].members.at(index);
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant");
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke");
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, _roles[role].adminRole, adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/Context.sol";
// 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);
}
}
}
}
// 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: BSD-3-Clause
pragma solidity ^0.6.12;
import "./MToken.sol";
import "./Interfaces/MErc20Interface.sol";
import "./Moartroller.sol";
import "./AbstractInterestRateModel.sol";
import "./Interfaces/EIP20Interface.sol";
import "./Utils/SafeEIP20.sol";
/**
* @title MOAR's MErc20 Contract
* @notice MTokens which wrap an EIP-20 underlying
*/
contract MErc20 is MToken, MErc20Interface {
using SafeEIP20 for EIP20Interface;
/**
* @notice Initialize the new money market
* @param underlying_ The address of the underlying asset
* @param moartroller_ The address of the Moartroller
* @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 init(address underlying_,
Moartroller moartroller_,
AbstractInterestRateModel interestRateModel_,
uint initialExchangeRateMantissa_,
string memory name_,
string memory symbol_,
uint8 decimals_) public {
// MToken initialize does the bulk of the work
super.init(moartroller_, 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 mTokens 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 override returns (uint) {
(uint err,) = mintInternal(mintAmount);
return err;
}
/**
* @notice Sender redeems mTokens in exchange for the underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemTokens The number of mTokens to redeem into underlying
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeem(uint redeemTokens) external override returns (uint) {
return redeemInternal(redeemTokens);
}
/**
* @notice Sender redeems mTokens 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 override 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 override returns (uint) {
return borrowInternal(borrowAmount);
}
function borrowFor(address payable borrower, uint borrowAmount) external override returns (uint) {
return borrowForInternal(borrower, 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 override 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 override 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 mToken to be liquidated
* @param repayAmount The amount of the underlying borrowed asset to repay
* @param mTokenCollateral 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, MToken mTokenCollateral) external override returns (uint) {
(uint err,) = liquidateBorrowInternal(borrower, repayAmount, mTokenCollateral);
return err;
}
/**
* @notice A public function to sweep accidental ERC-20 transfers to this contract. Tokens are sent to admin (timelock)
* @param token The address of the ERC-20 token to sweep
*/
function sweepToken(EIP20Interface token) override external {
require(address(token) != underlying, "MErc20::sweepToken: can not sweep underlying token");
uint256 balance = token.balanceOf(address(this));
token.safeTransfer(admin, balance);
}
/**
* @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 override 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 override 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 override returns (uint) {
EIP20Interface token = EIP20Interface(underlying);
uint balanceBefore = token.balanceOf(address(this));
token.safeTransferFrom(from, address(this), amount);
// Calculate the amount that was *actually* transferred
uint balanceAfter = token.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 override {
EIP20Interface token = EIP20Interface(underlying);
token.safeTransfer(to, amount);
}
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.6.12;
import "../MToken.sol";
interface MErc20Interface {
/*** User contract ***/
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 borrowFor(address payable borrower, 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, MToken mTokenCollateral) external returns (uint);
/*** Admin Functions ***/
function _addReserves(uint addAmount) external returns (uint);
}
| Moves a number of votes from a token holder to a designated representative _source address of token holder _destination address of voting delegate _amount of voting delegation transfered to designated representative return bool whether move was successful Requires ROLE_TEST/ | function moveVotingDelegates(
address _source,
address _destination,
uint256 _amount) public returns (bool) {
require(hasRole(ROLE_TEST, _msgSender()), "UPGT_ERROR: ROLE_TEST Required");
return _moveVotingDelegates(_source, _destination, _amount);
}
| 11,818,579 |
./full_match/80001/0xc67c792c0f81F08b78ED5678a5D979e16df52eC3/sources/contracts/NasAcademyPolygonTest2.sol | Allow for token minting for an approved minter with a valid message signature. The address of the sender is hashed and signed with the server's private key and verified./ | function specialMint(
bytes32 messageHash,
bytes calldata signature
) external virtual {
require(isFirstSaleActive || isSecondSaleActive, "SALE_IS_NOT_ACTIVE");
require(msg.sender == specialMintAddress, "MINT_NOT_ALLOWED");
require(hashMessage(msg.sender) == messageHash, "MESSAGE_INVALID");
require(verifyAddressSigner(messageHash, signature), "SIGNATURE_VALIDATION_FAILED");
uint256 currentId = tokenIds.current();
if (isFirstSaleActive) {
require(currentId <= firstSaleSupply, "NOT_ENOUGH_MINTS_AVAILABLE");
require(currentId <= maxSupply, "NOT_ENOUGH_MINTS_AVAILABLE");
}
_safeMint(msg.sender, currentId);
tokenIds.increment();
if (isFirstSaleActive && (currentId == firstSaleSupply)) {
isFirstSaleActive = false;
isSecondSaleActive = false;
}
}
| 9,472,993 |
pragma solidity ^0.4.24;
/**
* @summary: CryptoRome Land ERC-998 Bottom-Up Composable NFT Contract (and additional helper contracts)
* @author: GigLabs, LLC
*/
/**
* @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 ERC721 Non-Fungible Token Standard basic interface
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
* Note: the ERC-165 identifier for this interface is 0x80ac58cd.
*/
interface ERC721 /* is ERC165 */ {
event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId);
event Approval(address indexed _tokenOwner, address indexed _approved, uint256 indexed _tokenId);
event ApprovalForAll(address indexed _tokenOwner, address indexed _operator, bool _approved);
function balanceOf(address _tokenOwner) external view returns (uint256 _balance);
function ownerOf(uint256 _tokenId) external view returns (address _tokenOwner);
function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes _data) external;
function safeTransferFrom(address _from, address _to, uint256 _tokenId) external;
function transferFrom(address _from, address _to, uint256 _tokenId) external;
function approve(address _to, uint256 _tokenId) external;
function setApprovalForAll(address _operator, bool _approved) external;
function getApproved(uint256 _tokenId) external view returns (address _operator);
function isApprovedForAll(address _tokenOwner, address _operator) external view returns (bool);
}
/**
* @notice Query if a contract implements an interface
* @dev Interface identification is specified in ERC-165. This function
* uses less than 30,000 gas.
*/
interface ERC165 {
function supportsInterface(bytes4 interfaceID) external view returns (bool);
}
interface ERC721TokenReceiver {
/**
* @notice Handle the receipt of an NFT
* @dev The ERC721 smart contract calls this function on the recipient
* after a `transfer`. This function MAY throw to revert and reject the
* transfer. Return of other than the magic value MUST result in the
* transaction being reverted.
* Note: the contract address is always the message sender.
* @param _operator The address which called `safeTransferFrom` function
* @param _from The address which previously owned the token
* @param _tokenId The NFT identifier which is being transferred
* @param _data Additional data with no specified format
* @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
* unless throwing
*/
function onERC721Received(address _operator, address _from, uint256 _tokenId, bytes _data) external returns(bytes4);
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
* Note: the ERC-165 identifier for this interface is 0x5b5e139f.
*/
interface ERC721Metadata /* is ERC721 */ {
function name() external view returns (string _name);
function symbol() external view returns (string _symbol);
function tokenURI(uint256 _tokenId) external view returns (string);
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
* Note: the ERC-165 identifier for this interface is 0x780e9d63.
*/
interface ERC721Enumerable /* is ERC721 */ {
function totalSupply() external view returns (uint256);
function tokenByIndex(uint256 _index) external view returns (uint256);
function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256);
}
/**
* @title ERC998ERC721 Bottom-Up Composable Non-Fungible Token
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-998.md
* Note: the ERC-165 identifier for this interface is 0xa1b23002
*/
interface ERC998ERC721BottomUp {
event TransferToParent(address indexed _toContract, uint256 indexed _toTokenId, uint256 _tokenId);
event TransferFromParent(address indexed _fromContract, uint256 indexed _fromTokenId, uint256 _tokenId);
function rootOwnerOf(uint256 _tokenId) public view returns (bytes32 rootOwner);
/**
* The tokenOwnerOf function gets the owner of the _tokenId which can be a user address or another ERC721 token.
* The tokenOwner address return value can be either a user address or an ERC721 contract address.
* If the tokenOwner address is a user address then parentTokenId will be 0 and should not be used or considered.
* If tokenOwner address is a user address then isParent is false, otherwise isChild is true, which means that
* tokenOwner is an ERC721 contract address and _tokenId is a child of tokenOwner and parentTokenId.
*/
function tokenOwnerOf(uint256 _tokenId) external view returns (bytes32 tokenOwner, uint256 parentTokenId, bool isParent);
// Transfers _tokenId as a child to _toContract and _toTokenId
function transferToParent(address _from, address _toContract, uint256 _toTokenId, uint256 _tokenId, bytes _data) public;
// Transfers _tokenId from a parent ERC721 token to a user address.
function transferFromParent(address _fromContract, uint256 _fromTokenId, address _to, uint256 _tokenId, bytes _data) public;
// Transfers _tokenId from a parent ERC721 token to a parent ERC721 token.
function transferAsChild(address _fromContract, uint256 _fromTokenId, address _toContract, uint256 _toTokenId, uint256 _tokenId, bytes _data) external;
}
/**
* @title ERC998ERC721 Bottom-Up Composable, optional enumerable extension
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-998.md
* Note: The ERC-165 identifier for this interface is 0x8318b539
*/
interface ERC998ERC721BottomUpEnumerable {
function totalChildTokens(address _parentContract, uint256 _parentTokenId) external view returns (uint256);
function childTokenByIndex(address _parentContract, uint256 _parentTokenId, uint256 _index) external view returns (uint256);
}
contract ERC998ERC721BottomUpToken is ERC721, ERC721Metadata, ERC721Enumerable, ERC165, ERC998ERC721BottomUp, ERC998ERC721BottomUpEnumerable {
using SafeMath for uint256;
struct TokenOwner {
address tokenOwner;
uint256 parentTokenId;
}
// return this.rootOwnerOf.selector ^ this.rootOwnerOfChild.selector ^
// this.tokenOwnerOf.selector ^ this.ownerOfChild.selector;
bytes32 constant ERC998_MAGIC_VALUE = 0xcd740db5;
// total number of tokens
uint256 internal tokenCount;
// tokenId => token owner
mapping(uint256 => TokenOwner) internal tokenIdToTokenOwner;
// Mapping from owner to list of owned token IDs
mapping(address => uint256[]) internal ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) internal ownedTokensIndex;
// root token owner address => (tokenId => approved address)
mapping(address => mapping(uint256 => address)) internal rootOwnerAndTokenIdToApprovedAddress;
// parent address => (parent tokenId => array of child tokenIds)
mapping(address => mapping(uint256 => uint256[])) internal parentToChildTokenIds;
// tokenId => position in childTokens array
mapping(uint256 => uint256) internal tokenIdToChildTokenIdsIndex;
// token owner => (operator address => bool)
mapping(address => mapping(address => bool)) internal tokenOwnerToOperators;
// Token name
string internal name_;
// Token symbol
string internal symbol_;
// Token URI
string internal tokenURIBase;
mapping(bytes4 => bool) internal supportedInterfaces;
//from zepellin ERC721Receiver.sol
//old version
bytes4 constant ERC721_RECEIVED = 0x150b7a02;
function isContract(address _addr) internal view returns (bool) {
uint256 size;
assembly {size := extcodesize(_addr)}
return size > 0;
}
constructor () public {
//ERC165
supportedInterfaces[0x01ffc9a7] = true;
//ERC721
supportedInterfaces[0x80ac58cd] = true;
//ERC721Metadata
supportedInterfaces[0x5b5e139f] = true;
//ERC721Enumerable
supportedInterfaces[0x780e9d63] = true;
//ERC998ERC721BottomUp
supportedInterfaces[0xa1b23002] = true;
//ERC998ERC721BottomUpEnumerable
supportedInterfaces[0x8318b539] = true;
}
/////////////////////////////////////////////////////////////////////////////
//
// ERC165Impl
//
/////////////////////////////////////////////////////////////////////////////
function supportsInterface(bytes4 _interfaceID) external view returns (bool) {
return supportedInterfaces[_interfaceID];
}
/////////////////////////////////////////////////////////////////////////////
//
// ERC721 implementation & ERC998 Authentication
//
/////////////////////////////////////////////////////////////////////////////
function balanceOf(address _tokenOwner) public view returns (uint256) {
require(_tokenOwner != address(0));
return ownedTokens[_tokenOwner].length;
}
// returns the immediate owner of the token
function ownerOf(uint256 _tokenId) public view returns (address) {
address tokenOwner = tokenIdToTokenOwner[_tokenId].tokenOwner;
require(tokenOwner != address(0));
return tokenOwner;
}
function transferFrom(address _from, address _to, uint256 _tokenId) external {
require(_to != address(this));
_transferFromOwnerCheck(_from, _to, _tokenId);
_transferFrom(_from, _to, _tokenId);
}
function safeTransferFrom(address _from, address _to, uint256 _tokenId) external {
_transferFromOwnerCheck(_from, _to, _tokenId);
_transferFrom(_from, _to, _tokenId);
require(_checkAndCallSafeTransfer(_from, _to, _tokenId, ""));
}
function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes _data) external {
_transferFromOwnerCheck(_from, _to, _tokenId);
_transferFrom(_from, _to, _tokenId);
require(_checkAndCallSafeTransfer(_from, _to, _tokenId, _data));
}
function _checkAndCallSafeTransfer(address _from, address _to, uint256 _tokenId, bytes _data) internal view returns (bool) {
if (!isContract(_to)) {
return true;
}
bytes4 retval = ERC721TokenReceiver(_to).onERC721Received(msg.sender, _from, _tokenId, _data);
return (retval == ERC721_RECEIVED);
}
function _transferFromOwnerCheck(address _from, address _to, uint256 _tokenId) internal {
require(_from != address(0));
require(_to != address(0));
require(tokenIdToTokenOwner[_tokenId].tokenOwner == _from);
require(tokenIdToTokenOwner[_tokenId].parentTokenId == 0);
// check child approved
address approvedAddress = rootOwnerAndTokenIdToApprovedAddress[_from][_tokenId];
if(msg.sender != _from) {
bytes32 tokenOwner;
bool callSuccess;
// 0xeadb80b8 == ownerOfChild(address,uint256)
bytes memory calldata = abi.encodeWithSelector(0xed81cdda, address(this), _tokenId);
assembly {
callSuccess := staticcall(gas, _from, add(calldata, 0x20), mload(calldata), calldata, 0x20)
if callSuccess {
tokenOwner := mload(calldata)
}
}
if(callSuccess == true) {
require(tokenOwner >> 224 != ERC998_MAGIC_VALUE);
}
require(tokenOwnerToOperators[_from][msg.sender] || approvedAddress == msg.sender);
}
// clear approval
if (approvedAddress != address(0)) {
delete rootOwnerAndTokenIdToApprovedAddress[_from][_tokenId];
emit Approval(_from, address(0), _tokenId);
}
}
function _transferFrom(address _from, address _to, uint256 _tokenId) internal {
// first remove the token from the owner list of owned tokens
uint256 lastTokenIndex = ownedTokens[_from].length.sub(1);
uint256 lastTokenId = ownedTokens[_from][lastTokenIndex];
if (lastTokenId != _tokenId) {
// replace the _tokenId in the list of ownedTokens with the
// last token id in the list. Make sure ownedTokensIndex gets updated
// with the new position of the last token id as well.
uint256 tokenIndex = ownedTokensIndex[_tokenId];
ownedTokens[_from][tokenIndex] = lastTokenId;
ownedTokensIndex[lastTokenId] = tokenIndex;
}
// resize ownedTokens array (automatically deletes the last array entry)
ownedTokens[_from].length--;
// transfer token
tokenIdToTokenOwner[_tokenId].tokenOwner = _to;
// add token to the new owner's list of owned tokens
ownedTokensIndex[_tokenId] = ownedTokens[_to].length;
ownedTokens[_to].push(_tokenId);
emit Transfer(_from, _to, _tokenId);
}
function approve(address _approved, uint256 _tokenId) external {
address tokenOwner = tokenIdToTokenOwner[_tokenId].tokenOwner;
require(tokenOwner != address(0));
address rootOwner = address(rootOwnerOf(_tokenId));
require(rootOwner == msg.sender || tokenOwnerToOperators[rootOwner][msg.sender]);
rootOwnerAndTokenIdToApprovedAddress[rootOwner][_tokenId] = _approved;
emit Approval(rootOwner, _approved, _tokenId);
}
function getApproved(uint256 _tokenId) public view returns (address) {
address rootOwner = address(rootOwnerOf(_tokenId));
return rootOwnerAndTokenIdToApprovedAddress[rootOwner][_tokenId];
}
function setApprovalForAll(address _operator, bool _approved) external {
require(_operator != address(0));
tokenOwnerToOperators[msg.sender][_operator] = _approved;
emit ApprovalForAll(msg.sender, _operator, _approved);
}
function isApprovedForAll(address _owner, address _operator) external view returns (bool) {
require(_owner != address(0));
require(_operator != address(0));
return tokenOwnerToOperators[_owner][_operator];
}
function _tokenOwnerOf(uint256 _tokenId) internal view returns (address tokenOwner, uint256 parentTokenId, bool isParent) {
tokenOwner = tokenIdToTokenOwner[_tokenId].tokenOwner;
require(tokenOwner != address(0));
parentTokenId = tokenIdToTokenOwner[_tokenId].parentTokenId;
if (parentTokenId > 0) {
isParent = true;
parentTokenId--;
}
else {
isParent = false;
}
return (tokenOwner, parentTokenId, isParent);
}
function tokenOwnerOf(uint256 _tokenId) external view returns (bytes32 tokenOwner, uint256 parentTokenId, bool isParent) {
address tokenOwnerAddress = tokenIdToTokenOwner[_tokenId].tokenOwner;
require(tokenOwnerAddress != address(0));
parentTokenId = tokenIdToTokenOwner[_tokenId].parentTokenId;
if (parentTokenId > 0) {
isParent = true;
parentTokenId--;
}
else {
isParent = false;
}
return (ERC998_MAGIC_VALUE << 224 | bytes32(tokenOwnerAddress), parentTokenId, isParent);
}
// Use Cases handled:
// Case 1: Token owner is this contract and no parent tokenId.
// Case 2: Token owner is this contract and token
// Case 3: Token owner is top-down composable
// Case 4: Token owner is an unknown contract
// Case 5: Token owner is a user
// Case 6: Token owner is a bottom-up composable
// Case 7: Token owner is ERC721 token owned by top-down token
// Case 8: Token owner is ERC721 token owned by unknown contract
// Case 9: Token owner is ERC721 token owned by user
function rootOwnerOf(uint256 _tokenId) public view returns (bytes32 rootOwner) {
address rootOwnerAddress = tokenIdToTokenOwner[_tokenId].tokenOwner;
require(rootOwnerAddress != address(0));
uint256 parentTokenId = tokenIdToTokenOwner[_tokenId].parentTokenId;
bool isParent = parentTokenId > 0;
if (isParent) {
parentTokenId--;
}
if((rootOwnerAddress == address(this))) {
do {
if(isParent == false) {
// Case 1: Token owner is this contract and no token.
// This case should not happen.
return ERC998_MAGIC_VALUE << 224 | bytes32(rootOwnerAddress);
}
else {
// Case 2: Token owner is this contract and token
(rootOwnerAddress, parentTokenId, isParent) = _tokenOwnerOf(parentTokenId);
}
} while(rootOwnerAddress == address(this));
_tokenId = parentTokenId;
}
bytes memory calldata;
bool callSuccess;
if (isParent == false) {
// success if this token is owned by a top-down token
// 0xed81cdda == rootOwnerOfChild(address, uint256)
calldata = abi.encodeWithSelector(0xed81cdda, address(this), _tokenId);
assembly {
callSuccess := staticcall(gas, rootOwnerAddress, add(calldata, 0x20), mload(calldata), calldata, 0x20)
if callSuccess {
rootOwner := mload(calldata)
}
}
if(callSuccess == true && rootOwner >> 224 == ERC998_MAGIC_VALUE) {
// Case 3: Token owner is top-down composable
return rootOwner;
}
else {
// Case 4: Token owner is an unknown contract
// Or
// Case 5: Token owner is a user
return ERC998_MAGIC_VALUE << 224 | bytes32(rootOwnerAddress);
}
}
else {
// 0x43a61a8e == rootOwnerOf(uint256)
calldata = abi.encodeWithSelector(0x43a61a8e, parentTokenId);
assembly {
callSuccess := staticcall(gas, rootOwnerAddress, add(calldata, 0x20), mload(calldata), calldata, 0x20)
if callSuccess {
rootOwner := mload(calldata)
}
}
if (callSuccess == true && rootOwner >> 224 == ERC998_MAGIC_VALUE) {
// Case 6: Token owner is a bottom-up composable
// Or
// Case 2: Token owner is top-down composable
return rootOwner;
}
else {
// token owner is ERC721
address childContract = rootOwnerAddress;
//0x6352211e == "ownerOf(uint256)"
calldata = abi.encodeWithSelector(0x6352211e, parentTokenId);
assembly {
callSuccess := staticcall(gas, rootOwnerAddress, add(calldata, 0x20), mload(calldata), calldata, 0x20)
if callSuccess {
rootOwnerAddress := mload(calldata)
}
}
require(callSuccess);
// 0xed81cdda == rootOwnerOfChild(address,uint256)
calldata = abi.encodeWithSelector(0xed81cdda, childContract, parentTokenId);
assembly {
callSuccess := staticcall(gas, rootOwnerAddress, add(calldata, 0x20), mload(calldata), calldata, 0x20)
if callSuccess {
rootOwner := mload(calldata)
}
}
if(callSuccess == true && rootOwner >> 224 == ERC998_MAGIC_VALUE) {
// Case 7: Token owner is ERC721 token owned by top-down token
return rootOwner;
}
else {
// Case 8: Token owner is ERC721 token owned by unknown contract
// Or
// Case 9: Token owner is ERC721 token owned by user
return ERC998_MAGIC_VALUE << 224 | bytes32(rootOwnerAddress);
}
}
}
}
// List of all Land Tokens assigned to an address.
function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) {
return ownedTokens[_owner];
}
/////////////////////////////////////////////////////////////////////////////
//
// ERC721MetadataImpl
//
/////////////////////////////////////////////////////////////////////////////
function tokenURI(uint256 _tokenId) external view returns (string) {
require (exists(_tokenId));
return _appendUintToString(tokenURIBase, _tokenId);
}
function name() external view returns (string) {
return name_;
}
function symbol() external view returns (string) {
return symbol_;
}
function _appendUintToString(string inStr, uint v) private pure returns (string str) {
uint maxlength = 100;
bytes memory reversed = new bytes(maxlength);
uint i = 0;
while (v != 0) {
uint remainder = v % 10;
v = v / 10;
reversed[i++] = byte(48 + remainder);
}
bytes memory inStrb = bytes(inStr);
bytes memory s = new bytes(inStrb.length + i);
uint j;
for (j = 0; j < inStrb.length; j++) {
s[j] = inStrb[j];
}
for (j = 0; j < i; j++) {
s[j + inStrb.length] = reversed[i - 1 - j];
}
str = string(s);
}
/////////////////////////////////////////////////////////////////////////////
//
// ERC721EnumerableImpl
//
/////////////////////////////////////////////////////////////////////////////
function exists(uint256 _tokenId) public view returns (bool) {
return _tokenId < tokenCount;
}
function totalSupply() external view returns (uint256) {
return tokenCount;
}
function tokenOfOwnerByIndex(address _tokenOwner, uint256 _index) external view returns (uint256 tokenId) {
require(_index < ownedTokens[_tokenOwner].length);
return ownedTokens[_tokenOwner][_index];
}
function tokenByIndex(uint256 _index) external view returns (uint256 tokenId) {
require(_index < tokenCount);
return _index;
}
function _mint(address _to, uint256 _tokenId) internal {
require (_to != address(0));
require (tokenIdToTokenOwner[_tokenId].tokenOwner == address(0));
tokenIdToTokenOwner[_tokenId].tokenOwner = _to;
ownedTokensIndex[_tokenId] = ownedTokens[_to].length;
ownedTokens[_to].push(_tokenId);
tokenCount++;
emit Transfer(address(0), _to, _tokenId);
}
/////////////////////////////////////////////////////////////////////////////
//
// ERC998 Bottom-Up implementation (extenstion of ERC-721)
//
/////////////////////////////////////////////////////////////////////////////
function _removeChild(address _fromContract, uint256 _fromTokenId, uint256 _tokenId) internal {
uint256 lastChildTokenIndex = parentToChildTokenIds[_fromContract][_fromTokenId].length - 1;
uint256 lastChildTokenId = parentToChildTokenIds[_fromContract][_fromTokenId][lastChildTokenIndex];
if (_tokenId != lastChildTokenId) {
uint256 currentChildTokenIndex = tokenIdToChildTokenIdsIndex[_tokenId];
parentToChildTokenIds[_fromContract][_fromTokenId][currentChildTokenIndex] = lastChildTokenId;
tokenIdToChildTokenIdsIndex[lastChildTokenId] = currentChildTokenIndex;
}
parentToChildTokenIds[_fromContract][_fromTokenId].length--;
}
function _transferChild(address _from, address _toContract, uint256 _toTokenId, uint256 _tokenId) internal {
tokenIdToTokenOwner[_tokenId].parentTokenId = _toTokenId.add(1);
uint256 index = parentToChildTokenIds[_toContract][_toTokenId].length;
parentToChildTokenIds[_toContract][_toTokenId].push(_tokenId);
tokenIdToChildTokenIdsIndex[_tokenId] = index;
_transferFrom(_from, _toContract, _tokenId);
require(ERC721(_toContract).ownerOf(_toTokenId) != address(0));
emit TransferToParent(_toContract, _toTokenId, _tokenId);
}
function _removeFromToken(address _fromContract, uint256 _fromTokenId, address _to, uint256 _tokenId) internal {
require(_fromContract != address(0));
require(_to != address(0));
require(tokenIdToTokenOwner[_tokenId].tokenOwner == _fromContract);
uint256 parentTokenId = tokenIdToTokenOwner[_tokenId].parentTokenId;
require(parentTokenId != 0);
require(parentTokenId - 1 == _fromTokenId);
// authenticate
address rootOwner = address(rootOwnerOf(_tokenId));
address approvedAddress = rootOwnerAndTokenIdToApprovedAddress[rootOwner][_tokenId];
require(rootOwner == msg.sender || tokenOwnerToOperators[rootOwner][msg.sender] || approvedAddress == msg.sender);
// clear approval
if (approvedAddress != address(0)) {
delete rootOwnerAndTokenIdToApprovedAddress[rootOwner][_tokenId];
emit Approval(rootOwner, address(0), _tokenId);
}
tokenIdToTokenOwner[_tokenId].parentTokenId = 0;
_removeChild(_fromContract, _fromTokenId, _tokenId);
emit TransferFromParent(_fromContract, _fromTokenId, _tokenId);
}
function transferFromParent(address _fromContract, uint256 _fromTokenId, address _to, uint256 _tokenId, bytes _data) public {
_removeFromToken(_fromContract, _fromTokenId, _to, _tokenId);
delete tokenIdToChildTokenIdsIndex[_tokenId];
_transferFrom(_fromContract, _to, _tokenId);
require(_checkAndCallSafeTransfer(_fromContract, _to, _tokenId, _data));
}
function transferToParent(address _from, address _toContract, uint256 _toTokenId, uint256 _tokenId, bytes _data) public {
_transferFromOwnerCheck(_from, _toContract, _tokenId);
_transferChild(_from, _toContract, _toTokenId, _tokenId);
}
function transferAsChild(address _fromContract, uint256 _fromTokenId, address _toContract, uint256 _toTokenId, uint256 _tokenId, bytes _data) external {
_removeFromToken(_fromContract, _fromTokenId, _toContract, _tokenId);
_transferChild(_fromContract, _toContract, _toTokenId, _tokenId);
}
/////////////////////////////////////////////////////////////////////////////
//
// ERC998 Bottom-Up Enumerable Implementation
//
/////////////////////////////////////////////////////////////////////////////
function totalChildTokens(address _parentContract, uint256 _parentTokenId) public view returns (uint256) {
return parentToChildTokenIds[_parentContract][_parentTokenId].length;
}
function childTokenByIndex(address _parentContract, uint256 _parentTokenId, uint256 _index) public view returns (uint256) {
require(parentToChildTokenIds[_parentContract][_parentTokenId].length > _index);
return parentToChildTokenIds[_parentContract][_parentTokenId][_index];
}
}
contract CryptoRomeControl {
// Emited when contract is upgraded or ownership changed
event ContractUpgrade(address newContract);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
// Has control of (most) contract elements
address public ownerPrimary;
address public ownerSecondary;
// Address of owner wallet to transfer funds
address public ownerWallet;
address public cryptoRomeWallet;
// Contracts that need access for gameplay
// (state = 1 means access is active, state = 0 means disabled)
mapping(address => uint8) public otherOperators;
// Improvement contract is the only authorized address that can modify
// existing land data (ex. when player purchases a land improvement). No one else can
// modify land - even owners of this contract
address public improvementContract;
// Tracks if contract is paused or not. If paused, most actions are blocked
bool public paused = false;
constructor() public {
ownerPrimary = msg.sender;
ownerSecondary = msg.sender;
ownerWallet = msg.sender;
cryptoRomeWallet = msg.sender;
}
modifier onlyOwner() {
require (msg.sender == ownerPrimary || msg.sender == ownerSecondary);
_;
}
modifier anyOperator() {
require (
msg.sender == ownerPrimary ||
msg.sender == ownerSecondary ||
otherOperators[msg.sender] == 1
);
_;
}
modifier onlyOtherOperators() {
require (otherOperators[msg.sender] == 1);
_;
}
modifier onlyImprovementContract() {
require (msg.sender == improvementContract);
_;
}
function setPrimaryOwner(address _newOwner) external onlyOwner {
require (_newOwner != address(0));
emit OwnershipTransferred(ownerPrimary, _newOwner);
ownerPrimary = _newOwner;
}
function setSecondaryOwner(address _newOwner) external onlyOwner {
require (_newOwner != address(0));
emit OwnershipTransferred(ownerSecondary, _newOwner);
ownerSecondary = _newOwner;
}
function setOtherOperator(address _newOperator, uint8 _state) external onlyOwner {
require (_newOperator != address(0));
otherOperators[_newOperator] = _state;
}
function setImprovementContract(address _improvementContract) external onlyOwner {
require (_improvementContract != address(0));
emit OwnershipTransferred(improvementContract, _improvementContract);
improvementContract = _improvementContract;
}
function transferOwnerWalletOwnership(address newWalletAddress) onlyOwner external {
require(newWalletAddress != address(0));
ownerWallet = newWalletAddress;
}
function transferCryptoRomeWalletOwnership(address newWalletAddress) onlyOwner external {
require(newWalletAddress != address(0));
cryptoRomeWallet = newWalletAddress;
}
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused {
require(paused);
_;
}
function pause() public onlyOwner whenNotPaused {
paused = true;
}
function unpause() public onlyOwner whenPaused {
paused = false;
}
function withdrawBalance() public onlyOwner {
ownerWallet.transfer(address(this).balance);
}
}
contract CryptoRomeLandComposableNFT is ERC998ERC721BottomUpToken, CryptoRomeControl {
using SafeMath for uint256;
// Set in case the contract needs to be updated
address public newContractAddress;
struct LandInfo {
uint256 landType; // 0-4 unit, plot, village, town, city (unit unused)
uint256 landImprovements;
uint256 askingPrice;
}
mapping(uint256 => LandInfo) internal tokenIdToLand;
// for sale state of all tokens. tokens map to bits. 0 = not for sale; 1 = for sale
// 256 token states per index of this array
uint256[] internal allLandForSaleState;
// landType => land count
mapping(uint256 => uint256) internal landTypeToCount;
// total number of villages in existence is 50000 (no more can be created)
uint256 constant internal MAX_VILLAGES = 50000;
constructor () public {
paused = true;
name_ = "CryptoRome-Land-NFT";
symbol_ = "CRLAND";
}
function isCryptoRomeLandComposableNFT() external pure returns (bool) {
return true;
}
function getLandTypeCount(uint256 _landType) public view returns (uint256) {
return landTypeToCount[_landType];
}
function setTokenURI(string _tokenURI) external anyOperator {
tokenURIBase = _tokenURI;
}
function setNewAddress(address _v2Address) external onlyOwner {
require (_v2Address != address(0));
newContractAddress = _v2Address;
emit ContractUpgrade(_v2Address);
}
/////////////////////////////////////////////////////////////////////////////
// Get Land
// Token Owner: Address of the token owner
// Parent Token Id: If parentTokenId is > 0, then this land
// token is owned by another token (i.e. it is attached bottom-up).
// parentTokenId is the id of the owner token, and tokenOwner
// address (the first parameter) is the ERC721 contract address of the
// parent token. If parentTokenId == 0, then this land token is owned
// by a user address.
// Land Types: village=1, town=2, city=3
// Land Improvements: improvements and upgrades
// to each land NFT are coded into a single uint256 value
// Asking Price (in wei): 0 if land is not for sale
/////////////////////////////////////////////////////////////////////////////
function getLand(uint256 _tokenId) external view
returns (
address tokenOwner,
uint256 parentTokenId,
uint256 landType,
uint256 landImprovements,
uint256 askingPrice
) {
TokenOwner storage owner = tokenIdToTokenOwner[_tokenId];
LandInfo storage land = tokenIdToLand[_tokenId];
parentTokenId = owner.parentTokenId;
if (parentTokenId > 0) {
parentTokenId--;
}
tokenOwner = owner.tokenOwner;
parentTokenId = owner.parentTokenId;
landType = land.landType;
landImprovements = land.landImprovements;
askingPrice = land.askingPrice;
}
/////////////////////////////////////////////////////////////////////////////
// Create Land NFT
// Land Types: village=1, town=2, city=3
// Land Improvements: improvements and upgrades
// to each land NFT are the coded into a uint256 value
/////////////////////////////////////////////////////////////////////////////
function _createLand (address _tokenOwner, uint256 _landType, uint256 _landImprovements) internal returns (uint256 tokenId) {
require(_tokenOwner != address(0));
require(landTypeToCount[1] < MAX_VILLAGES);
tokenId = tokenCount;
LandInfo memory land = LandInfo({
landType: _landType, // 1-3 village, town, city
landImprovements: _landImprovements,
askingPrice: 0
});
// map new tokenId to the newly created land
tokenIdToLand[tokenId] = land;
landTypeToCount[_landType]++;
if (tokenId % 256 == 0) {
// create new land sale state entry in storage
allLandForSaleState.push(0);
}
_mint(_tokenOwner, tokenId);
return tokenId;
}
function createLand (address _tokenOwner, uint256 _landType, uint256 _landImprovements) external anyOperator whenNotPaused returns (uint256 tokenId) {
return _createLand (_tokenOwner, _landType, _landImprovements);
}
////////////////////////////////////////////////////////////////////////////////
// Land Improvement Data
// This uint256 land "dna" value describes all improvements and upgrades
// to a piece of land. After land token distribution, only the Improvement
// Contract can ever update or modify the land improvement data of a piece
// of land (contract owner cannot modify land).
//
// For villages, improvementData is a uint256 value containing village
// improvement data with the following slot bit mapping
// 0-31: slot 1 improvement info
// 32-63: slot 2 improvement info
// 64-95: slot 3 improvement info
// 96-127: slot 4 improvement info
// 128-159: slot 5 improvement info
// 160-191: slot 6 improvement info
// 192-255: reserved for additional land information
//
// Each 32 bit slot in the above structure has the following bit mapping
// 0-7: improvement type (index to global list of possible types)
// 8-14: upgrade type 1 - level 0-99 (0 for no upgrade present)
// 15-21: upgrade type 2 - level 0-99 (0 for no upgrade present)
// 22: upgrade type 3 - 1 if upgrade present, 0 if not (no leveling)
////////////////////////////////////////////////////////////////////////////////
function getLandImprovementData(uint256 _tokenId) external view returns (uint256) {
return tokenIdToLand[_tokenId].landImprovements;
}
function updateLandImprovementData(uint256 _tokenId, uint256 _newLandImprovementData) external whenNotPaused onlyImprovementContract {
require(_tokenId <= tokenCount);
tokenIdToLand[_tokenId].landImprovements = _newLandImprovementData;
}
/////////////////////////////////////////////////////////////////////////////
// Land Compose/Decompose functions
// Towns are composed of 3 Villages
// Cities are composed of 3 Towns
/////////////////////////////////////////////////////////////////////////////
// Attach three child land tokens onto a parent land token (ex. 3 villages onto a town).
// This function is called when the parent does not exist yet, so create parent land token first
// Ownership of the child lands transfers from the existing owner (sender) to the parent land token
function composeNewLand(uint256 _landType, uint256 _childLand1, uint256 _childLand2, uint256 _childLand3) external whenNotPaused returns(uint256) {
uint256 parentTokenId = _createLand(msg.sender, _landType, 0);
return composeLand(parentTokenId, _childLand1, _childLand2, _childLand3);
}
// Attach three child land tokens onto a parent land token (ex. 3 villages into a town).
// All three children and an existing parent need to be passed into this function.
// Ownership of the child lands transfers from the existing owner (sender) to the parent land token
function composeLand(uint256 _parentLandId, uint256 _childLand1, uint256 _childLand2, uint256 _childLand3) public whenNotPaused returns(uint256) {
require (tokenIdToLand[_parentLandId].landType == 2 || tokenIdToLand[_parentLandId].landType == 3);
uint256 validChildLandType = tokenIdToLand[_parentLandId].landType.sub(1);
require(tokenIdToLand[_childLand1].landType == validChildLandType &&
tokenIdToLand[_childLand2].landType == validChildLandType &&
tokenIdToLand[_childLand3].landType == validChildLandType);
// transfer ownership of child land tokens to parent land token
transferToParent(tokenIdToTokenOwner[_childLand1].tokenOwner, address(this), _parentLandId, _childLand1, "");
transferToParent(tokenIdToTokenOwner[_childLand2].tokenOwner, address(this), _parentLandId, _childLand2, "");
transferToParent(tokenIdToTokenOwner[_childLand3].tokenOwner, address(this), _parentLandId, _childLand3, "");
// if this contract is owner of the parent land token, transfer ownership to msg.sender
if (tokenIdToTokenOwner[_parentLandId].tokenOwner == address(this)) {
_transferFrom(address(this), msg.sender, _parentLandId);
}
return _parentLandId;
}
// Decompose a parent land back to it's attached child land token components (ex. a town into 3 villages).
// The existing owner of the parent land becomes the owner of the three child tokens
// This contract takes over ownership of the parent land token (for later reuse)
// Loop to remove and transfer all land tokens in case other land tokens are attached.
function decomposeLand(uint256 _tokenId) external whenNotPaused {
uint256 numChildren = totalChildTokens(address(this), _tokenId);
require (numChildren > 0);
// it is lower gas cost to remove children starting from the end of the array
for (uint256 numChild = numChildren; numChild > 0; numChild--) {
uint256 childTokenId = childTokenByIndex(address(this), _tokenId, numChild-1);
// transfer ownership of underlying lands to msg.sender
transferFromParent(address(this), _tokenId, msg.sender, childTokenId, "");
}
// transfer ownership of parent land back to this contract owner for reuse
_transferFrom(msg.sender, address(this), _tokenId);
}
/////////////////////////////////////////////////////////////////////////////
// Sale functions
/////////////////////////////////////////////////////////////////////////////
function _updateSaleData(uint256 _tokenId, uint256 _askingPrice) internal {
tokenIdToLand[_tokenId].askingPrice = _askingPrice;
if (_askingPrice > 0) {
// Item is for sale - set bit
allLandForSaleState[_tokenId.div(256)] = allLandForSaleState[_tokenId.div(256)] | (1 << (_tokenId % 256));
} else {
// Item is no longer for sale - clear bit
allLandForSaleState[_tokenId.div(256)] = allLandForSaleState[_tokenId.div(256)] & ~(1 << (_tokenId % 256));
}
}
function sellLand(uint256 _tokenId, uint256 _askingPrice) public whenNotPaused {
require(tokenIdToTokenOwner[_tokenId].tokenOwner == msg.sender);
require(tokenIdToTokenOwner[_tokenId].parentTokenId == 0);
require(_askingPrice > 0);
// Put the land token on the market
_updateSaleData(_tokenId, _askingPrice);
}
function cancelLandSale(uint256 _tokenId) public whenNotPaused {
require(tokenIdToTokenOwner[_tokenId].tokenOwner == msg.sender);
// Take the land token off the market
_updateSaleData(_tokenId, 0);
}
function purchaseLand(uint256 _tokenId) public whenNotPaused payable {
uint256 price = tokenIdToLand[_tokenId].askingPrice;
require(price <= msg.value);
// Take the land token off the market
_updateSaleData(_tokenId, 0);
// Marketplace fee
uint256 marketFee = computeFee(price);
uint256 sellerProceeds = msg.value.sub(marketFee);
cryptoRomeWallet.transfer(marketFee);
// Return excess payment to sender
uint256 excessPayment = msg.value.sub(price);
msg.sender.transfer(excessPayment);
// Transfer proceeds to seller. Sale was removed above before this transfer()
// to guard against reentrancy attacks
tokenIdToTokenOwner[_tokenId].tokenOwner.transfer(sellerProceeds);
// Transfer token to buyer
_transferFrom(tokenIdToTokenOwner[_tokenId].tokenOwner, msg.sender, _tokenId);
}
function getAllForSaleStatus() external view returns(uint256[]) {
// return uint256[] bitmap values up to max tokenId (for ease of querying from UI for marketplace)
// index 0 of the uint256 holds first 256 land token status; index 1 is next 256 land tokens, etc
// value of 1 = For Sale; 0 = Not for Sale
return allLandForSaleState;
}
function computeFee(uint256 amount) internal pure returns(uint256) {
// 3% marketplace fee, most of which will be distributed to the Caesar and Senators of CryptoRome
return amount.mul(3).div(100);
}
}
contract CryptoRomeLandDistribution is CryptoRomeControl {
using SafeMath for uint256;
// Set in case the contract needs to be updated
address public newContractAddress;
CryptoRomeLandComposableNFT public cryptoRomeLandNFTContract;
ImprovementGeneration public improvementGenContract;
uint256 public villageInventoryPrice;
uint256 public numImprovementsPerVillage;
uint256 constant public LOWEST_VILLAGE_INVENTORY_PRICE = 100000000000000000; // 0.1 ETH
constructor (address _cryptoRomeLandNFTContractAddress, address _improvementGenContractAddress) public {
require (_cryptoRomeLandNFTContractAddress != address(0));
require (_improvementGenContractAddress != address(0));
paused = true;
cryptoRomeLandNFTContract = CryptoRomeLandComposableNFT(_cryptoRomeLandNFTContractAddress);
improvementGenContract = ImprovementGeneration(_improvementGenContractAddress);
villageInventoryPrice = LOWEST_VILLAGE_INVENTORY_PRICE;
numImprovementsPerVillage = 3;
}
function setNewAddress(address _v2Address) external onlyOwner {
require (_v2Address != address(0));
newContractAddress = _v2Address;
emit ContractUpgrade(_v2Address);
}
function setCryptoRomeLandNFTContract(address _cryptoRomeLandNFTContract) external onlyOwner {
require (_cryptoRomeLandNFTContract != address(0));
cryptoRomeLandNFTContract = CryptoRomeLandComposableNFT(_cryptoRomeLandNFTContract);
}
function setImprovementGenContract(address _improvementGenContractAddress) external onlyOwner {
require (_improvementGenContractAddress != address(0));
improvementGenContract = ImprovementGeneration(_improvementGenContractAddress);
}
function setVillageInventoryPrice(uint256 _price) external onlyOwner {
require(_price >= LOWEST_VILLAGE_INVENTORY_PRICE);
villageInventoryPrice = _price;
}
function setNumImprovementsPerVillage(uint256 _numImprovements) external onlyOwner {
require(_numImprovements <= 6);
numImprovementsPerVillage = _numImprovements;
}
function purchaseFromVillageInventory(uint256 _num) external whenNotPaused payable {
uint256 price = villageInventoryPrice.mul(_num);
require (msg.value >= price);
require (_num > 0 && _num <= 50);
// Marketplace fee
uint256 marketFee = computeFee(price);
cryptoRomeWallet.transfer(marketFee);
// Return excess payment to sender
uint256 excessPayment = msg.value.sub(price);
msg.sender.transfer(excessPayment);
for (uint256 i = 0; i < _num; i++) {
// create a new village w/ random improvements and transfer the NFT to caller
_createVillageWithImprovementsFromInv(msg.sender);
}
}
function computeFee(uint256 amount) internal pure returns(uint256) {
// 3% marketplace fee, most of which will be distributed to the Caesar and Senators of CryptoRome
return amount.mul(3).div(100);
}
function batchIssueLand(address _toAddress, uint256[] _landType) external onlyOwner {
require (_toAddress != address(0));
require (_landType.length > 0);
for (uint256 i = 0; i < _landType.length; i++) {
issueLand(_toAddress, _landType[i]);
}
}
function batchIssueVillages(address _toAddress, uint256 _num) external onlyOwner {
require (_toAddress != address(0));
require (_num > 0);
for (uint256 i = 0; i < _num; i++) {
_createVillageWithImprovements(_toAddress);
}
}
function issueLand(address _toAddress, uint256 _landType) public onlyOwner returns (uint256) {
require (_toAddress != address(0));
return _createLandWithImprovements(_toAddress, _landType);
}
function batchCreateLand(uint256[] _landType) external onlyOwner {
require (_landType.length > 0);
for (uint256 i = 0; i < _landType.length; i++) {
// land created is owned by this contract for staging purposes
// (must later use transferTo or batchTransferTo)
_createLandWithImprovements(address(this), _landType[i]);
}
}
function batchCreateVillages(uint256 _num) external onlyOwner {
require (_num > 0);
for (uint256 i = 0; i < _num; i++) {
// land created is owned by this contract for staging purposes
// (must later use transferTo or batchTransferTo)
_createVillageWithImprovements(address(this));
}
}
function createLand(uint256 _landType) external onlyOwner {
// land created is owned by this contract for staging purposes
// (must later use transferTo or batchTransferTo)
_createLandWithImprovements(address(this), _landType);
}
function batchTransferTo(uint256[] _tokenIds, address _to) external onlyOwner {
require (_tokenIds.length > 0);
require (_to != address(0));
for (uint256 i = 0; i < _tokenIds.length; ++i) {
// transfers staged land out of this contract to the owners
cryptoRomeLandNFTContract.transferFrom(address(this), _to, _tokenIds[i]);
}
}
function transferTo(uint256 _tokenId, address _to) external onlyOwner {
require (_to != address(0));
// transfers staged land out of this contract to the owners
cryptoRomeLandNFTContract.transferFrom(address(this), _to, _tokenId);
}
function issueVillageWithImprovementsForPromo(address _toAddress, uint256 numImprovements) external onlyOwner returns (uint256) {
uint256 landImprovements = improvementGenContract.genInitialResourcesForVillage(numImprovements, false);
return cryptoRomeLandNFTContract.createLand(_toAddress, 1, landImprovements);
}
function _createVillageWithImprovementsFromInv(address _toAddress) internal returns (uint256) {
uint256 landImprovements = improvementGenContract.genInitialResourcesForVillage(numImprovementsPerVillage, true);
return cryptoRomeLandNFTContract.createLand(_toAddress, 1, landImprovements);
}
function _createVillageWithImprovements(address _toAddress) internal returns (uint256) {
uint256 landImprovements = improvementGenContract.genInitialResourcesForVillage(3, false);
return cryptoRomeLandNFTContract.createLand(_toAddress, 1, landImprovements);
}
function _createLandWithImprovements(address _toAddress, uint256 _landType) internal returns (uint256) {
require (_landType > 0 && _landType < 4);
if (_landType == 1) {
return _createVillageWithImprovements(_toAddress);
} else if (_landType == 2) {
uint256 village1TokenId = _createLandWithImprovements(address(this), 1);
uint256 village2TokenId = _createLandWithImprovements(address(this), 1);
uint256 village3TokenId = _createLandWithImprovements(address(this), 1);
uint256 townTokenId = cryptoRomeLandNFTContract.createLand(_toAddress, 2, 0);
cryptoRomeLandNFTContract.composeLand(townTokenId, village1TokenId, village2TokenId, village3TokenId);
return townTokenId;
} else if (_landType == 3) {
uint256 town1TokenId = _createLandWithImprovements(address(this), 2);
uint256 town2TokenId = _createLandWithImprovements(address(this), 2);
uint256 town3TokenId = _createLandWithImprovements(address(this), 2);
uint256 cityTokenId = cryptoRomeLandNFTContract.createLand(_toAddress, 3, 0);
cryptoRomeLandNFTContract.composeLand(cityTokenId, town1TokenId, town2TokenId, town3TokenId);
return cityTokenId;
}
}
}
interface RandomNumGeneration {
function getRandomNumber(uint256 seed) external returns (uint256);
}
contract ImprovementGeneration is CryptoRomeControl {
using SafeMath for uint256;
// Set in case the contract needs to be updated
address public newContractAddress;
RandomNumGeneration public randomNumberSource;
uint256 public rarityValueMax;
uint256 public latestPseudoRandomNumber;
uint8 public numResourceImprovements;
mapping(uint8 => uint256) private improvementIndexToRarityValue;
constructor () public {
// Starting Improvements
// improvement => rarity value (lower number = higher rarity)
improvementIndexToRarityValue[1] = 256; // Wheat
improvementIndexToRarityValue[2] = 256; // Wood
improvementIndexToRarityValue[3] = 128; // Grapes
improvementIndexToRarityValue[4] = 128; // Stone
improvementIndexToRarityValue[5] = 64; // Clay
improvementIndexToRarityValue[6] = 64; // Fish
improvementIndexToRarityValue[7] = 32; // Horse
improvementIndexToRarityValue[8] = 16; // Iron
improvementIndexToRarityValue[9] = 8; // Marble
// etc --> More can be added in the future
// max resource improvement types is 63
numResourceImprovements = 9;
rarityValueMax = 952;
}
function setNewAddress(address _v2Address) external onlyOwner {
require (_v2Address != address(0));
newContractAddress = _v2Address;
emit ContractUpgrade(_v2Address);
}
function setRandomNumGenerationContract(address _randomNumberGenAddress) external onlyOwner {
require (_randomNumberGenAddress != address(0));
randomNumberSource = RandomNumGeneration(_randomNumberGenAddress);
}
function genInitialResourcesForVillage(uint256 numImprovements, bool useRandomInput) external anyOperator returns(uint256) {
require(numImprovements <= 6);
uint256 landImprovements;
// each improvement takes up one village slot (max 6 slots)
for (uint256 i = 0; i < numImprovements; i++) {
uint8 newImprovement = generateImprovement(useRandomInput);
// each slot is a 32 bit section in the 256 bit landImprovement value
landImprovements |= uint256(newImprovement) << (32*i);
}
return landImprovements;
}
function generateImprovement(bool useRandomSource) public anyOperator returns (uint8 newImprovement) {
// seed does not need to be anything super fancy for initial improvement generation for villages...
// players will not be performing that operation, so this should be random enough
uint256 seed = latestPseudoRandomNumber.add(now);
if (useRandomSource) {
// for cases where players are generating land (i.e. after initial distribution of villages), there
// will need to be a better source of randomness
seed = randomNumberSource.getRandomNumber(seed);
}
latestPseudoRandomNumber = addmod(uint256(blockhash(block.number-1)), seed, rarityValueMax);
// do lookup for the improvement
newImprovement = lookupImprovementTypeByRarity(latestPseudoRandomNumber);
}
function lookupImprovementTypeByRarity(uint256 rarityNum) public view returns (uint8 improvementType) {
uint256 rarityIndexValue;
for (uint8 i = 1; i <= numResourceImprovements; i++) {
rarityIndexValue += improvementIndexToRarityValue[i];
if (rarityNum < rarityIndexValue) {
return i;
}
}
return 0;
}
function addNewResourceImprovementType(uint256 rarityValue) external onlyOwner {
require(rarityValue > 0);
require(numResourceImprovements < 63);
numResourceImprovements++;
rarityValueMax += rarityValue;
improvementIndexToRarityValue[numResourceImprovements] = rarityValue;
}
function updateImprovementRarityValue(uint256 rarityValue, uint8 improvementIndex) external onlyOwner {
require(rarityValue > 0);
require(improvementIndex <= numResourceImprovements);
rarityValueMax -= improvementIndexToRarityValue[improvementIndex];
rarityValueMax += rarityValue;
improvementIndexToRarityValue[improvementIndex] = rarityValue;
}
} | // Get Land Token Owner: Address of the token owner Parent Token Id: If parentTokenId is > 0, then this land token is owned by another token (i.e. it is attached bottom-up). parentTokenId is the id of the owner token, and tokenOwner address (the first parameter) is the ERC721 contract address of the parent token. If parentTokenId == 0, then this land token is owned by a user address. Land Types: village=1, town=2, city=3 Land Improvements: improvements and upgrades to each land NFT are coded into a single uint256 value Asking Price (in wei): 0 if land is not for sale// | function getLand(uint256 _tokenId) external view
returns (
address tokenOwner,
uint256 parentTokenId,
uint256 landType,
uint256 landImprovements,
uint256 askingPrice
) {
TokenOwner storage owner = tokenIdToTokenOwner[_tokenId];
LandInfo storage land = tokenIdToLand[_tokenId];
parentTokenId = owner.parentTokenId;
if (parentTokenId > 0) {
parentTokenId--;
}
tokenOwner = owner.tokenOwner;
parentTokenId = owner.parentTokenId;
landType = land.landType;
landImprovements = land.landImprovements;
askingPrice = land.askingPrice;
}
| 1,090,718 |
./full_match/7700/0x5c35B23Bc2C7F75dbCc5eAa334f7644e79FC4794/sources/contracts/CantoRabbits.sol | @solidity memory-safe-assembly | 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;
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
assembly {
revert(add(32, reason), mload(reason))
}
}
}
return true;
}
}
| 4,650,233 |
pragma solidity ^0.4.19;
/**
* This is the official Ethbet Token smart contract (EBET) - https://ethbet.io/
*/
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
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;
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) constant returns (uint256);
function transfer(address to, uint256 value) returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
/**
* @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) 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) constant returns (uint256 balance) {
return balances[_owner];
}
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) constant returns (uint256);
function transferFrom(address from, address to, uint256 value) returns (bool);
function approve(address spender, uint256 value) returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) 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) returns (bool) {
require(_to != address(0));
var _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.
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) returns (bool) {
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender, 0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
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) 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;
}
}
/**
* @title EthbetToken
*/
contract EthbetToken is StandardToken {
string public constant name = "Ethbet";
string public constant symbol = "EBET";
uint8 public constant decimals = 2; // only two deciminals, token cannot be divided past 1/100th
uint256 public constant INITIAL_SUPPLY = 1000000000; // 10 million + 2 decimals
/**
* @dev Contructor that gives msg.sender all of existing tokens.
*/
function EthbetToken() {
totalSupply = INITIAL_SUPPLY;
balances[msg.sender] = INITIAL_SUPPLY;
}
}
// Import newer SafeMath version under new name to avoid conflict with the version included in EthbetToken
// SafeMath Library https://github.com/OpenZeppelin/zeppelin-solidity/blob/49b42e86963df7192e7024e0e5bd30fa9d7ccbef/contracts/math/SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath2 {
/**
* @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;
}
}
contract Ethbet {
using SafeMath2 for uint256;
/*
* Events
*/
event Deposit(address indexed user, uint amount, uint balance);
event Withdraw(address indexed user, uint amount, uint balance);
event LockedBalance(address indexed user, uint amount);
event UnlockedBalance(address indexed user, uint amount);
event ExecutedBet(address indexed winner, address indexed loser, uint amount);
event RelayAddressChanged(address relay);
/*
* Storage
*/
address public relay;
EthbetToken public token;
mapping(address => uint256) balances;
mapping(address => uint256) lockedBalances;
/*
* Modifiers
*/
modifier isRelay() {
require(msg.sender == relay);
_;
}
/*
* Public functions
*/
/**
* @dev Contract constructor
* @param _relay Relay Address
* @param _tokenAddress Ethbet Token Address
*/
function Ethbet(address _relay, address _tokenAddress) public {
// make sure relay address set
require(_relay != address(0));
relay = _relay;
token = EthbetToken(_tokenAddress);
}
/**
* @dev set relay address
* @param _relay Relay Address
*/
function setRelay(address _relay) public isRelay {
// make sure address not null
require(_relay != address(0));
relay = _relay;
RelayAddressChanged(_relay);
}
/**
* @dev deposit EBET tokens into the contract
* @param _amount Amount to deposit
*/
function deposit(uint _amount) public {
require(_amount > 0);
// token.approve needs to be called beforehand
// transfer tokens from the user to the contract
require(token.transferFrom(msg.sender, this, _amount));
// add the tokens to the user's balance
balances[msg.sender] = balances[msg.sender].add(_amount);
Deposit(msg.sender, _amount, balances[msg.sender]);
}
/**
* @dev withdraw EBET tokens from the contract
* @param _amount Amount to withdraw
*/
function withdraw(uint _amount) public {
require(_amount > 0);
require(balances[msg.sender] >= _amount);
// subtract the tokens from the user's balance
balances[msg.sender] = balances[msg.sender].sub(_amount);
// transfer tokens from the contract to the user
require(token.transfer(msg.sender, _amount));
Withdraw(msg.sender, _amount, balances[msg.sender]);
}
/**
* @dev Lock user balance to be used for bet
* @param _userAddress User Address
* @param _amount Amount to be locked
*/
function lockBalance(address _userAddress, uint _amount) public isRelay {
require(_amount > 0);
require(balances[_userAddress] >= _amount);
// subtract the tokens from the user's balance
balances[_userAddress] = balances[_userAddress].sub(_amount);
// add the tokens to the user's locked balance
lockedBalances[_userAddress] = lockedBalances[_userAddress].add(_amount);
LockedBalance(_userAddress, _amount);
}
/**
* @dev Unlock user balance
* @param _userAddress User Address
* @param _amount Amount to be locked
*/
function unlockBalance(address _userAddress, uint _amount) public isRelay {
require(_amount > 0);
require(lockedBalances[_userAddress] >= _amount);
// subtract the tokens from the user's locked balance
lockedBalances[_userAddress] = lockedBalances[_userAddress].sub(_amount);
// add the tokens to the user's balance
balances[_userAddress] = balances[_userAddress].add(_amount);
UnlockedBalance(_userAddress, _amount);
}
/**
* @dev Get user balance
* @param _userAddress User Address
*/
function balanceOf(address _userAddress) constant public returns (uint) {
return balances[_userAddress];
}
/**
* @dev Get user locked balance
* @param _userAddress User Address
*/
function lockedBalanceOf(address _userAddress) constant public returns (uint) {
return lockedBalances[_userAddress];
}
/**
* @dev Execute bet
* @param _maker Maker Address
* @param _caller Caller Address
* @param _makerWon Did the maker win
* @param _amount amount
*/
function executeBet(address _maker, address _caller, bool _makerWon, uint _amount) isRelay public {
//The caller must have enough locked balance
require(lockedBalances[_caller] >= _amount);
//The maker must have enough locked balance
require(lockedBalances[_maker] >= _amount);
// unlock maker balance
unlockBalance(_caller, _amount);
// unlock maker balance
unlockBalance(_maker, _amount);
var winner = _makerWon ? _maker : _caller;
var loser = _makerWon ? _caller : _maker;
// add the tokens to the winner's balance
balances[winner] = balances[winner].add(_amount);
// remove the tokens from the loser's balance
balances[loser] = balances[loser].sub(_amount);
//Log the event
ExecutedBet(winner, loser, _amount);
}
} | set relay address _relay Relay Address/ make sure address not null | function setRelay(address _relay) public isRelay {
require(_relay != address(0));
relay = _relay;
RelayAddressChanged(_relay);
}
| 10,106,768 |
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "../interface/IERC20.sol";
import "../interface/ILToken.sol";
import "./ERC20.sol";
import "../math/UnsignedSafeMath.sol";
/**
* @title Deri Protocol liquidity provider token implementation
*/
contract LToken is IERC20, ILToken, ERC20 {
using UnsignedSafeMath for uint256;
// Pool address this LToken associated with
address private _pool;
modifier _pool_() {
require(msg.sender == _pool, "LToken: called by non-associative pool, probably the original pool has been migrated");
_;
}
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token
*/
constructor(string memory name_, string memory symbol_, address pool_) ERC20(name_, symbol_) {
require(pool_ != address(0), "LToken: construct with 0 address pool");
_pool = pool_;
}
/**
* @dev See {ILToken}.{setPool}
*/
function setPool(address newPool) public override {
require(newPool != address(0), "LToken: setPool to 0 address");
require(msg.sender == _pool, "LToken: setPool caller is not current pool");
_pool = newPool;
}
/**
* @dev See {ILToken}.{pool}
*/
function pool() public view override returns (address) {
return _pool;
}
/**
* @dev See {ILToken}.{mint}
*/
function mint(address account, uint256 amount) public override _pool_ {
require(account != address(0), "LToken: mint to 0 address");
_balances[account] = _balances[account].add(amount);
_totalSupply = _totalSupply.add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev See {ILToken}.{burn}
*/
function burn(address account, uint256 amount) public override _pool_ {
require(account != address(0), "LToken: burn from 0 address");
require(_balances[account] >= amount, "LToken: burn amount exceeds balance");
_balances[account] = _balances[account].sub(amount);
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
}
// 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 Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `amount` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 amount);
/**
* @dev Emitted when `amount` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `amount` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 amount);
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token, usually a shorter version of the name.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() external view returns (uint8);
/**
* @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 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 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 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);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "./IERC20.sol";
/**
* @title Deri Protocol liquidity provider token interface
*/
interface ILToken is IERC20 {
/**
* @dev Set the pool address of this LToken
* pool is the only controller of this contract
* can only be called by current pool
*/
function setPool(address newPool) external;
/**
* @dev Returns address of pool
*/
function pool() external view returns (address);
/**
* @dev Mint LToken to `account` of `amount`
*
* Can only be called by pool
* `account` cannot be zero address
*/
function mint(address account, uint256 amount) external;
/**
* @dev Burn `amount` LToken of `account`
*
* Can only be called by pool
* `account` cannot be zero address
* `account` must owns at least `amount` LToken
*/
function burn(address account, uint256 amount) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../interface/IERC20.sol";
import "../math/UnsignedSafeMath.sol";
/**
* @title ERC20 Implementation
*/
contract ERC20 is IERC20 {
using UnsignedSafeMath for uint256;
string _name;
string _symbol;
uint8 _decimals = 18;
uint256 _totalSupply;
mapping (address => uint256) _balances;
mapping (address => mapping (address => uint256)) _allowances;
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC20}.{name}
*/
function name() public view override returns (string memory) {
return _name;
}
/**
* @dev See {IERC20}.{symbol}
*/
function symbol() public view override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC20}.{decimals}
*/
function decimals() public view override 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}.{allowance}
*/
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20}.{approve}
*/
function approve(address spender, uint256 amount) public override returns (bool) {
require(spender != address(0), "ERC20: approve to 0 address");
_approve(msg.sender, spender, amount);
return true;
}
/**
* @dev See {IERC20}.{transfer}
*/
function transfer(address to, uint256 amount) public override returns (bool) {
require(to != address(0), "ERC20: transfer to 0 address");
require(_balances[msg.sender] >= amount, "ERC20: transfer amount exceeds balance");
_transfer(msg.sender, to, amount);
return true;
}
/**
* @dev See {IERC20}.{transferFrom}
*/
function transferFrom(address from, address to, uint256 amount) public override returns (bool) {
require(to != address(0), "ERC20: transferFrom to 0 address");
if (_allowances[from][msg.sender] != uint256(-1)) {
require(_allowances[from][msg.sender] >= amount, "ERC20: transferFrom not approved");
_allowances[from][msg.sender] = _allowances[from][msg.sender].sub(amount);
}
_transfer(from, to, amount);
return true;
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`.
* Emits an {Approval} event.
*
* Parameters check should be carried out before calling this function.
*/
function _approve(address owner, address spender, uint256 amount) internal {
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Moves tokens `amount` from `from` to `to`.
* Emits a {Transfer} event.
*
* Parameters check should be carried out before calling this function.
*/
function _transfer(address from, address to, uint256 amount) internal {
_balances[from] = _balances[from].sub(amount);
_balances[to] = _balances[to].add(amount);
emit Transfer(from, to, amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @title Unsigned safe math
*/
library UnsignedSafeMath {
/**
* @dev Addition of unsigned integers, counterpart to `+`
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "UnsignedSafeMath: addition overflow");
return c;
}
/**
* @dev Subtraction of unsigned integers, counterpart to `-`
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(a >= b, "UnsignedSafeMath: subtraction overflow");
uint256 c = a - b;
return c;
}
/**
* @dev Multiplication of unsigned integers, counterpart to `*`
*/
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, "UnsignedSafeMath: multiplication overflow");
return c;
}
/**
* @dev Division of unsigned integers, counterpart to `/`
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "UnsignedSafeMath: division by zero");
uint256 c = a / b;
return c;
}
/**
* @dev Modulo of unsigned integers, counterpart to `%`
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "UnsignedSafeMath: modulo by zero");
uint256 c = a % b;
return c;
}
} | See {IERC20}.{approve}/ | function approve(address spender, uint256 amount) public override returns (bool) {
require(spender != address(0), "ERC20: approve to 0 address");
_approve(msg.sender, spender, amount);
return true;
}
| 10,376,713 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./WithLimitedSupply.sol";
/// @author 1001.digital
/// @title Randomly assign tokenIDs from a given set of tokens.
abstract contract RandomlyAssigned is WithLimitedSupply {
// Used for random index assignment
mapping(uint256 => uint256) private tokenMatrix;
// The initial token ID
uint256 private startFrom;
/// Instanciate the contract
/// @param _totalSupply how many tokens this collection should hold
/// @param _startFrom the tokenID with which to start counting
constructor (uint256 _totalSupply, uint256 _startFrom)
WithLimitedSupply(_totalSupply)
{
startFrom = _startFrom;
}
/// Get the next token ID
/// @dev Randomly gets a new token ID and keeps track of the ones that are still available.
/// @return the next token ID
function nextToken() internal override ensureAvailability returns (uint256) {
uint256 maxIndex = allSupply() - tokenCount();
uint256 random = uint256(keccak256(
abi.encodePacked(
msg.sender,
block.coinbase,
block.difficulty,
block.gaslimit,
block.timestamp
)
)) % maxIndex;
uint256 value = 0;
if (tokenMatrix[random] == 0) {
// If this matrix position is empty, set the value to the generated random number.
value = random;
} else {
// Otherwise, use the previously stored number from the matrix.
value = tokenMatrix[random];
}
// If the last available tokenID is still unused...
if (tokenMatrix[maxIndex - 1] == 0) {
// ...store that ID in the current matrix position.
tokenMatrix[random] = maxIndex - 1;
} else {
// ...otherwise copy over the stored number to the current matrix position.
tokenMatrix[random] = tokenMatrix[maxIndex - 1];
}
// Increment counts
super.nextToken();
return value + startFrom;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/utils/Counters.sol";
/// @author 1001.digital
/// @title A token tracker that limits the token supply and increments token IDs on each new mint.
abstract contract WithLimitedSupply {
using Counters for Counters.Counter;
/// @dev Emitted when the supply of this collection changes
event SupplyChanged(uint256 indexed supply);
// Keeps track of how many we have minted
Counters.Counter private _tokenCount;
/// @dev The maximum count of tokens this token tracker will hold.
uint256 private _totalSupply;
/// Instanciate the contract
/// @param totalSupply_ how many tokens this collection should hold
constructor (uint256 totalSupply_) {
_totalSupply = totalSupply_;
}
/// @dev Get the max Supply
/// @return the maximum token count
function allSupply() public view returns (uint256) {
return _totalSupply;
}
/// @dev Get the current token count
/// @return the created token count
function tokenCount() public view returns (uint256) {
return _tokenCount.current();
}
/// @dev Check whether tokens are still available
/// @return the available token count
function availableTokenCount() public view returns (uint256) {
return allSupply() - tokenCount();
}
/// @dev Increment the token count and fetch the latest count
/// @return the next token id
function nextToken() internal virtual returns (uint256) {
uint256 token = _tokenCount.current();
_tokenCount.increment();
return token;
}
/// @dev Check whether another token is still available
modifier ensureAvailability() {
require(availableTokenCount() > 0, "No more tokens available");
_;
}
/// @param amount Check whether number of tokens are still available
/// @dev Check whether tokens are still available
modifier ensureAvailabilityFor(uint256 amount) {
require(availableTokenCount() >= amount, "Requested number of tokens not available");
_;
}
/// Update the supply for the collection
/// @param _supply the new token supply.
/// @dev create additional token supply for this collection.
function _setSupply(uint256 _supply) internal virtual {
require(_supply > tokenCount(), "Can't set the supply to less than the current token count");
_totalSupply = _supply;
emit SupplyChanged(allSupply());
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/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/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 (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@1001-digital/erc721-extensions/contracts/RandomlyAssigned.sol";
contract DogeClub is ERC721Enumerable, Ownable, RandomlyAssigned {
using Strings for uint256;
uint256 public currentSupply = 0;
uint256 public cost = 40000000 gwei;
uint256 public maxSupply = 10000; // Needs to be 10,000 on mainnet
uint256 public maxMintAmount = 20;
string public baseURI;
bool public paused = true;
constructor()
public ERC721("DOGE CLUB", "DC")
RandomlyAssigned(maxSupply,1) {}
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;
function mint(uint256 _mintAmount) public payable {
require(!paused, "Paused Contract");
require(_mintAmount > 0, "Need an amount");
require(_mintAmount <= maxMintAmount, "To many");
require(currentSupply + _mintAmount <= maxSupply, "Not enough left");
if (msg.sender != owner()) {
require(msg.value >= cost * _mintAmount, "Bad maths");
}
for (uint256 i = 1; i <= _mintAmount; i++) {
uint256 id = nextToken();
_safeMint(msg.sender, id);
currentSupply++;
}
}
// Token URI overrided
function tokenURI(uint256 tokenId) public view override virtual returns (string memory) {
bytes32 tokenIdBytes;
if (tokenId == 0) {
tokenIdBytes = "0";
} else {
uint256 value = tokenId;
while (value > 0) {
tokenIdBytes = bytes32(uint256(tokenIdBytes) / (2 ** 8));
tokenIdBytes |= bytes32(((value % 10) + 48) * 2 ** (8 * 31));
value /= 10;
}
}
bytes memory prefixBytes = bytes(baseURI);
bytes memory tokenURIBytes = new bytes(prefixBytes.length + tokenIdBytes.length);
uint8 i;
uint8 index = 0;
for (i = 0; i < prefixBytes.length; i++) {
tokenURIBytes[index] = prefixBytes[i];
index++;
}
for (i = 0; i < tokenIdBytes.length; i++) {
tokenURIBytes[index] = tokenIdBytes[i];
index++;
}
return string(tokenURIBytes);
}
function walletOfOwner(address _owner)
public
view
returns (uint256[] memory)
{
uint256 ownerTokenCount = balanceOf(_owner);
uint256[] memory tokenIds = new uint256[](ownerTokenCount);
for (uint256 i; i < ownerTokenCount; i++) {
tokenIds[i] = tokenOfOwnerByIndex(_owner, i);
}
return tokenIds;
}
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
function tokensOfOwner(address _owner) external view returns(uint256[] memory) {
uint tokenCount = balanceOf(_owner);
uint256[] memory tokenId = new uint256[](tokenCount);
for(uint i = 0; i < tokenCount; i++){
tokenId[i] = tokenOfOwnerByIndex(_owner, i);
}
return tokenId;
}
//only owner
function setCost(uint256 _newCost) public onlyOwner {
cost = _newCost;
}
function setBaseURI(string memory _newBaseURI) public onlyOwner {
baseURI = _newBaseURI;
}
function pause(bool _state) public onlyOwner {
require(keccak256(abi.encodePacked(baseURI)) != keccak256(abi.encodePacked("")), "No baseURI set");
paused = _state;
}
function withdraw() public payable onlyOwner {
(bool os, ) = payable(owner()).call{value: address(this).balance}("");
require(os);
}
} | Get the next token ID Randomly gets a new token ID and keeps track of the ones that are still available. return the next token ID If this matrix position is empty, set the value to the generated random number. Otherwise, use the previously stored number from the matrix. If the last available tokenID is still unused... ...store that ID in the current matrix position. ...otherwise copy over the stored number to the current matrix position. | function nextToken() internal override ensureAvailability returns (uint256) {
uint256 maxIndex = allSupply() - tokenCount();
uint256 random = uint256(keccak256(
abi.encodePacked(
msg.sender,
block.coinbase,
block.difficulty,
block.gaslimit,
block.timestamp
)
)) % maxIndex;
uint256 value = 0;
if (tokenMatrix[random] == 0) {
value = random;
value = tokenMatrix[random];
}
if (tokenMatrix[maxIndex - 1] == 0) {
tokenMatrix[random] = maxIndex - 1;
tokenMatrix[random] = tokenMatrix[maxIndex - 1];
}
return value + startFrom;
}
| 1,548,692 |
// SPDX-License-Identifier: MIT
pragma solidity =0.8.10;
abstract contract IProxyRegistry {
function proxies(address _owner) public virtual view returns (address);
function build(address) public virtual returns (address);
}
abstract contract IGem {
function dec() virtual public returns (uint);
function gem() virtual public returns (IGem);
function join(address, uint) virtual public payable;
function exit(address, uint) virtual public;
function approve(address, uint) virtual public;
function transfer(address, uint) virtual public returns (bool);
function transferFrom(address, address, uint) virtual public returns (bool);
function deposit() virtual public payable;
function withdraw(uint) virtual public;
function allowance(address, address) virtual public returns (uint);
}
abstract contract IJoin {
bytes32 public ilk;
function dec() virtual public view returns (uint);
function gem() virtual public view returns (IGem);
function join(address, uint) virtual public payable;
function exit(address, uint) virtual public;
}
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);
}
abstract contract IManager {
function last(address) virtual public returns (uint);
function cdpCan(address, uint, address) virtual public view returns (uint);
function ilks(uint) virtual public view returns (bytes32);
function owns(uint) virtual public view returns (address);
function urns(uint) virtual public view returns (address);
function vat() virtual public view returns (address);
function open(bytes32, address) virtual public returns (uint);
function give(uint, address) virtual public;
function cdpAllow(uint, address, uint) virtual public;
function urnAllow(address, uint) virtual public;
function frob(uint, int, int) virtual public;
function flux(uint, address, uint) virtual public;
function move(uint, address, uint) virtual public;
function exit(address, uint, address, uint) virtual public;
function quit(uint, address) virtual public;
function enter(address, uint) virtual public;
function shift(uint, uint) virtual public;
}
contract DSMath {
function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = x + y;
}
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = x - y;
}
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = x * y;
}
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);
}
}
}
}
abstract contract DSAuthority {
function canCall(
address src,
address dst,
bytes4 sig
) public view virtual returns (bool);
}
contract DSAuthEvents {
event LogSetAuthority(address indexed authority);
event LogSetOwner(address indexed owner);
}
contract DSAuth is DSAuthEvents {
DSAuthority public authority;
address public owner;
constructor() {
owner = msg.sender;
emit LogSetOwner(msg.sender);
}
function setOwner(address owner_) public auth {
owner = owner_;
emit LogSetOwner(owner);
}
function setAuthority(DSAuthority authority_) public auth {
authority = authority_;
emit LogSetAuthority(address(authority));
}
modifier auth {
require(isAuthorized(msg.sender, msg.sig), "Not authorized");
_;
}
function isAuthorized(address src, bytes4 sig) internal view returns (bool) {
if (src == address(this)) {
return true;
} else if (src == owner) {
return true;
} else if (authority == DSAuthority(address(0))) {
return false;
} else {
return authority.canCall(src, address(this), sig);
}
}
}
contract DSNote {
event LogNote(
bytes4 indexed sig,
address indexed guy,
bytes32 indexed foo,
bytes32 indexed bar,
uint256 wad,
bytes fax
) anonymous;
modifier note {
bytes32 foo;
bytes32 bar;
assembly {
foo := calldataload(4)
bar := calldataload(36)
}
emit LogNote(msg.sig, msg.sender, foo, bar, msg.value, msg.data);
_;
}
}
abstract contract DSProxy is DSAuth, DSNote {
DSProxyCache public cache; // global cache for contracts
constructor(address _cacheAddr) {
if (!(setCache(_cacheAddr))){
require(isAuthorized(msg.sender, msg.sig), "Not authorized");
}
}
// solhint-disable-next-line no-empty-blocks
receive() external payable {}
// use the proxy to execute calldata _data on contract _code
function execute(bytes memory _code, bytes memory _data)
public
payable
virtual
returns (address target, bytes32 response);
function execute(address _target, bytes memory _data)
public
payable
virtual
returns (bytes32 response);
//set new cache
function setCache(address _cacheAddr) public payable virtual returns (bool);
}
contract DSProxyCache {
mapping(bytes32 => address) cache;
function read(bytes memory _code) public view returns (address) {
bytes32 hash = keccak256(_code);
return cache[hash];
}
function write(bytes memory _code) public returns (address target) {
assembly {
target := create(0, add(_code, 0x20), mload(_code))
switch iszero(extcodesize(target))
case 1 {
// throw if contract failed to deploy
revert(0, 0)
}
}
bytes32 hash = keccak256(_code);
cache[hash] = target;
}
}
abstract contract IVat {
struct Urn {
uint256 ink; // Locked Collateral [wad]
uint256 art; // Normalised Debt [wad]
}
struct Ilk {
uint256 Art; // Total Normalised Debt [wad]
uint256 rate; // Accumulated Rates [ray]
uint256 spot; // Price with Safety Margin [ray]
uint256 line; // Debt Ceiling [rad]
uint256 dust; // Urn Debt Floor [rad]
}
mapping (bytes32 => mapping (address => Urn )) public urns;
mapping (bytes32 => Ilk) public ilks;
mapping (bytes32 => mapping (address => uint)) public gem; // [wad]
function can(address, address) virtual public view returns (uint);
function dai(address) virtual public view returns (uint);
function frob(bytes32, address, address, address, int, int) virtual public;
function hope(address) virtual public;
function move(address, address, uint) virtual public;
function fork(bytes32, address, address, int, int) virtual public;
}
interface IERC20 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint256 digits);
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);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
abstract contract IWETH {
function allowance(address, address) public virtual view returns (uint256);
function balanceOf(address) public virtual view 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;
}
library Address {
//insufficient balance
error InsufficientBalance(uint256 available, uint256 required);
//unable to send value, recipient may have reverted
error SendingValueFail();
//insufficient balance for call
error InsufficientBalanceForCall(uint256 available, uint256 required);
//call to non-contract
error NonContractCall();
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 {
uint256 balance = address(this).balance;
if (balance < amount){
revert InsufficientBalance(balance, amount);
}
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{value: amount}("");
if (!(success)){
revert SendingValueFail();
}
}
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) {
uint256 balance = address(this).balance;
if (balance < value){
revert InsufficientBalanceForCall(balance, value);
}
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(
address target,
bytes memory data,
uint256 weiValue,
string memory errorMessage
) private returns (bytes memory) {
if (!(isContract(target))){
revert NonContractCall();
}
// 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 Edited so it always first approves 0 and then the value, because of non standard tokens
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");
}
}
}
library TokenUtils {
using SafeERC20 for IERC20;
address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
function approveToken(
address _tokenAddr,
address _to,
uint256 _amount
) internal {
if (_tokenAddr == ETH_ADDR) return;
if (IERC20(_tokenAddr).allowance(address(this), _to) < _amount) {
IERC20(_tokenAddr).safeApprove(_to, _amount);
}
}
function pullTokensIfNeeded(
address _token,
address _from,
uint256 _amount
) internal returns (uint256) {
// handle max uint amount
if (_amount == type(uint256).max) {
_amount = getBalance(_token, _from);
}
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 (uint256) {
if (_amount == type(uint256).max) {
_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 depositWeth(uint256 _amount) internal {
IWETH(WETH_ADDR).deposit{value: _amount}();
}
function withdrawWeth(uint256 _amount) internal {
IWETH(WETH_ADDR).withdraw(_amount);
}
function getBalance(address _tokenAddr, address _acc) internal view returns (uint256) {
if (_tokenAddr == ETH_ADDR) {
return _acc.balance;
} else {
return IERC20(_tokenAddr).balanceOf(_acc);
}
}
function getTokenDecimals(address _token) internal view returns (uint256) {
if (_token == ETH_ADDR) return 18;
return IERC20(_token).decimals();
}
}
contract MainnetMcdAddresses {
address internal constant VAT_ADDR = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B;
address internal constant DAI_JOIN_ADDR = 0x9759A6Ac90977b93B58547b4A71c78317f391A28;
address internal constant DAI_ADDR = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
address internal constant JUG_ADDRESS = 0x19c0976f590D67707E62397C87829d896Dc0f1F1;
address internal constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3;
address internal constant PROXY_REGISTRY_ADDR = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4;
}
contract McdHelper is DSMath, MainnetMcdAddresses {
IVat public constant vat = IVat(VAT_ADDR);
error IntOverflow();
/// @notice Returns a normalized debt _amount based on the current rate
/// @param _amount Amount of dai to be normalized
/// @param _rate Current rate of the stability fee
/// @param _daiVatBalance Balance od Dai in the Vat for that CDP
function normalizeDrawAmount(uint _amount, uint _rate, uint _daiVatBalance) internal pure returns (int dart) {
if (_daiVatBalance < _amount * RAY) {
dart = toPositiveInt((_amount * RAY - _daiVatBalance) / _rate);
dart = uint(dart) * _rate < _amount * RAY ? dart + 1 : dart;
}
}
/// @notice Converts a number to Rad precision
/// @param _wad The input number in wad precision
function toRad(uint _wad) internal pure returns (uint) {
return _wad * (10 ** 27);
}
/// @notice Converts a number to 18 decimal precision
/// @dev If token decimal is bigger than 18, function reverts
/// @param _joinAddr Join address of the collateral
/// @param _amount Number to be converted
function convertTo18(address _joinAddr, uint256 _amount) internal view returns (uint256) {
return _amount * (10 ** (18 - IJoin(_joinAddr).dec()));
}
/// @notice Converts a uint to int and checks if positive
/// @param _x Number to be converted
function toPositiveInt(uint _x) internal pure returns (int y) {
y = int(_x);
if (y < 0){
revert IntOverflow();
}
}
/// @notice Gets Dai amount in Vat which can be added to Cdp
/// @param _vat Address of Vat contract
/// @param _urn Urn of the Cdp
/// @param _ilk Ilk of the Cdp
function normalizePaybackAmount(address _vat, address _urn, bytes32 _ilk) internal view returns (int amount) {
uint dai = IVat(_vat).dai(_urn);
(, uint rate,,,) = IVat(_vat).ilks(_ilk);
(, uint art) = IVat(_vat).urns(_ilk, _urn);
amount = toPositiveInt(dai / rate);
amount = uint(amount) <= art ? - amount : - toPositiveInt(art);
}
/// @notice Gets the whole debt of the CDP
/// @param _vat Address of Vat contract
/// @param _usr Address of the Dai holder
/// @param _urn Urn of the Cdp
/// @param _ilk Ilk of the Cdp
function getAllDebt(address _vat, address _usr, address _urn, bytes32 _ilk) internal view returns (uint daiAmount) {
(, uint rate,,,) = IVat(_vat).ilks(_ilk);
(, uint art) = IVat(_vat).urns(_ilk, _urn);
uint dai = IVat(_vat).dai(_usr);
uint rad = art * rate - dai;
daiAmount = rad / RAY;
// handles precision error (off by 1 wei)
daiAmount = daiAmount * RAY < rad ? daiAmount + 1 : daiAmount;
}
/// @notice Checks if the join address is one of the Ether coll. types
/// @param _joinAddr Join address to check
function isEthJoinAddr(address _joinAddr) internal view returns (bool) {
// if it's dai_join_addr don't check gem() it will fail
if (_joinAddr == DAI_JOIN_ADDR) return false;
// if coll is weth it's and eth type coll
if (address(IJoin(_joinAddr).gem()) == TokenUtils.WETH_ADDR) {
return true;
}
return false;
}
/// @notice Returns the underlying token address from the joinAddr
/// @dev For eth based collateral returns 0xEee... not weth addr
/// @param _joinAddr Join address to check
function getTokenFromJoin(address _joinAddr) internal view returns (address) {
// if it's dai_join_addr don't check gem() it will fail, return dai addr
if (_joinAddr == DAI_JOIN_ADDR) {
return DAI_ADDR;
}
return address(IJoin(_joinAddr).gem());
}
/// @notice Gets CDP info (collateral, debt)
/// @param _manager Manager contract
/// @param _cdpId Id of the CDP
/// @param _ilk Ilk of the CDP
function getCdpInfo(IManager _manager, uint _cdpId, bytes32 _ilk) public view returns (uint, uint) {
address urn = _manager.urns(_cdpId);
(uint collateral, uint debt) = vat.urns(_ilk, urn);
(,uint rate,,,) = vat.ilks(_ilk);
return (collateral, rmul(debt, rate));
}
/// @notice Address that owns the DSProxy that owns the CDP
/// @param _manager Manager contract
/// @param _cdpId Id of the CDP
function getOwner(IManager _manager, uint _cdpId) public view returns (address) {
DSProxy proxy = DSProxy(payable(address(uint160(_manager.owns(_cdpId)))));
return proxy.owner();
}
}
abstract contract IDFSRegistry {
function getAddr(bytes4 _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;
}
contract MainnetAuthAddresses {
address internal constant ADMIN_VAULT_ADDR = 0xCCf3d848e08b94478Ed8f46fFead3008faF581fD;
address internal constant FACTORY_ADDRESS = 0x5a15566417e6C1c9546523066500bDDBc53F88C7;
address internal constant ADMIN_ADDR = 0x25eFA336886C74eA8E282ac466BdCd0199f85BB9; // USED IN ADMIN VAULT CONSTRUCTOR
}
contract AuthHelper is MainnetAuthAddresses {
}
contract AdminVault is AuthHelper {
address public owner;
address public admin;
error SenderNotAdmin();
constructor() {
owner = msg.sender;
admin = ADMIN_ADDR;
}
/// @notice Admin is able to change owner
/// @param _owner Address of new owner
function changeOwner(address _owner) public {
if (admin != msg.sender){
revert SenderNotAdmin();
}
owner = _owner;
}
/// @notice Admin is able to set new admin
/// @param _admin Address of multisig that becomes new admin
function changeAdmin(address _admin) public {
if (admin != msg.sender){
revert SenderNotAdmin();
}
admin = _admin;
}
}
contract AdminAuth is AuthHelper {
using SafeERC20 for IERC20;
AdminVault public constant adminVault = AdminVault(ADMIN_VAULT_ADDR);
error SenderNotOwner();
error SenderNotAdmin();
modifier onlyOwner() {
if (adminVault.owner() != msg.sender){
revert SenderNotOwner();
}
_;
}
modifier onlyAdmin() {
if (adminVault.admin() != msg.sender){
revert SenderNotAdmin();
}
_;
}
/// @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));
}
}
contract DFSRegistry is AdminAuth {
error EntryAlreadyExistsError(bytes4);
error EntryNonExistentError(bytes4);
error EntryNotInChangeError(bytes4);
error ChangeNotReadyError(uint256,uint256);
error EmptyPrevAddrError(bytes4);
error AlreadyInContractChangeError(bytes4);
error AlreadyInWaitPeriodChangeError(bytes4);
event AddNewContract(address,bytes4,address,uint256);
event RevertToPreviousAddress(address,bytes4,address,address);
event StartContractChange(address,bytes4,address,address);
event ApproveContractChange(address,bytes4,address,address);
event CancelContractChange(address,bytes4,address,address);
event StartWaitPeriodChange(address,bytes4,uint256);
event ApproveWaitPeriodChange(address,bytes4,uint256,uint256);
event CancelWaitPeriodChange(address,bytes4,uint256,uint256);
struct Entry {
address contractAddr;
uint256 waitPeriod;
uint256 changeStartTime;
bool inContractChange;
bool inWaitPeriodChange;
bool exists;
}
mapping(bytes4 => Entry) public entries;
mapping(bytes4 => address) public previousAddresses;
mapping(bytes4 => address) public pendingAddresses;
mapping(bytes4 => uint256) public pendingWaitTimes;
/// @notice Given an contract id returns the registered address
/// @dev Id is keccak256 of the contract name
/// @param _id Id of contract
function getAddr(bytes4 _id) public view returns (address) {
return entries[_id].contractAddr;
}
/// @notice Helper function to easily query if id is registered
/// @param _id Id of contract
function isRegistered(bytes4 _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(
bytes4 _id,
address _contractAddr,
uint256 _waitPeriod
) public onlyOwner {
if (entries[_id].exists){
revert EntryAlreadyExistsError(_id);
}
entries[_id] = Entry({
contractAddr: _contractAddr,
waitPeriod: _waitPeriod,
changeStartTime: 0,
inContractChange: false,
inWaitPeriodChange: false,
exists: true
});
emit AddNewContract(msg.sender, _id, _contractAddr, _waitPeriod);
}
/// @notice Reverts 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(bytes4 _id) public onlyOwner {
if (!(entries[_id].exists)){
revert EntryNonExistentError(_id);
}
if (previousAddresses[_id] == address(0)){
revert EmptyPrevAddrError(_id);
}
address currentAddr = entries[_id].contractAddr;
entries[_id].contractAddr = previousAddresses[_id];
emit RevertToPreviousAddress(msg.sender, _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(bytes4 _id, address _newContractAddr) public onlyOwner {
if (!entries[_id].exists){
revert EntryNonExistentError(_id);
}
if (entries[_id].inWaitPeriodChange){
revert AlreadyInWaitPeriodChangeError(_id);
}
entries[_id].changeStartTime = block.timestamp; // solhint-disable-line
entries[_id].inContractChange = true;
pendingAddresses[_id] = _newContractAddr;
emit StartContractChange(msg.sender, _id, entries[_id].contractAddr, _newContractAddr);
}
/// @notice Changes new contract address, correct time must have passed
/// @param _id Id of contract
function approveContractChange(bytes4 _id) public onlyOwner {
if (!entries[_id].exists){
revert EntryNonExistentError(_id);
}
if (!entries[_id].inContractChange){
revert EntryNotInChangeError(_id);
}
if (block.timestamp < (entries[_id].changeStartTime + entries[_id].waitPeriod)){// solhint-disable-line
revert ChangeNotReadyError(block.timestamp, (entries[_id].changeStartTime + entries[_id].waitPeriod));
}
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;
emit ApproveContractChange(msg.sender, _id, oldContractAddr, entries[_id].contractAddr);
}
/// @notice Cancel pending change
/// @param _id Id of contract
function cancelContractChange(bytes4 _id) public onlyOwner {
if (!entries[_id].exists){
revert EntryNonExistentError(_id);
}
if (!entries[_id].inContractChange){
revert EntryNotInChangeError(_id);
}
address oldContractAddr = pendingAddresses[_id];
pendingAddresses[_id] = address(0);
entries[_id].inContractChange = false;
entries[_id].changeStartTime = 0;
emit CancelContractChange(msg.sender, _id, oldContractAddr, entries[_id].contractAddr);
}
/// @notice Starts the change for waitPeriod
/// @param _id Id of contract
/// @param _newWaitPeriod New wait time
function startWaitPeriodChange(bytes4 _id, uint256 _newWaitPeriod) public onlyOwner {
if (!entries[_id].exists){
revert EntryNonExistentError(_id);
}
if (entries[_id].inContractChange){
revert AlreadyInContractChangeError(_id);
}
pendingWaitTimes[_id] = _newWaitPeriod;
entries[_id].changeStartTime = block.timestamp; // solhint-disable-line
entries[_id].inWaitPeriodChange = true;
emit StartWaitPeriodChange(msg.sender, _id, _newWaitPeriod);
}
/// @notice Changes new wait period, correct time must have passed
/// @param _id Id of contract
function approveWaitPeriodChange(bytes4 _id) public onlyOwner {
if (!entries[_id].exists){
revert EntryNonExistentError(_id);
}
if (!entries[_id].inWaitPeriodChange){
revert EntryNotInChangeError(_id);
}
if (block.timestamp < (entries[_id].changeStartTime + entries[_id].waitPeriod)){ // solhint-disable-line
revert ChangeNotReadyError(block.timestamp, (entries[_id].changeStartTime + entries[_id].waitPeriod));
}
uint256 oldWaitTime = entries[_id].waitPeriod;
entries[_id].waitPeriod = pendingWaitTimes[_id];
entries[_id].inWaitPeriodChange = false;
entries[_id].changeStartTime = 0;
pendingWaitTimes[_id] = 0;
emit ApproveWaitPeriodChange(msg.sender, _id, oldWaitTime, entries[_id].waitPeriod);
}
/// @notice Cancel wait period change
/// @param _id Id of contract
function cancelWaitPeriodChange(bytes4 _id) public onlyOwner {
if (!entries[_id].exists){
revert EntryNonExistentError(_id);
}
if (!entries[_id].inWaitPeriodChange){
revert EntryNotInChangeError(_id);
}
uint256 oldWaitPeriod = pendingWaitTimes[_id];
pendingWaitTimes[_id] = 0;
entries[_id].inWaitPeriodChange = false;
entries[_id].changeStartTime = 0;
emit CancelWaitPeriodChange(msg.sender, _id, oldWaitPeriod, entries[_id].waitPeriod);
}
}
contract DefisaverLogger {
event RecipeEvent(
address indexed caller,
string indexed logName
);
event ActionDirectEvent(
address indexed caller,
string indexed logName,
bytes data
);
function logRecipeEvent(
string memory _logName
) public {
emit RecipeEvent(msg.sender, _logName);
}
function logActionDirectEvent(
string memory _logName,
bytes memory _data
) public {
emit ActionDirectEvent(msg.sender, _logName, _data);
}
}
contract MainnetActionsUtilAddresses {
address internal constant DFS_REG_CONTROLLER_ADDR = 0xF8f8B3C98Cf2E63Df3041b73f80F362a4cf3A576;
address internal constant REGISTRY_ADDR = 0x287778F121F134C66212FB16c9b53eC991D32f5b;
address internal constant DFS_LOGGER_ADDR = 0xcE7a977Cac4a481bc84AC06b2Da0df614e621cf3;
}
contract ActionsUtilHelper is MainnetActionsUtilAddresses {
}
abstract contract ActionBase is AdminAuth, ActionsUtilHelper {
event ActionEvent(
string indexed logName,
bytes data
);
DFSRegistry public constant registry = DFSRegistry(REGISTRY_ADDR);
DefisaverLogger public constant logger = DefisaverLogger(
DFS_LOGGER_ADDR
);
//Wrong sub index value
error SubIndexValueError();
//Wrong return index value
error ReturnIndexValueError();
/// @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, FEE_ACTION, CHECK_ACTION, CUSTOM_ACTION }
/// @notice Parses inputs and runs the implemented action through a proxy
/// @dev Is called by the RecipeExecutor 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,
bytes32[] 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 replace the input value with
/// @param _returnValues Array of subscription data we can replace the input value with
function _parseParamUint(
uint _param,
uint8 _mapType,
bytes32[] memory _subData,
bytes32[] memory _returnValues
) internal pure returns (uint) {
if (isReplaceable(_mapType)) {
if (isReturnInjection(_mapType)) {
_param = uint(_returnValues[getReturnIndex(_mapType)]);
} else {
_param = uint256(_subData[getSubIndex(_mapType)]);
}
}
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 replace the input value with
/// @param _returnValues Array of subscription data we can replace the input value with
function _parseParamAddr(
address _param,
uint8 _mapType,
bytes32[] memory _subData,
bytes32[] memory _returnValues
) internal view returns (address) {
if (isReplaceable(_mapType)) {
if (isReturnInjection(_mapType)) {
_param = address(bytes20((_returnValues[getReturnIndex(_mapType)])));
} else {
/// @dev The last two values are specially reserved for proxy addr and owner addr
if (_mapType == 254) return address(this); //DSProxy address
if (_mapType == 255) return DSProxy(payable(address(this))).owner(); // owner of DSProxy
_param = address(uint160(uint256(_subData[getSubIndex(_mapType)])));
}
}
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 replace the input value with
/// @param _returnValues Array of subscription data we can replace the input value with
function _parseParamABytes32(
bytes32 _param,
uint8 _mapType,
bytes32[] memory _subData,
bytes32[] memory _returnValues
) internal pure returns (bytes32) {
if (isReplaceable(_mapType)) {
if (isReturnInjection(_mapType)) {
_param = (_returnValues[getReturnIndex(_mapType)]);
} else {
_param = _subData[getSubIndex(_mapType)];
}
}
return _param;
}
/// @notice Checks if the paramMapping value indicated that we need to inject values
/// @param _type Indicated the type of the input
function isReplaceable(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) {
if (!(isReturnInjection(_type))){
revert SubIndexValueError();
}
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) {
if (_type < SUB_MIN_INDEX_VALUE){
revert ReturnIndexValueError();
}
return (_type - SUB_MIN_INDEX_VALUE);
}
}
contract McdGive is ActionBase {
address public constant PROXY_REGISTRY_ADDR = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4;
//Can't send vault to 0x0
error NoBurnVaultError();
struct Params {
uint256 vaultId;
address newOwner;
bool createProxy;
address mcdManager;
}
/// @inheritdoc ActionBase
function executeAction(
bytes memory _callData,
bytes32[] memory _subData,
uint8[] memory _paramMapping,
bytes32[] memory _returnValues
) public payable virtual override returns (bytes32) {
Params memory inputData = parseInputs(_callData);
inputData.vaultId = _parseParamUint(inputData.vaultId, _paramMapping[0], _subData, _returnValues);
inputData.newOwner = _parseParamAddr(inputData.newOwner, _paramMapping[1], _subData, _returnValues);
inputData.mcdManager = _parseParamAddr(inputData.mcdManager, _paramMapping[2], _subData, _returnValues);
(address newOwner, bytes memory logData) = _mcdGive(inputData.vaultId, inputData.newOwner, inputData.createProxy, inputData.mcdManager);
emit ActionEvent("McdGive", logData);
return bytes32(bytes20(newOwner));
}
/// @inheritdoc ActionBase
function executeActionDirect(bytes memory _callData) public payable override {
Params memory inputData = parseInputs(_callData);
(, bytes memory logData) = _mcdGive(inputData.vaultId, inputData.newOwner, inputData.createProxy, inputData.mcdManager);
logger.logActionDirectEvent("McdGive", logData);
}
/// @inheritdoc ActionBase
function actionType() public pure virtual override returns (uint8) {
return uint8(ActionType.STANDARD_ACTION);
}
//////////////////////////// ACTION LOGIC ////////////////////////////
/// @notice Gives the vault ownership to a different address
/// @dev If _createProxy is true, vault is always sent to a proxy
/// @param _vaultId The id of the vault
/// @param _newOwner The address of the new owner
/// @param _createProxy If true, it will create a proxy if the _newOwner does not have one
/// @param _mcdManager Manager address
function _mcdGive(
uint256 _vaultId,
address _newOwner,
bool _createProxy,
address _mcdManager
) internal returns (address newOwner, bytes memory logData) {
newOwner = _newOwner;
if (_createProxy) {
address proxy = IProxyRegistry(PROXY_REGISTRY_ADDR).proxies(_newOwner);
if (proxy == address(0) || IDSProxy(proxy).owner() != _newOwner) {
proxy = IProxyRegistry(PROXY_REGISTRY_ADDR).build(_newOwner);
}
newOwner = proxy;
}
if (newOwner == address(0)){
revert NoBurnVaultError();
}
IManager(_mcdManager).give(_vaultId, newOwner);
logData = abi.encode(_vaultId, newOwner, _createProxy, _mcdManager);
}
function parseInputs(bytes memory _callData) public pure returns (Params memory params) {
params = abi.decode(_callData, (Params));
}
}
| Address that owns the DSProxy that owns the CDP _manager Manager contract _cdpId Id of the CDP | function getOwner(IManager _manager, uint _cdpId) public view returns (address) {
DSProxy proxy = DSProxy(payable(address(uint160(_manager.owns(_cdpId)))));
return proxy.owner();
}
| 1,503,481 |
/*
Copyright 2021 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
pragma experimental "ABIEncoderV2";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import { AaveV2 } from "../integration/lib/AaveV2.sol";
import { IAToken } from "../../interfaces/external/aave-v2/IAToken.sol";
import { IController } from "../../interfaces/IController.sol";
import { IDebtIssuanceModule } from "../../interfaces/IDebtIssuanceModule.sol";
import { IExchangeAdapter } from "../../interfaces/IExchangeAdapter.sol";
import { ILendingPool } from "../../interfaces/external/aave-v2/ILendingPool.sol";
import { ILendingPoolAddressesProvider } from "../../interfaces/external/aave-v2/ILendingPoolAddressesProvider.sol";
import { IModuleIssuanceHook } from "../../interfaces/IModuleIssuanceHook.sol";
import { IProtocolDataProvider } from "../../interfaces/external/aave-v2/IProtocolDataProvider.sol";
import { ISetToken } from "../../interfaces/ISetToken.sol";
import { IVariableDebtToken } from "../../interfaces/external/aave-v2/IVariableDebtToken.sol";
import { ModuleBase } from "../lib/ModuleBase.sol";
/**
* @title AaveLeverageModule
* @author Set Protocol
* @notice Smart contract that enables leverage trading using Aave as the lending protocol.
* @dev Do not use this module in conjunction with other debt modules that allow Aave debt positions as it could lead to double counting of
* debt when borrowed assets are the same.
*/
contract AaveLeverageModule is ModuleBase, ReentrancyGuard, Ownable, IModuleIssuanceHook {
using AaveV2 for ISetToken;
/* ============ Structs ============ */
struct EnabledAssets {
address[] collateralAssets; // Array of enabled underlying collateral assets for a SetToken
address[] borrowAssets; // Array of enabled underlying borrow assets for a SetToken
}
struct ActionInfo {
ISetToken setToken; // SetToken instance
ILendingPool lendingPool; // Lending pool instance, we grab this everytime since it's best practice not to store
IExchangeAdapter exchangeAdapter; // Exchange adapter instance
uint256 setTotalSupply; // Total supply of SetToken
uint256 notionalSendQuantity; // Total notional quantity sent to exchange
uint256 minNotionalReceiveQuantity; // Min total notional received from exchange
IERC20 collateralAsset; // Address of collateral asset
IERC20 borrowAsset; // Address of borrow asset
uint256 preTradeReceiveTokenBalance; // Balance of pre-trade receive token balance
}
struct ReserveTokens {
IAToken aToken; // Reserve's aToken instance
IVariableDebtToken variableDebtToken; // Reserve's variable debt token instance
}
/* ============ Events ============ */
/**
* @dev Emitted on lever()
* @param _setToken Instance of the SetToken being levered
* @param _borrowAsset Asset being borrowed for leverage
* @param _collateralAsset Collateral asset being levered
* @param _exchangeAdapter Exchange adapter used for trading
* @param _totalBorrowAmount Total amount of `_borrowAsset` borrowed
* @param _totalReceiveAmount Total amount of `_collateralAsset` received by selling `_borrowAsset`
* @param _protocolFee Protocol fee charged
*/
event LeverageIncreased(
ISetToken indexed _setToken,
IERC20 indexed _borrowAsset,
IERC20 indexed _collateralAsset,
IExchangeAdapter _exchangeAdapter,
uint256 _totalBorrowAmount,
uint256 _totalReceiveAmount,
uint256 _protocolFee
);
/**
* @dev Emitted on delever() and deleverToZeroBorrowBalance()
* @param _setToken Instance of the SetToken being delevered
* @param _collateralAsset Asset sold to decrease leverage
* @param _repayAsset Asset being bought to repay to Aave
* @param _exchangeAdapter Exchange adapter used for trading
* @param _totalRedeemAmount Total amount of `_collateralAsset` being sold
* @param _totalRepayAmount Total amount of `_repayAsset` being repaid
* @param _protocolFee Protocol fee charged
*/
event LeverageDecreased(
ISetToken indexed _setToken,
IERC20 indexed _collateralAsset,
IERC20 indexed _repayAsset,
IExchangeAdapter _exchangeAdapter,
uint256 _totalRedeemAmount,
uint256 _totalRepayAmount,
uint256 _protocolFee
);
/**
* @dev Emitted on addCollateralAssets() and removeCollateralAssets()
* @param _setToken Instance of SetToken whose collateral assets is updated
* @param _added true if assets are added false if removed
* @param _assets Array of collateral assets being added/removed
*/
event CollateralAssetsUpdated(
ISetToken indexed _setToken,
bool indexed _added,
IERC20[] _assets
);
/**
* @dev Emitted on addBorrowAssets() and removeBorrowAssets()
* @param _setToken Instance of SetToken whose borrow assets is updated
* @param _added true if assets are added false if removed
* @param _assets Array of borrow assets being added/removed
*/
event BorrowAssetsUpdated(
ISetToken indexed _setToken,
bool indexed _added,
IERC20[] _assets
);
/**
* @dev Emitted when `underlyingToReserveTokensMappings` is updated
* @param _underlying Address of the underlying asset
* @param _aToken Updated aave reserve aToken
* @param _variableDebtToken Updated aave reserve variable debt token
*/
event ReserveTokensUpdated(
IERC20 indexed _underlying,
IAToken indexed _aToken,
IVariableDebtToken indexed _variableDebtToken
);
/**
* @dev Emitted on updateAllowedSetToken()
* @param _setToken SetToken being whose allowance to initialize this module is being updated
* @param _added true if added false if removed
*/
event SetTokenStatusUpdated(
ISetToken indexed _setToken,
bool indexed _added
);
/**
* @dev Emitted on updateAnySetAllowed()
* @param _anySetAllowed true if any set is allowed to initialize this module, false otherwise
*/
event AnySetAllowedUpdated(
bool indexed _anySetAllowed
);
/* ============ Constants ============ */
// This module only supports borrowing in variable rate mode from Aave which is represented by 2
uint256 constant internal BORROW_RATE_MODE = 2;
// String identifying the DebtIssuanceModule in the IntegrationRegistry. Note: Governance must add DefaultIssuanceModule as
// the string as the integration name
string constant internal DEFAULT_ISSUANCE_MODULE_NAME = "DefaultIssuanceModule";
// 0 index stores protocol fee % on the controller, charged in the _executeTrade function
uint256 constant internal PROTOCOL_TRADE_FEE_INDEX = 0;
/* ============ State Variables ============ */
// Mapping to efficiently fetch reserve token addresses. Tracking Aave reserve token addresses and updating them
// upon requirement is more efficient than fetching them each time from Aave.
// Note: For an underlying asset to be enabled as collateral/borrow asset on SetToken, it must be added to this mapping first.
mapping(IERC20 => ReserveTokens) public underlyingToReserveTokens;
// Used to fetch reserves and user data from AaveV2
IProtocolDataProvider public immutable protocolDataProvider;
// Used to fetch lendingPool address. This contract is immutable and its address will never change.
ILendingPoolAddressesProvider public immutable lendingPoolAddressesProvider;
// Mapping to efficiently check if collateral asset is enabled in SetToken
mapping(ISetToken => mapping(IERC20 => bool)) public collateralAssetEnabled;
// Mapping to efficiently check if a borrow asset is enabled in SetToken
mapping(ISetToken => mapping(IERC20 => bool)) public borrowAssetEnabled;
// Internal mapping of enabled collateral and borrow tokens for syncing positions
mapping(ISetToken => EnabledAssets) internal enabledAssets;
// Mapping of SetToken to boolean indicating if SetToken is on allow list. Updateable by governance
mapping(ISetToken => bool) public allowedSetTokens;
// Boolean that returns if any SetToken can initialize this module. If false, then subject to allow list. Updateable by governance.
bool public anySetAllowed;
/* ============ Constructor ============ */
/**
* @dev Instantiate addresses. Underlying to reserve tokens mapping is created.
* @param _controller Address of controller contract
* @param _lendingPoolAddressesProvider Address of Aave LendingPoolAddressProvider
*/
constructor(
IController _controller,
ILendingPoolAddressesProvider _lendingPoolAddressesProvider
)
public
ModuleBase(_controller)
{
lendingPoolAddressesProvider = _lendingPoolAddressesProvider;
IProtocolDataProvider _protocolDataProvider = IProtocolDataProvider(
// Use the raw input vs bytes32() conversion. This is to ensure the input is an uint and not a string.
_lendingPoolAddressesProvider.getAddress(0x0100000000000000000000000000000000000000000000000000000000000000)
);
protocolDataProvider = _protocolDataProvider;
IProtocolDataProvider.TokenData[] memory reserveTokens = _protocolDataProvider.getAllReservesTokens();
for(uint256 i = 0; i < reserveTokens.length; i++) {
(address aToken, , address variableDebtToken) = _protocolDataProvider.getReserveTokensAddresses(reserveTokens[i].tokenAddress);
underlyingToReserveTokens[IERC20(reserveTokens[i].tokenAddress)] = ReserveTokens(IAToken(aToken), IVariableDebtToken(variableDebtToken));
}
}
/* ============ External Functions ============ */
/**
* @dev MANAGER ONLY: Increases leverage for a given collateral position using an enabled borrow asset.
* Borrows _borrowAsset from Aave. Performs a DEX trade, exchanging the _borrowAsset for _collateralAsset.
* Deposits _collateralAsset to Aave and mints corresponding aToken.
* Note: Both collateral and borrow assets need to be enabled, and they must not be the same asset.
* @param _setToken Instance of the SetToken
* @param _borrowAsset Address of underlying asset being borrowed for leverage
* @param _collateralAsset Address of underlying collateral asset
* @param _borrowQuantityUnits Borrow quantity of asset in position units
* @param _minReceiveQuantityUnits Min receive quantity of collateral asset to receive post-trade in position units
* @param _tradeAdapterName Name of trade adapter
* @param _tradeData Arbitrary data for trade
*/
function lever(
ISetToken _setToken,
IERC20 _borrowAsset,
IERC20 _collateralAsset,
uint256 _borrowQuantityUnits,
uint256 _minReceiveQuantityUnits,
string memory _tradeAdapterName,
bytes memory _tradeData
)
external
nonReentrant
onlyManagerAndValidSet(_setToken)
{
// For levering up, send quantity is derived from borrow asset and receive quantity is derived from
// collateral asset
ActionInfo memory leverInfo = _createAndValidateActionInfo(
_setToken,
_borrowAsset,
_collateralAsset,
_borrowQuantityUnits,
_minReceiveQuantityUnits,
_tradeAdapterName,
true
);
_borrow(leverInfo.setToken, leverInfo.lendingPool, leverInfo.borrowAsset, leverInfo.notionalSendQuantity);
uint256 postTradeReceiveQuantity = _executeTrade(leverInfo, _borrowAsset, _collateralAsset, _tradeData);
uint256 protocolFee = _accrueProtocolFee(_setToken, _collateralAsset, postTradeReceiveQuantity);
uint256 postTradeCollateralQuantity = postTradeReceiveQuantity.sub(protocolFee);
_deposit(leverInfo.setToken, leverInfo.lendingPool, _collateralAsset, postTradeCollateralQuantity);
_updateLeverPositions(leverInfo, _borrowAsset);
emit LeverageIncreased(
_setToken,
_borrowAsset,
_collateralAsset,
leverInfo.exchangeAdapter,
leverInfo.notionalSendQuantity,
postTradeCollateralQuantity,
protocolFee
);
}
/**
* @dev MANAGER ONLY: Decrease leverage for a given collateral position using an enabled borrow asset.
* Withdraws _collateralAsset from Aave. Performs a DEX trade, exchanging the _collateralAsset for _repayAsset.
* Repays _repayAsset to Aave and burns corresponding debt tokens.
* Note: Both collateral and borrow assets need to be enabled, and they must not be the same asset.
* @param _setToken Instance of the SetToken
* @param _collateralAsset Address of underlying collateral asset being withdrawn
* @param _repayAsset Address of underlying borrowed asset being repaid
* @param _redeemQuantityUnits Quantity of collateral asset to delever in position units
* @param _minRepayQuantityUnits Minimum amount of repay asset to receive post trade in position units
* @param _tradeAdapterName Name of trade adapter
* @param _tradeData Arbitrary data for trade
*/
function delever(
ISetToken _setToken,
IERC20 _collateralAsset,
IERC20 _repayAsset,
uint256 _redeemQuantityUnits,
uint256 _minRepayQuantityUnits,
string memory _tradeAdapterName,
bytes memory _tradeData
)
external
nonReentrant
onlyManagerAndValidSet(_setToken)
{
// Note: for delevering, send quantity is derived from collateral asset and receive quantity is derived from
// repay asset
ActionInfo memory deleverInfo = _createAndValidateActionInfo(
_setToken,
_collateralAsset,
_repayAsset,
_redeemQuantityUnits,
_minRepayQuantityUnits,
_tradeAdapterName,
false
);
_withdraw(deleverInfo.setToken, deleverInfo.lendingPool, _collateralAsset, deleverInfo.notionalSendQuantity);
uint256 postTradeReceiveQuantity = _executeTrade(deleverInfo, _collateralAsset, _repayAsset, _tradeData);
uint256 protocolFee = _accrueProtocolFee(_setToken, _repayAsset, postTradeReceiveQuantity);
uint256 repayQuantity = postTradeReceiveQuantity.sub(protocolFee);
_repayBorrow(deleverInfo.setToken, deleverInfo.lendingPool, _repayAsset, repayQuantity);
_updateDeleverPositions(deleverInfo, _repayAsset);
emit LeverageDecreased(
_setToken,
_collateralAsset,
_repayAsset,
deleverInfo.exchangeAdapter,
deleverInfo.notionalSendQuantity,
repayQuantity,
protocolFee
);
}
/** @dev MANAGER ONLY: Pays down the borrow asset to 0 selling off a given amount of collateral asset.
* Withdraws _collateralAsset from Aave. Performs a DEX trade, exchanging the _collateralAsset for _repayAsset.
* Minimum receive amount for the DEX trade is set to the current variable debt balance of the borrow asset.
* Repays received _repayAsset to Aave which burns corresponding debt tokens. Any extra received borrow asset is .
* updated as equity. No protocol fee is charged.
* Note: Both collateral and borrow assets need to be enabled, and they must not be the same asset.
* The function reverts if not enough collateral asset is redeemed to buy the required minimum amount of _repayAsset.
* @param _setToken Instance of the SetToken
* @param _collateralAsset Address of underlying collateral asset being redeemed
* @param _repayAsset Address of underlying asset being repaid
* @param _redeemQuantityUnits Quantity of collateral asset to delever in position units
* @param _tradeAdapterName Name of trade adapter
* @param _tradeData Arbitrary data for trade
* @return uint256 Notional repay quantity
*/
function deleverToZeroBorrowBalance(
ISetToken _setToken,
IERC20 _collateralAsset,
IERC20 _repayAsset,
uint256 _redeemQuantityUnits,
string memory _tradeAdapterName,
bytes memory _tradeData
)
external
nonReentrant
onlyManagerAndValidSet(_setToken)
returns (uint256)
{
uint256 setTotalSupply = _setToken.totalSupply();
uint256 notionalRedeemQuantity = _redeemQuantityUnits.preciseMul(setTotalSupply);
require(borrowAssetEnabled[_setToken][_repayAsset], "Borrow not enabled");
uint256 notionalRepayQuantity = underlyingToReserveTokens[_repayAsset].variableDebtToken.balanceOf(address(_setToken));
require(notionalRepayQuantity > 0, "Borrow balance is zero");
ActionInfo memory deleverInfo = _createAndValidateActionInfoNotional(
_setToken,
_collateralAsset,
_repayAsset,
notionalRedeemQuantity,
notionalRepayQuantity,
_tradeAdapterName,
false,
setTotalSupply
);
_withdraw(deleverInfo.setToken, deleverInfo.lendingPool, _collateralAsset, deleverInfo.notionalSendQuantity);
_executeTrade(deleverInfo, _collateralAsset, _repayAsset, _tradeData);
_repayBorrow(deleverInfo.setToken, deleverInfo.lendingPool, _repayAsset, notionalRepayQuantity);
_updateDeleverPositions(deleverInfo, _repayAsset);
emit LeverageDecreased(
_setToken,
_collateralAsset,
_repayAsset,
deleverInfo.exchangeAdapter,
deleverInfo.notionalSendQuantity,
notionalRepayQuantity,
0 // No protocol fee
);
return notionalRepayQuantity;
}
/**
* @dev CALLABLE BY ANYBODY: Sync Set positions with ALL enabled Aave collateral and borrow positions.
* For collateral assets, update aToken default position. For borrow assets, update external borrow position.
* - Collateral assets may come out of sync when interest is accrued or a position is liquidated
* - Borrow assets may come out of sync when interest is accrued or position is liquidated and borrow is repaid
* Note: In Aave, both collateral and borrow interest is accrued in each block by increasing the balance of
* aTokens and debtTokens for each user, and 1 aToken = 1 variableDebtToken = 1 underlying.
* @param _setToken Instance of the SetToken
*/
function sync(ISetToken _setToken) public nonReentrant onlyValidAndInitializedSet(_setToken) {
uint256 setTotalSupply = _setToken.totalSupply();
// Only sync positions when Set supply is not 0. Without this check, if sync is called by someone before the
// first issuance, then editDefaultPosition would remove the default positions from the SetToken
if (setTotalSupply > 0) {
address[] memory collateralAssets = enabledAssets[_setToken].collateralAssets;
for(uint256 i = 0; i < collateralAssets.length; i++) {
IAToken aToken = underlyingToReserveTokens[IERC20(collateralAssets[i])].aToken;
uint256 previousPositionUnit = _setToken.getDefaultPositionRealUnit(address(aToken)).toUint256();
uint256 newPositionUnit = _getCollateralPosition(_setToken, aToken, setTotalSupply);
// Note: Accounts for if position does not exist on SetToken but is tracked in enabledAssets
if (previousPositionUnit != newPositionUnit) {
_updateCollateralPosition(_setToken, aToken, newPositionUnit);
}
}
address[] memory borrowAssets = enabledAssets[_setToken].borrowAssets;
for(uint256 i = 0; i < borrowAssets.length; i++) {
IERC20 borrowAsset = IERC20(borrowAssets[i]);
int256 previousPositionUnit = _setToken.getExternalPositionRealUnit(address(borrowAsset), address(this));
int256 newPositionUnit = _getBorrowPosition(_setToken, borrowAsset, setTotalSupply);
// Note: Accounts for if position does not exist on SetToken but is tracked in enabledAssets
if (newPositionUnit != previousPositionUnit) {
_updateBorrowPosition(_setToken, borrowAsset, newPositionUnit);
}
}
}
}
/**
* @dev MANAGER ONLY: Initializes this module to the SetToken. Either the SetToken needs to be on the allowed list
* or anySetAllowed needs to be true. Only callable by the SetToken's manager.
* Note: Managers can enable collateral and borrow assets that don't exist as positions on the SetToken
* @param _setToken Instance of the SetToken to initialize
* @param _collateralAssets Underlying tokens to be enabled as collateral in the SetToken
* @param _borrowAssets Underlying tokens to be enabled as borrow in the SetToken
*/
function initialize(
ISetToken _setToken,
IERC20[] memory _collateralAssets,
IERC20[] memory _borrowAssets
)
external
onlySetManager(_setToken, msg.sender)
onlyValidAndPendingSet(_setToken)
{
if (!anySetAllowed) {
require(allowedSetTokens[_setToken], "Not allowed SetToken");
}
// Initialize module before trying register
_setToken.initializeModule();
// Get debt issuance module registered to this module and require that it is initialized
require(_setToken.isInitializedModule(getAndValidateAdapter(DEFAULT_ISSUANCE_MODULE_NAME)), "Issuance not initialized");
// Try if register exists on any of the modules including the debt issuance module
address[] memory modules = _setToken.getModules();
for(uint256 i = 0; i < modules.length; i++) {
try IDebtIssuanceModule(modules[i]).registerToIssuanceModule(_setToken) {} catch {}
}
// _collateralAssets and _borrowAssets arrays are validated in their respective internal functions
_addCollateralAssets(_setToken, _collateralAssets);
_addBorrowAssets(_setToken, _borrowAssets);
}
/**
* @dev MANAGER ONLY: Removes this module from the SetToken, via call by the SetToken. Any deposited collateral assets
* are disabled to be used as collateral on Aave. Aave Settings and manager enabled assets state is deleted.
* Note: Function will revert is there is any debt remaining on Aave
*/
function removeModule() external override onlyValidAndInitializedSet(ISetToken(msg.sender)) {
ISetToken setToken = ISetToken(msg.sender);
// Sync Aave and SetToken positions prior to any removal action
sync(setToken);
address[] memory borrowAssets = enabledAssets[setToken].borrowAssets;
for(uint256 i = 0; i < borrowAssets.length; i++) {
IERC20 borrowAsset = IERC20(borrowAssets[i]);
require(underlyingToReserveTokens[borrowAsset].variableDebtToken.balanceOf(address(setToken)) == 0, "Variable debt remaining");
delete borrowAssetEnabled[setToken][borrowAsset];
}
address[] memory collateralAssets = enabledAssets[setToken].collateralAssets;
for(uint256 i = 0; i < collateralAssets.length; i++) {
IERC20 collateralAsset = IERC20(collateralAssets[i]);
_updateUseReserveAsCollateral(setToken, collateralAsset, false);
delete collateralAssetEnabled[setToken][collateralAsset];
}
delete enabledAssets[setToken];
// Try if unregister exists on any of the modules
address[] memory modules = setToken.getModules();
for(uint256 i = 0; i < modules.length; i++) {
try IDebtIssuanceModule(modules[i]).unregisterFromIssuanceModule(setToken) {} catch {}
}
}
/**
* @dev MANAGER ONLY: Add registration of this module on the debt issuance module for the SetToken.
* Note: if the debt issuance module is not added to SetToken before this module is initialized, then this function
* needs to be called if the debt issuance module is later added and initialized to prevent state inconsistencies
* @param _setToken Instance of the SetToken
* @param _debtIssuanceModule Debt issuance module address to register
*/
function registerToModule(ISetToken _setToken, IDebtIssuanceModule _debtIssuanceModule) external onlyManagerAndValidSet(_setToken) {
require(_setToken.isInitializedModule(address(_debtIssuanceModule)), "Issuance not initialized");
_debtIssuanceModule.registerToIssuanceModule(_setToken);
}
/**
* @dev CALLABLE BY ANYBODY: Updates `underlyingToReserveTokens` mappings. Reverts if mapping already exists
* or the passed _underlying asset does not have a valid reserve on Aave.
* Note: Call this function when Aave adds a new reserve.
* @param _underlying Address of underlying asset
*/
function addUnderlyingToReserveTokensMapping(IERC20 _underlying) external {
require(address(underlyingToReserveTokens[_underlying].aToken) == address(0), "Mapping already exists");
// An active reserve is an alias for a valid reserve on Aave.
(,,,,,,,, bool isActive,) = protocolDataProvider.getReserveConfigurationData(address(_underlying));
require(isActive, "Invalid aave reserve");
_addUnderlyingToReserveTokensMapping(_underlying);
}
/**
* @dev MANAGER ONLY: Add collateral assets. aTokens corresponding to collateral assets are tracked for syncing positions.
* Note: Reverts with "Collateral already enabled" if there are duplicate assets in the passed _newCollateralAssets array.
*
* NOTE: ALL ADDED COLLATERAL ASSETS CAN BE ADDED AS A POSITION ON THE SET TOKEN WITHOUT MANAGER'S EXPLICIT PERMISSION.
* UNWANTED EXTRA POSITIONS CAN BREAK EXTERNAL LOGIC, INCREASE COST OF MINT/REDEEM OF SET TOKEN, AMONG OTHER POTENTIAL UNINTENDED CONSEQUENCES.
* SO, PLEASE ADD ONLY THOSE COLLATERAL ASSETS WHOSE CORRESPONDING aTOKENS ARE NEEDED AS DEFAULT POSITIONS ON THE SET TOKEN.
*
* @param _setToken Instance of the SetToken
* @param _newCollateralAssets Addresses of new collateral underlying assets
*/
function addCollateralAssets(ISetToken _setToken, IERC20[] memory _newCollateralAssets) external onlyManagerAndValidSet(_setToken) {
_addCollateralAssets(_setToken, _newCollateralAssets);
}
/**
* @dev MANAGER ONLY: Remove collateral assets. Disable deposited assets to be used as collateral on Aave market.
* @param _setToken Instance of the SetToken
* @param _collateralAssets Addresses of collateral underlying assets to remove
*/
function removeCollateralAssets(ISetToken _setToken, IERC20[] memory _collateralAssets) external onlyManagerAndValidSet(_setToken) {
for(uint256 i = 0; i < _collateralAssets.length; i++) {
IERC20 collateralAsset = _collateralAssets[i];
require(collateralAssetEnabled[_setToken][collateralAsset], "Collateral not enabled");
_updateUseReserveAsCollateral(_setToken, collateralAsset, false);
delete collateralAssetEnabled[_setToken][collateralAsset];
enabledAssets[_setToken].collateralAssets.removeStorage(address(collateralAsset));
}
emit CollateralAssetsUpdated(_setToken, false, _collateralAssets);
}
/**
* @dev MANAGER ONLY: Add borrow assets. Debt tokens corresponding to borrow assets are tracked for syncing positions.
* Note: Reverts with "Borrow already enabled" if there are duplicate assets in the passed _newBorrowAssets array.
* @param _setToken Instance of the SetToken
* @param _newBorrowAssets Addresses of borrow underlying assets to add
*/
function addBorrowAssets(ISetToken _setToken, IERC20[] memory _newBorrowAssets) external onlyManagerAndValidSet(_setToken) {
_addBorrowAssets(_setToken, _newBorrowAssets);
}
/**
* @dev MANAGER ONLY: Remove borrow assets.
* Note: If there is a borrow balance, borrow asset cannot be removed
* @param _setToken Instance of the SetToken
* @param _borrowAssets Addresses of borrow underlying assets to remove
*/
function removeBorrowAssets(ISetToken _setToken, IERC20[] memory _borrowAssets) external onlyManagerAndValidSet(_setToken) {
for(uint256 i = 0; i < _borrowAssets.length; i++) {
IERC20 borrowAsset = _borrowAssets[i];
require(borrowAssetEnabled[_setToken][borrowAsset], "Borrow not enabled");
require(underlyingToReserveTokens[borrowAsset].variableDebtToken.balanceOf(address(_setToken)) == 0, "Variable debt remaining");
delete borrowAssetEnabled[_setToken][borrowAsset];
enabledAssets[_setToken].borrowAssets.removeStorage(address(borrowAsset));
}
emit BorrowAssetsUpdated(_setToken, false, _borrowAssets);
}
/**
* @dev GOVERNANCE ONLY: Enable/disable ability of a SetToken to initialize this module. Only callable by governance.
* @param _setToken Instance of the SetToken
* @param _status Bool indicating if _setToken is allowed to initialize this module
*/
function updateAllowedSetToken(ISetToken _setToken, bool _status) external onlyOwner {
require(controller.isSet(address(_setToken)) || allowedSetTokens[_setToken], "Invalid SetToken");
allowedSetTokens[_setToken] = _status;
emit SetTokenStatusUpdated(_setToken, _status);
}
/**
* @dev GOVERNANCE ONLY: Toggle whether ANY SetToken is allowed to initialize this module. Only callable by governance.
* @param _anySetAllowed Bool indicating if ANY SetToken is allowed to initialize this module
*/
function updateAnySetAllowed(bool _anySetAllowed) external onlyOwner {
anySetAllowed = _anySetAllowed;
emit AnySetAllowedUpdated(_anySetAllowed);
}
/**
* @dev MODULE ONLY: Hook called prior to issuance to sync positions on SetToken. Only callable by valid module.
* @param _setToken Instance of the SetToken
*/
function moduleIssueHook(ISetToken _setToken, uint256 /* _setTokenQuantity */) external override onlyModule(_setToken) {
sync(_setToken);
}
/**
* @dev MODULE ONLY: Hook called prior to redemption to sync positions on SetToken. For redemption, always use current borrowed
* balance after interest accrual. Only callable by valid module.
* @param _setToken Instance of the SetToken
*/
function moduleRedeemHook(ISetToken _setToken, uint256 /* _setTokenQuantity */) external override onlyModule(_setToken) {
sync(_setToken);
}
/**
* @dev MODULE ONLY: Hook called prior to looping through each component on issuance. Invokes borrow in order for
* module to return debt to issuer. Only callable by valid module.
* @param _setToken Instance of the SetToken
* @param _setTokenQuantity Quantity of SetToken
* @param _component Address of component
*/
function componentIssueHook(ISetToken _setToken, uint256 _setTokenQuantity, IERC20 _component, bool _isEquity) external override onlyModule(_setToken) {
// Check hook not being called for an equity position. If hook is called with equity position and outstanding borrow position
// exists the loan would be taken out twice potentially leading to liquidation
if (!_isEquity) {
int256 componentDebt = _setToken.getExternalPositionRealUnit(address(_component), address(this));
require(componentDebt < 0, "Component must be negative");
uint256 notionalDebt = componentDebt.mul(-1).toUint256().preciseMul(_setTokenQuantity);
_borrowForHook(_setToken, _component, notionalDebt);
}
}
/**
* @dev MODULE ONLY: Hook called prior to looping through each component on redemption. Invokes repay after
* the issuance module transfers debt from the issuer. Only callable by valid module.
* @param _setToken Instance of the SetToken
* @param _setTokenQuantity Quantity of SetToken
* @param _component Address of component
*/
function componentRedeemHook(ISetToken _setToken, uint256 _setTokenQuantity, IERC20 _component, bool _isEquity) external override onlyModule(_setToken) {
// Check hook not being called for an equity position. If hook is called with equity position and outstanding borrow position
// exists the loan would be paid down twice, decollateralizing the Set
if (!_isEquity) {
int256 componentDebt = _setToken.getExternalPositionRealUnit(address(_component), address(this));
require(componentDebt < 0, "Component must be negative");
uint256 notionalDebt = componentDebt.mul(-1).toUint256().preciseMulCeil(_setTokenQuantity);
_repayBorrowForHook(_setToken, _component, notionalDebt);
}
}
/* ============ External Getter Functions ============ */
/**
* @dev Get enabled assets for SetToken. Returns an array of collateral and borrow assets.
* @return Underlying collateral assets that are enabled
* @return Underlying borrowed assets that are enabled
*/
function getEnabledAssets(ISetToken _setToken) external view returns(address[] memory, address[] memory) {
return (
enabledAssets[_setToken].collateralAssets,
enabledAssets[_setToken].borrowAssets
);
}
/* ============ Internal Functions ============ */
/**
* @dev Invoke deposit from SetToken using AaveV2 library. Mints aTokens for SetToken.
*/
function _deposit(ISetToken _setToken, ILendingPool _lendingPool, IERC20 _asset, uint256 _notionalQuantity) internal {
_setToken.invokeApprove(address(_asset), address(_lendingPool), _notionalQuantity);
_setToken.invokeDeposit(_lendingPool, address(_asset), _notionalQuantity);
}
/**
* @dev Invoke withdraw from SetToken using AaveV2 library. Burns aTokens and returns underlying to SetToken.
*/
function _withdraw(ISetToken _setToken, ILendingPool _lendingPool, IERC20 _asset, uint256 _notionalQuantity) internal {
_setToken.invokeWithdraw(_lendingPool, address(_asset), _notionalQuantity);
}
/**
* @dev Invoke repay from SetToken using AaveV2 library. Burns DebtTokens for SetToken.
*/
function _repayBorrow(ISetToken _setToken, ILendingPool _lendingPool, IERC20 _asset, uint256 _notionalQuantity) internal {
_setToken.invokeApprove(address(_asset), address(_lendingPool), _notionalQuantity);
_setToken.invokeRepay(_lendingPool, address(_asset), _notionalQuantity, BORROW_RATE_MODE);
}
/**
* @dev Invoke borrow from the SetToken during issuance hook. Since we only need to interact with AAVE once we fetch the
* lending pool in this function to optimize vs forcing a fetch twice during lever/delever.
*/
function _repayBorrowForHook(ISetToken _setToken, IERC20 _asset, uint256 _notionalQuantity) internal {
_repayBorrow(_setToken, ILendingPool(lendingPoolAddressesProvider.getLendingPool()), _asset, _notionalQuantity);
}
/**
* @dev Invoke borrow from the SetToken using AaveV2 library. Mints DebtTokens for SetToken.
*/
function _borrow(ISetToken _setToken, ILendingPool _lendingPool, IERC20 _asset, uint256 _notionalQuantity) internal {
_setToken.invokeBorrow(_lendingPool, address(_asset), _notionalQuantity, BORROW_RATE_MODE);
}
/**
* @dev Invoke borrow from the SetToken during issuance hook. Since we only need to interact with AAVE once we fetch the
* lending pool in this function to optimize vs forcing a fetch twice during lever/delever.
*/
function _borrowForHook(ISetToken _setToken, IERC20 _asset, uint256 _notionalQuantity) internal {
_borrow(_setToken, ILendingPool(lendingPoolAddressesProvider.getLendingPool()), _asset, _notionalQuantity);
}
/**
* @dev Invokes approvals, gets trade call data from exchange adapter and invokes trade from SetToken
* @return uint256 The quantity of tokens received post-trade
*/
function _executeTrade(
ActionInfo memory _actionInfo,
IERC20 _sendToken,
IERC20 _receiveToken,
bytes memory _data
)
internal
returns (uint256)
{
ISetToken setToken = _actionInfo.setToken;
uint256 notionalSendQuantity = _actionInfo.notionalSendQuantity;
setToken.invokeApprove(
address(_sendToken),
_actionInfo.exchangeAdapter.getSpender(),
notionalSendQuantity
);
(
address targetExchange,
uint256 callValue,
bytes memory methodData
) = _actionInfo.exchangeAdapter.getTradeCalldata(
address(_sendToken),
address(_receiveToken),
address(setToken),
notionalSendQuantity,
_actionInfo.minNotionalReceiveQuantity,
_data
);
setToken.invoke(targetExchange, callValue, methodData);
uint256 receiveTokenQuantity = _receiveToken.balanceOf(address(setToken)).sub(_actionInfo.preTradeReceiveTokenBalance);
require(
receiveTokenQuantity >= _actionInfo.minNotionalReceiveQuantity,
"Slippage too high"
);
return receiveTokenQuantity;
}
/**
* @dev Calculates protocol fee on module and pays protocol fee from SetToken
* @return uint256 Total protocol fee paid
*/
function _accrueProtocolFee(ISetToken _setToken, IERC20 _receiveToken, uint256 _exchangedQuantity) internal returns(uint256) {
uint256 protocolFeeTotal = getModuleFee(PROTOCOL_TRADE_FEE_INDEX, _exchangedQuantity);
payProtocolFeeFromSetToken(_setToken, address(_receiveToken), protocolFeeTotal);
return protocolFeeTotal;
}
/**
* @dev Updates the collateral (aToken held) and borrow position (variableDebtToken held) of the SetToken
*/
function _updateLeverPositions(ActionInfo memory _actionInfo, IERC20 _borrowAsset) internal {
IAToken aToken = underlyingToReserveTokens[_actionInfo.collateralAsset].aToken;
_updateCollateralPosition(
_actionInfo.setToken,
aToken,
_getCollateralPosition(
_actionInfo.setToken,
aToken,
_actionInfo.setTotalSupply
)
);
_updateBorrowPosition(
_actionInfo.setToken,
_borrowAsset,
_getBorrowPosition(
_actionInfo.setToken,
_borrowAsset,
_actionInfo.setTotalSupply
)
);
}
/**
* @dev Updates positions as per _updateLeverPositions and updates Default position for borrow asset in case Set is
* delevered all the way to zero any remaining borrow asset after the debt is paid can be added as a position.
*/
function _updateDeleverPositions(ActionInfo memory _actionInfo, IERC20 _repayAsset) internal {
// if amount of tokens traded for exceeds debt, update default position first to save gas on editing borrow position
uint256 repayAssetBalance = _repayAsset.balanceOf(address(_actionInfo.setToken));
if (repayAssetBalance != _actionInfo.preTradeReceiveTokenBalance) {
_actionInfo.setToken.calculateAndEditDefaultPosition(
address(_repayAsset),
_actionInfo.setTotalSupply,
_actionInfo.preTradeReceiveTokenBalance
);
}
_updateLeverPositions(_actionInfo, _repayAsset);
}
/**
* @dev Updates default position unit for given aToken on SetToken
*/
function _updateCollateralPosition(ISetToken _setToken, IAToken _aToken, uint256 _newPositionUnit) internal {
_setToken.editDefaultPosition(address(_aToken), _newPositionUnit);
}
/**
* @dev Updates external position unit for given borrow asset on SetToken
*/
function _updateBorrowPosition(ISetToken _setToken, IERC20 _underlyingAsset, int256 _newPositionUnit) internal {
_setToken.editExternalPosition(address(_underlyingAsset), address(this), _newPositionUnit, "");
}
/**
* @dev Construct the ActionInfo struct for lever and delever
* @return ActionInfo Instance of constructed ActionInfo struct
*/
function _createAndValidateActionInfo(
ISetToken _setToken,
IERC20 _sendToken,
IERC20 _receiveToken,
uint256 _sendQuantityUnits,
uint256 _minReceiveQuantityUnits,
string memory _tradeAdapterName,
bool _isLever
)
internal
view
returns(ActionInfo memory)
{
uint256 totalSupply = _setToken.totalSupply();
return _createAndValidateActionInfoNotional(
_setToken,
_sendToken,
_receiveToken,
_sendQuantityUnits.preciseMul(totalSupply),
_minReceiveQuantityUnits.preciseMul(totalSupply),
_tradeAdapterName,
_isLever,
totalSupply
);
}
/**
* @dev Construct the ActionInfo struct for lever and delever accepting notional units
* @return ActionInfo Instance of constructed ActionInfo struct
*/
function _createAndValidateActionInfoNotional(
ISetToken _setToken,
IERC20 _sendToken,
IERC20 _receiveToken,
uint256 _notionalSendQuantity,
uint256 _minNotionalReceiveQuantity,
string memory _tradeAdapterName,
bool _isLever,
uint256 _setTotalSupply
)
internal
view
returns(ActionInfo memory)
{
ActionInfo memory actionInfo = ActionInfo ({
exchangeAdapter: IExchangeAdapter(getAndValidateAdapter(_tradeAdapterName)),
lendingPool: ILendingPool(lendingPoolAddressesProvider.getLendingPool()),
setToken: _setToken,
collateralAsset: _isLever ? _receiveToken : _sendToken,
borrowAsset: _isLever ? _sendToken : _receiveToken,
setTotalSupply: _setTotalSupply,
notionalSendQuantity: _notionalSendQuantity,
minNotionalReceiveQuantity: _minNotionalReceiveQuantity,
preTradeReceiveTokenBalance: IERC20(_receiveToken).balanceOf(address(_setToken))
});
_validateCommon(actionInfo);
return actionInfo;
}
/**
* @dev Updates `underlyingToReserveTokens` mappings for given `_underlying` asset. Emits ReserveTokensUpdated event.
*/
function _addUnderlyingToReserveTokensMapping(IERC20 _underlying) internal {
(address aToken, , address variableDebtToken) = protocolDataProvider.getReserveTokensAddresses(address(_underlying));
underlyingToReserveTokens[_underlying].aToken = IAToken(aToken);
underlyingToReserveTokens[_underlying].variableDebtToken = IVariableDebtToken(variableDebtToken);
emit ReserveTokensUpdated(_underlying, IAToken(aToken), IVariableDebtToken(variableDebtToken));
}
/**
* @dev Add collateral assets to SetToken. Updates the collateralAssetsEnabled and enabledAssets mappings.
* Emits CollateralAssetsUpdated event.
*/
function _addCollateralAssets(ISetToken _setToken, IERC20[] memory _newCollateralAssets) internal {
for(uint256 i = 0; i < _newCollateralAssets.length; i++) {
IERC20 collateralAsset = _newCollateralAssets[i];
_validateNewCollateralAsset(_setToken, collateralAsset);
_updateUseReserveAsCollateral(_setToken, collateralAsset, true);
collateralAssetEnabled[_setToken][collateralAsset] = true;
enabledAssets[_setToken].collateralAssets.push(address(collateralAsset));
}
emit CollateralAssetsUpdated(_setToken, true, _newCollateralAssets);
}
/**
* @dev Add borrow assets to SetToken. Updates the borrowAssetsEnabled and enabledAssets mappings.
* Emits BorrowAssetsUpdated event.
*/
function _addBorrowAssets(ISetToken _setToken, IERC20[] memory _newBorrowAssets) internal {
for(uint256 i = 0; i < _newBorrowAssets.length; i++) {
IERC20 borrowAsset = _newBorrowAssets[i];
_validateNewBorrowAsset(_setToken, borrowAsset);
borrowAssetEnabled[_setToken][borrowAsset] = true;
enabledAssets[_setToken].borrowAssets.push(address(borrowAsset));
}
emit BorrowAssetsUpdated(_setToken, true, _newBorrowAssets);
}
/**
* @dev Updates SetToken's ability to use an asset as collateral on Aave
*/
function _updateUseReserveAsCollateral(ISetToken _setToken, IERC20 _asset, bool _useAsCollateral) internal {
/*
Note: Aave ENABLES an asset to be used as collateral by `to` address in an `aToken.transfer(to, amount)` call provided
1. msg.sender (from address) isn't the same as `to` address
2. `to` address had zero aToken balance before the transfer
3. transfer `amount` is greater than 0
Note: Aave DISABLES an asset to be used as collateral by `msg.sender`in an `aToken.transfer(to, amount)` call provided
1. msg.sender (from address) isn't the same as `to` address
2. msg.sender has zero balance after the transfer
Different states of the SetToken and what this function does in those states:
Case 1: Manager adds collateral asset to SetToken before first issuance
- Since aToken.balanceOf(setToken) == 0, we do not call `setToken.invokeUserUseReserveAsCollateral` because Aave
requires aToken balance to be greater than 0 before enabling/disabling the underlying asset to be used as collateral
on Aave markets.
Case 2: First issuance of the SetToken
- SetToken was initialized with aToken as default position
- DebtIssuanceModule reads the default position and transfers corresponding aToken from the issuer to the SetToken
- Aave enables aToken to be used as collateral by the SetToken
- Manager calls lever() and the aToken is used as collateral to borrow other assets
Case 3: Manager removes collateral asset from the SetToken
- Disable asset to be used as collateral on SetToken by calling `setToken.invokeSetUserUseReserveAsCollateral` with
useAsCollateral equals false
- Note: If health factor goes below 1 by removing the collateral asset, then Aave reverts on the above call, thus whole
transaction reverts, and manager can't remove corresponding collateral asset
Case 4: Manager adds collateral asset after removing it
- If aToken.balanceOf(setToken) > 0, we call `setToken.invokeUserUseReserveAsCollateral` and the corresponding aToken
is re-enabled as collateral on Aave
Case 5: On redemption/delever/liquidated and aToken balance becomes zero
- Aave disables aToken to be used as collateral by SetToken
Values of variables in below if condition and corresponding action taken:
---------------------------------------------------------------------------------------------------------------------
| usageAsCollateralEnabled | _useAsCollateral | aToken.balanceOf() | Action |
|--------------------------|-------------------|-----------------------|--------------------------------------------|
| true | true | X | Skip invoke. Save gas. |
|--------------------------|-------------------|-----------------------|--------------------------------------------|
| true | false | greater than 0 | Invoke and set to false. |
|--------------------------|-------------------|-----------------------|--------------------------------------------|
| true | false | = 0 | Impossible case. Aave disables usage as |
| | | | collateral when aToken balance becomes 0 |
|--------------------------|-------------------|-----------------------|--------------------------------------------|
| false | false | X | Skip invoke. Save gas. |
|--------------------------|-------------------|-----------------------|--------------------------------------------|
| false | true | greater than 0 | Invoke and set to true. |
|--------------------------|-------------------|-----------------------|--------------------------------------------|
| false | true | = 0 | Don't invoke. Will revert. |
---------------------------------------------------------------------------------------------------------------------
*/
(,,,,,,,,bool usageAsCollateralEnabled) = protocolDataProvider.getUserReserveData(address(_asset), address(_setToken));
if (
usageAsCollateralEnabled != _useAsCollateral
&& underlyingToReserveTokens[_asset].aToken.balanceOf(address(_setToken)) > 0
) {
_setToken.invokeSetUserUseReserveAsCollateral(
ILendingPool(lendingPoolAddressesProvider.getLendingPool()),
address(_asset),
_useAsCollateral
);
}
}
/**
* @dev Validate common requirements for lever and delever
*/
function _validateCommon(ActionInfo memory _actionInfo) internal view {
require(collateralAssetEnabled[_actionInfo.setToken][_actionInfo.collateralAsset], "Collateral not enabled");
require(borrowAssetEnabled[_actionInfo.setToken][_actionInfo.borrowAsset], "Borrow not enabled");
require(_actionInfo.collateralAsset != _actionInfo.borrowAsset, "Collateral and borrow asset must be different");
require(_actionInfo.notionalSendQuantity > 0, "Quantity is 0");
}
/**
* @dev Validates if a new asset can be added as collateral asset for given SetToken
*/
function _validateNewCollateralAsset(ISetToken _setToken, IERC20 _asset) internal view {
require(!collateralAssetEnabled[_setToken][_asset], "Collateral already enabled");
(address aToken, , ) = protocolDataProvider.getReserveTokensAddresses(address(_asset));
require(address(underlyingToReserveTokens[_asset].aToken) == aToken, "Invalid aToken address");
( , , , , , bool usageAsCollateralEnabled, , , bool isActive, bool isFrozen) = protocolDataProvider.getReserveConfigurationData(address(_asset));
// An active reserve is an alias for a valid reserve on Aave.
// We are checking for the availability of the reserve directly on Aave rather than checking our internal `underlyingToReserveTokens` mappings,
// because our mappings can be out-of-date if a new reserve is added to Aave
require(isActive, "Invalid aave reserve");
// A frozen reserve doesn't allow any new deposit, borrow or rate swap but allows repayments, liquidations and withdrawals
require(!isFrozen, "Frozen aave reserve");
require(usageAsCollateralEnabled, "Collateral disabled on Aave");
}
/**
* @dev Validates if a new asset can be added as borrow asset for given SetToken
*/
function _validateNewBorrowAsset(ISetToken _setToken, IERC20 _asset) internal view {
require(!borrowAssetEnabled[_setToken][_asset], "Borrow already enabled");
( , , address variableDebtToken) = protocolDataProvider.getReserveTokensAddresses(address(_asset));
require(address(underlyingToReserveTokens[_asset].variableDebtToken) == variableDebtToken, "Invalid variable debt token address");
(, , , , , , bool borrowingEnabled, , bool isActive, bool isFrozen) = protocolDataProvider.getReserveConfigurationData(address(_asset));
require(isActive, "Invalid aave reserve");
require(!isFrozen, "Frozen aave reserve");
require(borrowingEnabled, "Borrowing disabled on Aave");
}
/**
* @dev Reads aToken balance and calculates default position unit for given collateral aToken and SetToken
*
* @return uint256 default collateral position unit
*/
function _getCollateralPosition(ISetToken _setToken, IAToken _aToken, uint256 _setTotalSupply) internal view returns (uint256) {
uint256 collateralNotionalBalance = _aToken.balanceOf(address(_setToken));
return collateralNotionalBalance.preciseDiv(_setTotalSupply);
}
/**
* @dev Reads variableDebtToken balance and calculates external position unit for given borrow asset and SetToken
*
* @return int256 external borrow position unit
*/
function _getBorrowPosition(ISetToken _setToken, IERC20 _borrowAsset, uint256 _setTotalSupply) internal view returns (int256) {
uint256 borrowNotionalBalance = underlyingToReserveTokens[_borrowAsset].variableDebtToken.balanceOf(address(_setToken));
return borrowNotionalBalance.preciseDivCeil(_setTotalSupply).toInt256().mul(-1);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../GSN/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
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 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 Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () internal {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
/*
Copyright 2021 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { ILendingPool } from "../../../interfaces/external/aave-v2/ILendingPool.sol";
import { ISetToken } from "../../../interfaces/ISetToken.sol";
/**
* @title AaveV2
* @author Set Protocol
*
* Collection of helper functions for interacting with AaveV2 integrations.
*/
library AaveV2 {
/* ============ External ============ */
/**
* Get deposit calldata from SetToken
*
* Deposits an `_amountNotional` of underlying asset into the reserve, receiving in return overlying aTokens.
* - E.g. User deposits 100 USDC and gets in return 100 aUSDC
* @param _lendingPool Address of the LendingPool contract
* @param _asset The address of the underlying asset to deposit
* @param _amountNotional The amount to be deposited
* @param _onBehalfOf The address that will receive the aTokens, same as msg.sender if the user
* wants to receive them on his own wallet, or a different address if the beneficiary of aTokens
* is a different wallet
* @param _referralCode Code used to register the integrator originating the operation, for potential rewards.
* 0 if the action is executed directly by the user, without any middle-man
*
* @return address Target contract address
* @return uint256 Call value
* @return bytes Deposit calldata
*/
function getDepositCalldata(
ILendingPool _lendingPool,
address _asset,
uint256 _amountNotional,
address _onBehalfOf,
uint16 _referralCode
)
public
pure
returns (address, uint256, bytes memory)
{
bytes memory callData = abi.encodeWithSignature(
"deposit(address,uint256,address,uint16)",
_asset,
_amountNotional,
_onBehalfOf,
_referralCode
);
return (address(_lendingPool), 0, callData);
}
/**
* Invoke deposit on LendingPool from SetToken
*
* Deposits an `_amountNotional` of underlying asset into the reserve, receiving in return overlying aTokens.
* - E.g. SetToken deposits 100 USDC and gets in return 100 aUSDC
* @param _setToken Address of the SetToken
* @param _lendingPool Address of the LendingPool contract
* @param _asset The address of the underlying asset to deposit
* @param _amountNotional The amount to be deposited
*/
function invokeDeposit(
ISetToken _setToken,
ILendingPool _lendingPool,
address _asset,
uint256 _amountNotional
)
external
{
( , , bytes memory depositCalldata) = getDepositCalldata(
_lendingPool,
_asset,
_amountNotional,
address(_setToken),
0
);
_setToken.invoke(address(_lendingPool), 0, depositCalldata);
}
/**
* Get withdraw calldata from SetToken
*
* Withdraws an `_amountNotional` of underlying asset from the reserve, burning the equivalent aTokens owned
* - E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC
* @param _lendingPool Address of the LendingPool contract
* @param _asset The address of the underlying asset to withdraw
* @param _amountNotional The underlying amount to be withdrawn
* Note: Passing type(uint256).max will withdraw the entire aToken balance
* @param _receiver Address that will receive the underlying, same as msg.sender if the user
* wants to receive it on his own wallet, or a different address if the beneficiary is a
* different wallet
*
* @return address Target contract address
* @return uint256 Call value
* @return bytes Withdraw calldata
*/
function getWithdrawCalldata(
ILendingPool _lendingPool,
address _asset,
uint256 _amountNotional,
address _receiver
)
public
pure
returns (address, uint256, bytes memory)
{
bytes memory callData = abi.encodeWithSignature(
"withdraw(address,uint256,address)",
_asset,
_amountNotional,
_receiver
);
return (address(_lendingPool), 0, callData);
}
/**
* Invoke withdraw on LendingPool from SetToken
*
* Withdraws an `_amountNotional` of underlying asset from the reserve, burning the equivalent aTokens owned
* - E.g. SetToken has 100 aUSDC, and receives 100 USDC, burning the 100 aUSDC
*
* @param _setToken Address of the SetToken
* @param _lendingPool Address of the LendingPool contract
* @param _asset The address of the underlying asset to withdraw
* @param _amountNotional The underlying amount to be withdrawn
* Note: Passing type(uint256).max will withdraw the entire aToken balance
*
* @return uint256 The final amount withdrawn
*/
function invokeWithdraw(
ISetToken _setToken,
ILendingPool _lendingPool,
address _asset,
uint256 _amountNotional
)
external
returns (uint256)
{
( , , bytes memory withdrawCalldata) = getWithdrawCalldata(
_lendingPool,
_asset,
_amountNotional,
address(_setToken)
);
return abi.decode(_setToken.invoke(address(_lendingPool), 0, withdrawCalldata), (uint256));
}
/**
* Get borrow calldata from SetToken
*
* Allows users to borrow a specific `_amountNotional` of the reserve underlying `_asset`, provided that
* the borrower already deposited enough collateral, or he was given enough allowance by a credit delegator
* on the corresponding debt token (StableDebtToken or VariableDebtToken)
*
* @param _lendingPool Address of the LendingPool contract
* @param _asset The address of the underlying asset to borrow
* @param _amountNotional The amount to be borrowed
* @param _interestRateMode The interest rate mode at which the user wants to borrow: 1 for Stable, 2 for Variable
* @param _referralCode Code used to register the integrator originating the operation, for potential rewards.
* 0 if the action is executed directly by the user, without any middle-man
* @param _onBehalfOf Address of the user who will receive the debt. Should be the address of the borrower itself
* calling the function if he wants to borrow against his own collateral, or the address of the
* credit delegator if he has been given credit delegation allowance
*
* @return address Target contract address
* @return uint256 Call value
* @return bytes Borrow calldata
*/
function getBorrowCalldata(
ILendingPool _lendingPool,
address _asset,
uint256 _amountNotional,
uint256 _interestRateMode,
uint16 _referralCode,
address _onBehalfOf
)
public
pure
returns (address, uint256, bytes memory)
{
bytes memory callData = abi.encodeWithSignature(
"borrow(address,uint256,uint256,uint16,address)",
_asset,
_amountNotional,
_interestRateMode,
_referralCode,
_onBehalfOf
);
return (address(_lendingPool), 0, callData);
}
/**
* Invoke borrow on LendingPool from SetToken
*
* Allows SetToken to borrow a specific `_amountNotional` of the reserve underlying `_asset`, provided that
* the SetToken already deposited enough collateral, or it was given enough allowance by a credit delegator
* on the corresponding debt token (StableDebtToken or VariableDebtToken)
* @param _setToken Address of the SetToken
* @param _lendingPool Address of the LendingPool contract
* @param _asset The address of the underlying asset to borrow
* @param _amountNotional The amount to be borrowed
* @param _interestRateMode The interest rate mode at which the user wants to borrow: 1 for Stable, 2 for Variable
*/
function invokeBorrow(
ISetToken _setToken,
ILendingPool _lendingPool,
address _asset,
uint256 _amountNotional,
uint256 _interestRateMode
)
external
{
( , , bytes memory borrowCalldata) = getBorrowCalldata(
_lendingPool,
_asset,
_amountNotional,
_interestRateMode,
0,
address(_setToken)
);
_setToken.invoke(address(_lendingPool), 0, borrowCalldata);
}
/**
* Get repay calldata from SetToken
*
* Repays a borrowed `_amountNotional` on a specific `_asset` reserve, burning the equivalent debt tokens owned
* - E.g. User repays 100 USDC, burning 100 variable/stable debt tokens of the `onBehalfOf` address
* @param _lendingPool Address of the LendingPool contract
* @param _asset The address of the borrowed underlying asset previously borrowed
* @param _amountNotional The amount to repay
* Note: Passing type(uint256).max will repay the whole debt for `_asset` on the specific `_interestRateMode`
* @param _interestRateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable
* @param _onBehalfOf Address of the user who will get his debt reduced/removed. Should be the address of the
* user calling the function if he wants to reduce/remove his own debt, or the address of any other
* other borrower whose debt should be removed
*
* @return address Target contract address
* @return uint256 Call value
* @return bytes Repay calldata
*/
function getRepayCalldata(
ILendingPool _lendingPool,
address _asset,
uint256 _amountNotional,
uint256 _interestRateMode,
address _onBehalfOf
)
public
pure
returns (address, uint256, bytes memory)
{
bytes memory callData = abi.encodeWithSignature(
"repay(address,uint256,uint256,address)",
_asset,
_amountNotional,
_interestRateMode,
_onBehalfOf
);
return (address(_lendingPool), 0, callData);
}
/**
* Invoke repay on LendingPool from SetToken
*
* Repays a borrowed `_amountNotional` on a specific `_asset` reserve, burning the equivalent debt tokens owned
* - E.g. SetToken repays 100 USDC, burning 100 variable/stable debt tokens
* @param _setToken Address of the SetToken
* @param _lendingPool Address of the LendingPool contract
* @param _asset The address of the borrowed underlying asset previously borrowed
* @param _amountNotional The amount to repay
* Note: Passing type(uint256).max will repay the whole debt for `_asset` on the specific `_interestRateMode`
* @param _interestRateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable
*
* @return uint256 The final amount repaid
*/
function invokeRepay(
ISetToken _setToken,
ILendingPool _lendingPool,
address _asset,
uint256 _amountNotional,
uint256 _interestRateMode
)
external
returns (uint256)
{
( , , bytes memory repayCalldata) = getRepayCalldata(
_lendingPool,
_asset,
_amountNotional,
_interestRateMode,
address(_setToken)
);
return abi.decode(_setToken.invoke(address(_lendingPool), 0, repayCalldata), (uint256));
}
/**
* Get setUserUseReserveAsCollateral calldata from SetToken
*
* Allows borrower to enable/disable a specific deposited asset as collateral
* @param _lendingPool Address of the LendingPool contract
* @param _asset The address of the underlying asset deposited
* @param _useAsCollateral true` if the user wants to use the deposit as collateral, `false` otherwise
*
* @return address Target contract address
* @return uint256 Call value
* @return bytes SetUserUseReserveAsCollateral calldata
*/
function getSetUserUseReserveAsCollateralCalldata(
ILendingPool _lendingPool,
address _asset,
bool _useAsCollateral
)
public
pure
returns (address, uint256, bytes memory)
{
bytes memory callData = abi.encodeWithSignature(
"setUserUseReserveAsCollateral(address,bool)",
_asset,
_useAsCollateral
);
return (address(_lendingPool), 0, callData);
}
/**
* Invoke an asset to be used as collateral on Aave from SetToken
*
* Allows SetToken to enable/disable a specific deposited asset as collateral
* @param _setToken Address of the SetToken
* @param _lendingPool Address of the LendingPool contract
* @param _asset The address of the underlying asset deposited
* @param _useAsCollateral true` if the user wants to use the deposit as collateral, `false` otherwise
*/
function invokeSetUserUseReserveAsCollateral(
ISetToken _setToken,
ILendingPool _lendingPool,
address _asset,
bool _useAsCollateral
)
external
{
( , , bytes memory callData) = getSetUserUseReserveAsCollateralCalldata(
_lendingPool,
_asset,
_useAsCollateral
);
_setToken.invoke(address(_lendingPool), 0, callData);
}
/**
* Get swapBorrowRate calldata from SetToken
*
* Allows a borrower to toggle his debt between stable and variable mode
* @param _lendingPool Address of the LendingPool contract
* @param _asset The address of the underlying asset borrowed
* @param _rateMode The rate mode that the user wants to swap to
*
* @return address Target contract address
* @return uint256 Call value
* @return bytes SwapBorrowRate calldata
*/
function getSwapBorrowRateModeCalldata(
ILendingPool _lendingPool,
address _asset,
uint256 _rateMode
)
public
pure
returns (address, uint256, bytes memory)
{
bytes memory callData = abi.encodeWithSignature(
"swapBorrowRateMode(address,uint256)",
_asset,
_rateMode
);
return (address(_lendingPool), 0, callData);
}
/**
* Invoke to swap borrow rate of SetToken
*
* Allows SetToken to toggle it's debt between stable and variable mode
* @param _setToken Address of the SetToken
* @param _lendingPool Address of the LendingPool contract
* @param _asset The address of the underlying asset borrowed
* @param _rateMode The rate mode that the user wants to swap to
*/
function invokeSwapBorrowRateMode(
ISetToken _setToken,
ILendingPool _lendingPool,
address _asset,
uint256 _rateMode
)
external
{
( , , bytes memory callData) = getSwapBorrowRateModeCalldata(
_lendingPool,
_asset,
_rateMode
);
_setToken.invoke(address(_lendingPool), 0, callData);
}
}
/*
Copyright 2021 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IAToken is IERC20 {
function UNDERLYING_ASSET_ADDRESS() external view returns (address);
}
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
interface IController {
function addSet(address _setToken) external;
function feeRecipient() external view returns(address);
function getModuleFee(address _module, uint256 _feeType) external view returns(uint256);
function isModule(address _module) external view returns(bool);
function isSet(address _setToken) external view returns(bool);
function isSystemContract(address _contractAddress) external view returns (bool);
function resourceId(uint256 _id) external view returns(address);
}
/*
Copyright 2021 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
import { ISetToken } from "./ISetToken.sol";
/**
* @title IDebtIssuanceModule
* @author Set Protocol
*
* Interface for interacting with Debt Issuance module interface.
*/
interface IDebtIssuanceModule {
/**
* Called by another module to register itself on debt issuance module. Any logic can be included
* in case checks need to be made or state needs to be updated.
*/
function registerToIssuanceModule(ISetToken _setToken) external;
/**
* Called by another module to unregister itself on debt issuance module. Any logic can be included
* in case checks need to be made or state needs to be cleared.
*/
function unregisterFromIssuanceModule(ISetToken _setToken) external;
}
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
interface IExchangeAdapter {
function getSpender() external view returns(address);
function getTradeCalldata(
address _fromToken,
address _toToken,
address _toAddress,
uint256 _fromQuantity,
uint256 _minToQuantity,
bytes memory _data
)
external
view
returns (address, uint256, bytes memory);
}
/*
Copyright 2021 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import { ILendingPoolAddressesProvider } from "./ILendingPoolAddressesProvider.sol";
import { DataTypes } from "./lib/DataTypes.sol";
interface ILendingPool {
/**
* @dev Emitted on deposit()
* @param reserve The address of the underlying asset of the reserve
* @param user The address initiating the deposit
* @param onBehalfOf The beneficiary of the deposit, receiving the aTokens
* @param amount The amount deposited
* @param referral The referral code used
**/
event Deposit(
address indexed reserve,
address user,
address indexed onBehalfOf,
uint256 amount,
uint16 indexed referral
);
/**
* @dev Emitted on withdraw()
* @param reserve The address of the underlyng asset being withdrawn
* @param user The address initiating the withdrawal, owner of aTokens
* @param to Address that will receive the underlying
* @param amount The amount to be withdrawn
**/
event Withdraw(address indexed reserve, address indexed user, address indexed to, uint256 amount);
/**
* @dev Emitted on borrow() and flashLoan() when debt needs to be opened
* @param reserve The address of the underlying asset being borrowed
* @param user The address of the user initiating the borrow(), receiving the funds on borrow() or just
* initiator of the transaction on flashLoan()
* @param onBehalfOf The address that will be getting the debt
* @param amount The amount borrowed out
* @param borrowRateMode The rate mode: 1 for Stable, 2 for Variable
* @param borrowRate The numeric rate at which the user has borrowed
* @param referral The referral code used
**/
event Borrow(
address indexed reserve,
address user,
address indexed onBehalfOf,
uint256 amount,
uint256 borrowRateMode,
uint256 borrowRate,
uint16 indexed referral
);
/**
* @dev Emitted on repay()
* @param reserve The address of the underlying asset of the reserve
* @param user The beneficiary of the repayment, getting his debt reduced
* @param repayer The address of the user initiating the repay(), providing the funds
* @param amount The amount repaid
**/
event Repay(
address indexed reserve,
address indexed user,
address indexed repayer,
uint256 amount
);
/**
* @dev Emitted on swapBorrowRateMode()
* @param reserve The address of the underlying asset of the reserve
* @param user The address of the user swapping his rate mode
* @param rateMode The rate mode that the user wants to swap to
**/
event Swap(address indexed reserve, address indexed user, uint256 rateMode);
/**
* @dev Emitted on setUserUseReserveAsCollateral()
* @param reserve The address of the underlying asset of the reserve
* @param user The address of the user enabling the usage as collateral
**/
event ReserveUsedAsCollateralEnabled(address indexed reserve, address indexed user);
/**
* @dev Emitted on setUserUseReserveAsCollateral()
* @param reserve The address of the underlying asset of the reserve
* @param user The address of the user enabling the usage as collateral
**/
event ReserveUsedAsCollateralDisabled(address indexed reserve, address indexed user);
/**
* @dev Emitted on rebalanceStableBorrowRate()
* @param reserve The address of the underlying asset of the reserve
* @param user The address of the user for which the rebalance has been executed
**/
event RebalanceStableBorrowRate(address indexed reserve, address indexed user);
/**
* @dev Emitted on flashLoan()
* @param target The address of the flash loan receiver contract
* @param initiator The address initiating the flash loan
* @param asset The address of the asset being flash borrowed
* @param amount The amount flash borrowed
* @param premium The fee flash borrowed
* @param referralCode The referral code used
**/
event FlashLoan(
address indexed target,
address indexed initiator,
address indexed asset,
uint256 amount,
uint256 premium,
uint16 referralCode
);
/**
* @dev Emitted when the pause is triggered.
*/
event Paused();
/**
* @dev Emitted when the pause is lifted.
*/
event Unpaused();
/**
* @dev Emitted when a borrower is liquidated. This event is emitted by the LendingPool via
* LendingPoolCollateral manager using a DELEGATECALL
* This allows to have the events in the generated ABI for LendingPool.
* @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation
* @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation
* @param user The address of the borrower getting liquidated
* @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover
* @param liquidatedCollateralAmount The amount of collateral received by the liiquidator
* @param liquidator The address of the liquidator
* @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants
* to receive the underlying collateral asset directly
**/
event LiquidationCall(
address indexed collateralAsset,
address indexed debtAsset,
address indexed user,
uint256 debtToCover,
uint256 liquidatedCollateralAmount,
address liquidator,
bool receiveAToken
);
/**
* @dev Emitted when the state of a reserve is updated. NOTE: This event is actually declared
* in the ReserveLogic library and emitted in the updateInterestRates() function. Since the function is internal,
* the event will actually be fired by the LendingPool contract. The event is therefore replicated here so it
* gets added to the LendingPool ABI
* @param reserve The address of the underlying asset of the reserve
* @param liquidityRate The new liquidity rate
* @param stableBorrowRate The new stable borrow rate
* @param variableBorrowRate The new variable borrow rate
* @param liquidityIndex The new liquidity index
* @param variableBorrowIndex The new variable borrow index
**/
event ReserveDataUpdated(
address indexed reserve,
uint256 liquidityRate,
uint256 stableBorrowRate,
uint256 variableBorrowRate,
uint256 liquidityIndex,
uint256 variableBorrowIndex
);
/**
* @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying aTokens.
* - E.g. User deposits 100 USDC and gets in return 100 aUSDC
* @param asset The address of the underlying asset to deposit
* @param amount The amount to be deposited
* @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user
* wants to receive them on his own wallet, or a different address if the beneficiary of aTokens
* is a different wallet
* @param referralCode Code used to register the integrator originating the operation, for potential rewards.
* 0 if the action is executed directly by the user, without any middle-man
**/
function deposit(
address asset,
uint256 amount,
address onBehalfOf,
uint16 referralCode
) external;
/**
* @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned
* E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC
* @param asset The address of the underlying asset to withdraw
* @param amount The underlying amount to be withdrawn
* - Send the value type(uint256).max in order to withdraw the whole aToken balance
* @param to Address that will receive the underlying, same as msg.sender if the user
* wants to receive it on his own wallet, or a different address if the beneficiary is a
* different wallet
* @return The final amount withdrawn
**/
function withdraw(
address asset,
uint256 amount,
address to
) external returns (uint256);
/**
* @dev Allows users to borrow a specific `amount` of the reserve underlying asset, provided that the borrower
* already deposited enough collateral, or he was given enough allowance by a credit delegator on the
* corresponding debt token (StableDebtToken or VariableDebtToken)
* - E.g. User borrows 100 USDC passing as `onBehalfOf` his own address, receiving the 100 USDC in his wallet
* and 100 stable/variable debt tokens, depending on the `interestRateMode`
* @param asset The address of the underlying asset to borrow
* @param amount The amount to be borrowed
* @param interestRateMode The interest rate mode at which the user wants to borrow: 1 for Stable, 2 for Variable
* @param referralCode Code used to register the integrator originating the operation, for potential rewards.
* 0 if the action is executed directly by the user, without any middle-man
* @param onBehalfOf Address of the user who will receive the debt. Should be the address of the borrower itself
* calling the function if he wants to borrow against his own collateral, or the address of the credit delegator
* if he has been given credit delegation allowance
**/
function borrow(
address asset,
uint256 amount,
uint256 interestRateMode,
uint16 referralCode,
address onBehalfOf
) external;
/**
* @notice Repays a borrowed `amount` on a specific reserve, burning the equivalent debt tokens owned
* - E.g. User repays 100 USDC, burning 100 variable/stable debt tokens of the `onBehalfOf` address
* @param asset The address of the borrowed underlying asset previously borrowed
* @param amount The amount to repay
* - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode`
* @param rateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable
* @param onBehalfOf Address of the user who will get his debt reduced/removed. Should be the address of the
* user calling the function if he wants to reduce/remove his own debt, or the address of any other
* other borrower whose debt should be removed
* @return The final amount repaid
**/
function repay(
address asset,
uint256 amount,
uint256 rateMode,
address onBehalfOf
) external returns (uint256);
/**
* @dev Allows a borrower to swap his debt between stable and variable mode, or viceversa
* @param asset The address of the underlying asset borrowed
* @param rateMode The rate mode that the user wants to swap to
**/
function swapBorrowRateMode(address asset, uint256 rateMode) external;
/**
* @dev Rebalances the stable interest rate of a user to the current stable rate defined on the reserve.
* - Users can be rebalanced if the following conditions are satisfied:
* 1. Usage ratio is above 95%
* 2. the current deposit APY is below REBALANCE_UP_THRESHOLD * maxVariableBorrowRate, which means that too much has been
* borrowed at a stable rate and depositors are not earning enough
* @param asset The address of the underlying asset borrowed
* @param user The address of the user to be rebalanced
**/
function rebalanceStableBorrowRate(address asset, address user) external;
/**
* @dev Allows depositors to enable/disable a specific deposited asset as collateral
* @param asset The address of the underlying asset deposited
* @param useAsCollateral `true` if the user wants to use the deposit as collateral, `false` otherwise
**/
function setUserUseReserveAsCollateral(address asset, bool useAsCollateral) external;
/**
* @dev Function to liquidate a non-healthy position collateral-wise, with Health Factor below 1
* - The caller (liquidator) covers `debtToCover` amount of debt of the user getting liquidated, and receives
* a proportionally amount of the `collateralAsset` plus a bonus to cover market risk
* @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation
* @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation
* @param user The address of the borrower getting liquidated
* @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover
* @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants
* to receive the underlying collateral asset directly
**/
function liquidationCall(
address collateralAsset,
address debtAsset,
address user,
uint256 debtToCover,
bool receiveAToken
) external;
/**
* @dev Allows smartcontracts to access the liquidity of the pool within one transaction,
* as long as the amount taken plus a fee is returned.
* IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept into consideration.
* For further details please visit https://developers.aave.com
* @param receiverAddress The address of the contract receiving the funds, implementing the IFlashLoanReceiver interface
* @param assets The addresses of the assets being flash-borrowed
* @param amounts The amounts amounts being flash-borrowed
* @param modes Types of the debt to open if the flash loan is not returned:
* 0 -> Don't open any debt, just revert if funds can't be transferred from the receiver
* 1 -> Open debt at stable rate for the value of the amount flash-borrowed to the `onBehalfOf` address
* 2 -> Open debt at variable rate for the value of the amount flash-borrowed to the `onBehalfOf` address
* @param onBehalfOf The address that will receive the debt in the case of using on `modes` 1 or 2
* @param params Variadic packed params to pass to the receiver as extra information
* @param referralCode Code used to register the integrator originating the operation, for potential rewards.
* 0 if the action is executed directly by the user, without any middle-man
**/
function flashLoan(
address receiverAddress,
address[] calldata assets,
uint256[] calldata amounts,
uint256[] calldata modes,
address onBehalfOf,
bytes calldata params,
uint16 referralCode
) external;
/**
* @dev Returns the user account data across all the reserves
* @param user The address of the user
* @return totalCollateralETH the total collateral in ETH of the user
* @return totalDebtETH the total debt in ETH of the user
* @return availableBorrowsETH the borrowing power left of the user
* @return currentLiquidationThreshold the liquidation threshold of the user
* @return ltv the loan to value of the user
* @return healthFactor the current health factor of the user
**/
function getUserAccountData(address user)
external
view
returns (
uint256 totalCollateralETH,
uint256 totalDebtETH,
uint256 availableBorrowsETH,
uint256 currentLiquidationThreshold,
uint256 ltv,
uint256 healthFactor
);
function initReserve(
address reserve,
address aTokenAddress,
address stableDebtAddress,
address variableDebtAddress,
address interestRateStrategyAddress
) external;
function setReserveInterestRateStrategyAddress(address reserve, address rateStrategyAddress)
external;
function setConfiguration(address reserve, uint256 configuration) external;
/**
* @dev Returns the configuration of the reserve
* @param asset The address of the underlying asset of the reserve
* @return The configuration of the reserve
**/
function getConfiguration(address asset)
external
view
returns (DataTypes.ReserveConfigurationMap memory);
/**
* @dev Returns the configuration of the user across all the reserves
* @param user The user address
* @return The configuration of the user
**/
function getUserConfiguration(address user)
external
view
returns (DataTypes.UserConfigurationMap memory);
/**
* @dev Returns the normalized income normalized income of the reserve
* @param asset The address of the underlying asset of the reserve
* @return The reserve's normalized income
*/
function getReserveNormalizedIncome(address asset) external view returns (uint256);
/**
* @dev Returns the normalized variable debt per unit of asset
* @param asset The address of the underlying asset of the reserve
* @return The reserve normalized variable debt
*/
function getReserveNormalizedVariableDebt(address asset) external view returns (uint256);
/**
* @dev Returns the state and configuration of the reserve
* @param asset The address of the underlying asset of the reserve
* @return The state of the reserve
**/
function getReserveData(address asset) external view returns (DataTypes.ReserveData memory);
function finalizeTransfer(
address asset,
address from,
address to,
uint256 amount,
uint256 balanceFromAfter,
uint256 balanceToBefore
) external;
function getReservesList() external view returns (address[] memory);
function getAddressesProvider() external view returns (ILendingPoolAddressesProvider);
function setPause(bool val) external;
function paused() external view returns (bool);
}
/*
Copyright 2021 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
/**
* @title LendingPoolAddressesProvider contract
* @dev Main registry of addresses part of or connected to the protocol, including permissioned roles
* - Acting also as factory of proxies and admin of those, so with right to change its implementations
* - Owned by the Aave Governance
* @author Aave
**/
interface ILendingPoolAddressesProvider {
event MarketIdSet(string newMarketId);
event LendingPoolUpdated(address indexed newAddress);
event ConfigurationAdminUpdated(address indexed newAddress);
event EmergencyAdminUpdated(address indexed newAddress);
event LendingPoolConfiguratorUpdated(address indexed newAddress);
event LendingPoolCollateralManagerUpdated(address indexed newAddress);
event PriceOracleUpdated(address indexed newAddress);
event LendingRateOracleUpdated(address indexed newAddress);
event ProxyCreated(bytes32 id, address indexed newAddress);
event AddressSet(bytes32 id, address indexed newAddress, bool hasProxy);
function getMarketId() external view returns (string memory);
function setMarketId(string calldata marketId) external;
function setAddress(bytes32 id, address newAddress) external;
function setAddressAsProxy(bytes32 id, address impl) external;
function getAddress(bytes32 id) external view returns (address);
function getLendingPool() external view returns (address);
function setLendingPoolImpl(address pool) external;
function getLendingPoolConfigurator() external view returns (address);
function setLendingPoolConfiguratorImpl(address configurator) external;
function getLendingPoolCollateralManager() external view returns (address);
function setLendingPoolCollateralManager(address manager) external;
function getPoolAdmin() external view returns (address);
function setPoolAdmin(address admin) external;
function getEmergencyAdmin() external view returns (address);
function setEmergencyAdmin(address admin) external;
function getPriceOracle() external view returns (address);
function setPriceOracle(address priceOracle) external;
function getLendingRateOracle() external view returns (address);
function setLendingRateOracle(address lendingRateOracle) external;
}
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { ISetToken } from "./ISetToken.sol";
/**
* CHANGELOG:
* - Added a module level issue hook that can be used to set state ahead of component level
* issue hooks
*/
interface IModuleIssuanceHook {
function moduleIssueHook(ISetToken _setToken, uint256 _setTokenQuantity) external;
function moduleRedeemHook(ISetToken _setToken, uint256 _setTokenQuantity) external;
function componentIssueHook(
ISetToken _setToken,
uint256 _setTokenQuantity,
IERC20 _component,
bool _isEquity
) external;
function componentRedeemHook(
ISetToken _setToken,
uint256 _setTokenQuantity,
IERC20 _component,
bool _isEquity
) external;
}
/*
Copyright 2021 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import { ILendingPoolAddressesProvider } from "./ILendingPoolAddressesProvider.sol";
interface IProtocolDataProvider {
struct TokenData {
string symbol;
address tokenAddress;
}
function ADDRESSES_PROVIDER() external view returns (ILendingPoolAddressesProvider);
function getAllReservesTokens() external view returns (TokenData[] memory);
function getAllATokens() external view returns (TokenData[] memory);
function getReserveConfigurationData(address asset) external view returns (uint256 decimals, uint256 ltv, uint256 liquidationThreshold, uint256 liquidationBonus, uint256 reserveFactor, bool usageAsCollateralEnabled, bool borrowingEnabled, bool stableBorrowRateEnabled, bool isActive, bool isFrozen);
function getReserveData(address asset) external view returns (uint256 availableLiquidity, uint256 totalStableDebt, uint256 totalVariableDebt, uint256 liquidityRate, uint256 variableBorrowRate, uint256 stableBorrowRate, uint256 averageStableBorrowRate, uint256 liquidityIndex, uint256 variableBorrowIndex, uint40 lastUpdateTimestamp);
function getUserReserveData(address asset, address user) external view returns (uint256 currentATokenBalance, uint256 currentStableDebt, uint256 currentVariableDebt, uint256 principalStableDebt, uint256 scaledVariableDebt, uint256 stableBorrowRate, uint256 liquidityRate, uint40 stableRateLastUpdated, bool usageAsCollateralEnabled);
function getReserveTokensAddresses(address asset) external view returns (address aTokenAddress, address stableDebtTokenAddress, address variableDebtTokenAddress);
}
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
pragma experimental "ABIEncoderV2";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title ISetToken
* @author Set Protocol
*
* Interface for operating with SetTokens.
*/
interface ISetToken is IERC20 {
/* ============ Enums ============ */
enum ModuleState {
NONE,
PENDING,
INITIALIZED
}
/* ============ Structs ============ */
/**
* The base definition of a SetToken Position
*
* @param component Address of token in the Position
* @param module If not in default state, the address of associated module
* @param unit Each unit is the # of components per 10^18 of a SetToken
* @param positionState Position ENUM. Default is 0; External is 1
* @param data Arbitrary data
*/
struct Position {
address component;
address module;
int256 unit;
uint8 positionState;
bytes data;
}
/**
* A struct that stores a component's cash position details and external positions
* This data structure allows O(1) access to a component's cash position units and
* virtual units.
*
* @param virtualUnit Virtual value of a component's DEFAULT position. Stored as virtual for efficiency
* updating all units at once via the position multiplier. Virtual units are achieved
* by dividing a "real" value by the "positionMultiplier"
* @param componentIndex
* @param externalPositionModules List of external modules attached to each external position. Each module
* maps to an external position
* @param externalPositions Mapping of module => ExternalPosition struct for a given component
*/
struct ComponentPosition {
int256 virtualUnit;
address[] externalPositionModules;
mapping(address => ExternalPosition) externalPositions;
}
/**
* A struct that stores a component's external position details including virtual unit and any
* auxiliary data.
*
* @param virtualUnit Virtual value of a component's EXTERNAL position.
* @param data Arbitrary data
*/
struct ExternalPosition {
int256 virtualUnit;
bytes data;
}
/* ============ Functions ============ */
function addComponent(address _component) external;
function removeComponent(address _component) external;
function editDefaultPositionUnit(address _component, int256 _realUnit) external;
function addExternalPositionModule(address _component, address _positionModule) external;
function removeExternalPositionModule(address _component, address _positionModule) external;
function editExternalPositionUnit(address _component, address _positionModule, int256 _realUnit) external;
function editExternalPositionData(address _component, address _positionModule, bytes calldata _data) external;
function invoke(address _target, uint256 _value, bytes calldata _data) external returns(bytes memory);
function editPositionMultiplier(int256 _newMultiplier) external;
function mint(address _account, uint256 _quantity) external;
function burn(address _account, uint256 _quantity) external;
function lock() external;
function unlock() external;
function addModule(address _module) external;
function removeModule(address _module) external;
function initializeModule() external;
function setManager(address _manager) external;
function manager() external view returns (address);
function moduleStates(address _module) external view returns (ModuleState);
function getModules() external view returns (address[] memory);
function getDefaultPositionRealUnit(address _component) external view returns(int256);
function getExternalPositionRealUnit(address _component, address _positionModule) external view returns(int256);
function getComponents() external view returns(address[] memory);
function getExternalPositionModules(address _component) external view returns(address[] memory);
function getExternalPositionData(address _component, address _positionModule) external view returns(bytes memory);
function isExternalPositionModule(address _component, address _module) external view returns(bool);
function isComponent(address _component) external view returns(bool);
function positionMultiplier() external view returns (int256);
function getPositions() external view returns (Position[] memory);
function getTotalComponentRealUnits(address _component) external view returns(int256);
function isInitializedModule(address _module) external view returns(bool);
function isPendingModule(address _module) external view returns(bool);
function isLocked() external view returns (bool);
}
/*
Copyright 2021 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title IVariableDebtToken
* @author Aave
* @notice Defines the basic interface for a variable debt token.
**/
interface IVariableDebtToken is IERC20 {}
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { AddressArrayUtils } from "../../lib/AddressArrayUtils.sol";
import { ExplicitERC20 } from "../../lib/ExplicitERC20.sol";
import { IController } from "../../interfaces/IController.sol";
import { IModule } from "../../interfaces/IModule.sol";
import { ISetToken } from "../../interfaces/ISetToken.sol";
import { Invoke } from "./Invoke.sol";
import { Position } from "./Position.sol";
import { PreciseUnitMath } from "../../lib/PreciseUnitMath.sol";
import { ResourceIdentifier } from "./ResourceIdentifier.sol";
import { SafeCast } from "@openzeppelin/contracts/utils/SafeCast.sol";
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { SignedSafeMath } from "@openzeppelin/contracts/math/SignedSafeMath.sol";
/**
* @title ModuleBase
* @author Set Protocol
*
* Abstract class that houses common Module-related state and functions.
*
* CHANGELOG:
* - 4/21/21: Delegated modifier logic to internal helpers to reduce contract size
*
*/
abstract contract ModuleBase is IModule {
using AddressArrayUtils for address[];
using Invoke for ISetToken;
using Position for ISetToken;
using PreciseUnitMath for uint256;
using ResourceIdentifier for IController;
using SafeCast for int256;
using SafeCast for uint256;
using SafeMath for uint256;
using SignedSafeMath for int256;
/* ============ State Variables ============ */
// Address of the controller
IController public controller;
/* ============ Modifiers ============ */
modifier onlyManagerAndValidSet(ISetToken _setToken) {
_validateOnlyManagerAndValidSet(_setToken);
_;
}
modifier onlySetManager(ISetToken _setToken, address _caller) {
_validateOnlySetManager(_setToken, _caller);
_;
}
modifier onlyValidAndInitializedSet(ISetToken _setToken) {
_validateOnlyValidAndInitializedSet(_setToken);
_;
}
/**
* Throws if the sender is not a SetToken's module or module not enabled
*/
modifier onlyModule(ISetToken _setToken) {
_validateOnlyModule(_setToken);
_;
}
/**
* Utilized during module initializations to check that the module is in pending state
* and that the SetToken is valid
*/
modifier onlyValidAndPendingSet(ISetToken _setToken) {
_validateOnlyValidAndPendingSet(_setToken);
_;
}
/* ============ Constructor ============ */
/**
* Set state variables and map asset pairs to their oracles
*
* @param _controller Address of controller contract
*/
constructor(IController _controller) public {
controller = _controller;
}
/* ============ Internal Functions ============ */
/**
* Transfers tokens from an address (that has set allowance on the module).
*
* @param _token The address of the ERC20 token
* @param _from The address to transfer from
* @param _to The address to transfer to
* @param _quantity The number of tokens to transfer
*/
function transferFrom(IERC20 _token, address _from, address _to, uint256 _quantity) internal {
ExplicitERC20.transferFrom(_token, _from, _to, _quantity);
}
/**
* Gets the integration for the module with the passed in name. Validates that the address is not empty
*/
function getAndValidateAdapter(string memory _integrationName) internal view returns(address) {
bytes32 integrationHash = getNameHash(_integrationName);
return getAndValidateAdapterWithHash(integrationHash);
}
/**
* Gets the integration for the module with the passed in hash. Validates that the address is not empty
*/
function getAndValidateAdapterWithHash(bytes32 _integrationHash) internal view returns(address) {
address adapter = controller.getIntegrationRegistry().getIntegrationAdapterWithHash(
address(this),
_integrationHash
);
require(adapter != address(0), "Must be valid adapter");
return adapter;
}
/**
* Gets the total fee for this module of the passed in index (fee % * quantity)
*/
function getModuleFee(uint256 _feeIndex, uint256 _quantity) internal view returns(uint256) {
uint256 feePercentage = controller.getModuleFee(address(this), _feeIndex);
return _quantity.preciseMul(feePercentage);
}
/**
* Pays the _feeQuantity from the _setToken denominated in _token to the protocol fee recipient
*/
function payProtocolFeeFromSetToken(ISetToken _setToken, address _token, uint256 _feeQuantity) internal {
if (_feeQuantity > 0) {
_setToken.strictInvokeTransfer(_token, controller.feeRecipient(), _feeQuantity);
}
}
/**
* Returns true if the module is in process of initialization on the SetToken
*/
function isSetPendingInitialization(ISetToken _setToken) internal view returns(bool) {
return _setToken.isPendingModule(address(this));
}
/**
* Returns true if the address is the SetToken's manager
*/
function isSetManager(ISetToken _setToken, address _toCheck) internal view returns(bool) {
return _setToken.manager() == _toCheck;
}
/**
* Returns true if SetToken must be enabled on the controller
* and module is registered on the SetToken
*/
function isSetValidAndInitialized(ISetToken _setToken) internal view returns(bool) {
return controller.isSet(address(_setToken)) &&
_setToken.isInitializedModule(address(this));
}
/**
* Hashes the string and returns a bytes32 value
*/
function getNameHash(string memory _name) internal pure returns(bytes32) {
return keccak256(bytes(_name));
}
/* ============== Modifier Helpers ===============
* Internal functions used to reduce bytecode size
*/
/**
* Caller must SetToken manager and SetToken must be valid and initialized
*/
function _validateOnlyManagerAndValidSet(ISetToken _setToken) internal view {
require(isSetManager(_setToken, msg.sender), "Must be the SetToken manager");
require(isSetValidAndInitialized(_setToken), "Must be a valid and initialized SetToken");
}
/**
* Caller must SetToken manager
*/
function _validateOnlySetManager(ISetToken _setToken, address _caller) internal view {
require(isSetManager(_setToken, _caller), "Must be the SetToken manager");
}
/**
* SetToken must be valid and initialized
*/
function _validateOnlyValidAndInitializedSet(ISetToken _setToken) internal view {
require(isSetValidAndInitialized(_setToken), "Must be a valid and initialized SetToken");
}
/**
* Caller must be initialized module and module must be enabled on the controller
*/
function _validateOnlyModule(ISetToken _setToken) internal view {
require(
_setToken.moduleStates(msg.sender) == ISetToken.ModuleState.INITIALIZED,
"Only the module can call"
);
require(
controller.isModule(msg.sender),
"Module must be enabled on controller"
);
}
/**
* SetToken must be in a pending state and module must be in pending state
*/
function _validateOnlyValidAndPendingSet(ISetToken _setToken) internal view {
require(controller.isSet(address(_setToken)), "Must be controller-enabled SetToken");
require(isSetPendingInitialization(_setToken), "Must be pending initialization");
}
}
// 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;
}
}
/*
Copyright 2021 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
library DataTypes {
// refer to the whitepaper, section 1.1 basic concepts for a formal description of these properties.
struct ReserveData {
//stores the reserve configuration
ReserveConfigurationMap configuration;
//the liquidity index. Expressed in ray
uint128 liquidityIndex;
//variable borrow index. Expressed in ray
uint128 variableBorrowIndex;
//the current supply rate. Expressed in ray
uint128 currentLiquidityRate;
//the current variable borrow rate. Expressed in ray
uint128 currentVariableBorrowRate;
//the current stable borrow rate. Expressed in ray
uint128 currentStableBorrowRate;
uint40 lastUpdateTimestamp;
//tokens addresses
address aTokenAddress;
address stableDebtTokenAddress;
address variableDebtTokenAddress;
//address of the interest rate strategy
address interestRateStrategyAddress;
//the id of the reserve. Represents the position in the list of the active reserves
uint8 id;
}
struct ReserveConfigurationMap {
//bit 0-15: LTV
//bit 16-31: Liq. threshold
//bit 32-47: Liq. bonus
//bit 48-55: Decimals
//bit 56: Reserve is active
//bit 57: reserve is frozen
//bit 58: borrowing is enabled
//bit 59: stable rate borrowing enabled
//bit 60-63: reserved
//bit 64-79: reserve factor
uint256 data;
}
struct UserConfigurationMap {
uint256 data;
}
enum InterestRateMode {NONE, STABLE, VARIABLE}
}
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
/**
* @title AddressArrayUtils
* @author Set Protocol
*
* Utility functions to handle Address Arrays
*
* CHANGELOG:
* - 4/21/21: Added validatePairsWithArray methods
*/
library AddressArrayUtils {
/**
* Finds the index of the first occurrence of the given element.
* @param A The input array to search
* @param a The value to find
* @return Returns (index and isIn) for the first occurrence starting from index 0
*/
function indexOf(address[] memory A, address a) internal pure returns (uint256, bool) {
uint256 length = A.length;
for (uint256 i = 0; i < length; i++) {
if (A[i] == a) {
return (i, true);
}
}
return (uint256(-1), false);
}
/**
* Returns true if the value is present in the list. Uses indexOf internally.
* @param A The input array to search
* @param a The value to find
* @return Returns isIn for the first occurrence starting from index 0
*/
function contains(address[] memory A, address a) internal pure returns (bool) {
(, bool isIn) = indexOf(A, a);
return isIn;
}
/**
* Returns true if there are 2 elements that are the same in an array
* @param A The input array to search
* @return Returns boolean for the first occurrence of a duplicate
*/
function hasDuplicate(address[] memory A) internal pure returns(bool) {
require(A.length > 0, "A is empty");
for (uint256 i = 0; i < A.length - 1; i++) {
address current = A[i];
for (uint256 j = i + 1; j < A.length; j++) {
if (current == A[j]) {
return true;
}
}
}
return false;
}
/**
* @param A The input array to search
* @param a The address to remove
* @return Returns the array with the object removed.
*/
function remove(address[] memory A, address a)
internal
pure
returns (address[] memory)
{
(uint256 index, bool isIn) = indexOf(A, a);
if (!isIn) {
revert("Address not in array.");
} else {
(address[] memory _A,) = pop(A, index);
return _A;
}
}
/**
* @param A The input array to search
* @param a The address to remove
*/
function removeStorage(address[] storage A, address a)
internal
{
(uint256 index, bool isIn) = indexOf(A, a);
if (!isIn) {
revert("Address not in array.");
} else {
uint256 lastIndex = A.length - 1; // If the array would be empty, the previous line would throw, so no underflow here
if (index != lastIndex) { A[index] = A[lastIndex]; }
A.pop();
}
}
/**
* Removes specified index from array
* @param A The input array to search
* @param index The index to remove
* @return Returns the new array and the removed entry
*/
function pop(address[] memory A, uint256 index)
internal
pure
returns (address[] memory, address)
{
uint256 length = A.length;
require(index < A.length, "Index must be < A length");
address[] memory newAddresses = new address[](length - 1);
for (uint256 i = 0; i < index; i++) {
newAddresses[i] = A[i];
}
for (uint256 j = index + 1; j < length; j++) {
newAddresses[j - 1] = A[j];
}
return (newAddresses, A[index]);
}
/**
* Returns the combination of the two arrays
* @param A The first array
* @param B The second array
* @return Returns A extended by B
*/
function extend(address[] memory A, address[] memory B) internal pure returns (address[] memory) {
uint256 aLength = A.length;
uint256 bLength = B.length;
address[] memory newAddresses = new address[](aLength + bLength);
for (uint256 i = 0; i < aLength; i++) {
newAddresses[i] = A[i];
}
for (uint256 j = 0; j < bLength; j++) {
newAddresses[aLength + j] = B[j];
}
return newAddresses;
}
/**
* Validate that address and uint array lengths match. Validate address array is not empty
* and contains no duplicate elements.
*
* @param A Array of addresses
* @param B Array of uint
*/
function validatePairsWithArray(address[] memory A, uint[] memory B) internal pure {
require(A.length == B.length, "Array length mismatch");
_validateLengthAndUniqueness(A);
}
/**
* Validate that address and bool array lengths match. Validate address array is not empty
* and contains no duplicate elements.
*
* @param A Array of addresses
* @param B Array of bool
*/
function validatePairsWithArray(address[] memory A, bool[] memory B) internal pure {
require(A.length == B.length, "Array length mismatch");
_validateLengthAndUniqueness(A);
}
/**
* Validate that address and string array lengths match. Validate address array is not empty
* and contains no duplicate elements.
*
* @param A Array of addresses
* @param B Array of strings
*/
function validatePairsWithArray(address[] memory A, string[] memory B) internal pure {
require(A.length == B.length, "Array length mismatch");
_validateLengthAndUniqueness(A);
}
/**
* Validate that address array lengths match, and calling address array are not empty
* and contain no duplicate elements.
*
* @param A Array of addresses
* @param B Array of addresses
*/
function validatePairsWithArray(address[] memory A, address[] memory B) internal pure {
require(A.length == B.length, "Array length mismatch");
_validateLengthAndUniqueness(A);
}
/**
* Validate that address and bytes array lengths match. Validate address array is not empty
* and contains no duplicate elements.
*
* @param A Array of addresses
* @param B Array of bytes
*/
function validatePairsWithArray(address[] memory A, bytes[] memory B) internal pure {
require(A.length == B.length, "Array length mismatch");
_validateLengthAndUniqueness(A);
}
/**
* Validate address array is not empty and contains no duplicate elements.
*
* @param A Array of addresses
*/
function _validateLengthAndUniqueness(address[] memory A) internal pure {
require(A.length > 0, "Array length must be > 0");
require(!hasDuplicate(A), "Cannot duplicate addresses");
}
}
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
/**
* @title ExplicitERC20
* @author Set Protocol
*
* Utility functions for ERC20 transfers that require the explicit amount to be transferred.
*/
library ExplicitERC20 {
using SafeMath for uint256;
/**
* When given allowance, transfers a token from the "_from" to the "_to" of quantity "_quantity".
* Ensures that the recipient has received the correct quantity (ie no fees taken on transfer)
*
* @param _token ERC20 token to approve
* @param _from The account to transfer tokens from
* @param _to The account to transfer tokens to
* @param _quantity The quantity to transfer
*/
function transferFrom(
IERC20 _token,
address _from,
address _to,
uint256 _quantity
)
internal
{
// Call specified ERC20 contract to transfer tokens (via proxy).
if (_quantity > 0) {
uint256 existingBalance = _token.balanceOf(_to);
SafeERC20.safeTransferFrom(
_token,
_from,
_to,
_quantity
);
uint256 newBalance = _token.balanceOf(_to);
// Verify transfer quantity is reflected in balance
require(
newBalance == existingBalance.add(_quantity),
"Invalid post transfer balance"
);
}
}
}
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
/**
* @title IModule
* @author Set Protocol
*
* Interface for interacting with Modules.
*/
interface IModule {
/**
* Called by a SetToken to notify that this module was removed from the Set token. Any logic can be included
* in case checks need to be made or state needs to be cleared.
*/
function removeModule() external;
}
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { ISetToken } from "../../interfaces/ISetToken.sol";
/**
* @title Invoke
* @author Set Protocol
*
* A collection of common utility functions for interacting with the SetToken's invoke function
*/
library Invoke {
using SafeMath for uint256;
/* ============ Internal ============ */
/**
* Instructs the SetToken to set approvals of the ERC20 token to a spender.
*
* @param _setToken SetToken instance to invoke
* @param _token ERC20 token to approve
* @param _spender The account allowed to spend the SetToken's balance
* @param _quantity The quantity of allowance to allow
*/
function invokeApprove(
ISetToken _setToken,
address _token,
address _spender,
uint256 _quantity
)
internal
{
bytes memory callData = abi.encodeWithSignature("approve(address,uint256)", _spender, _quantity);
_setToken.invoke(_token, 0, callData);
}
/**
* Instructs the SetToken to transfer the ERC20 token to a recipient.
*
* @param _setToken SetToken instance to invoke
* @param _token ERC20 token to transfer
* @param _to The recipient account
* @param _quantity The quantity to transfer
*/
function invokeTransfer(
ISetToken _setToken,
address _token,
address _to,
uint256 _quantity
)
internal
{
if (_quantity > 0) {
bytes memory callData = abi.encodeWithSignature("transfer(address,uint256)", _to, _quantity);
_setToken.invoke(_token, 0, callData);
}
}
/**
* Instructs the SetToken to transfer the ERC20 token to a recipient.
* The new SetToken balance must equal the existing balance less the quantity transferred
*
* @param _setToken SetToken instance to invoke
* @param _token ERC20 token to transfer
* @param _to The recipient account
* @param _quantity The quantity to transfer
*/
function strictInvokeTransfer(
ISetToken _setToken,
address _token,
address _to,
uint256 _quantity
)
internal
{
if (_quantity > 0) {
// Retrieve current balance of token for the SetToken
uint256 existingBalance = IERC20(_token).balanceOf(address(_setToken));
Invoke.invokeTransfer(_setToken, _token, _to, _quantity);
// Get new balance of transferred token for SetToken
uint256 newBalance = IERC20(_token).balanceOf(address(_setToken));
// Verify only the transfer quantity is subtracted
require(
newBalance == existingBalance.sub(_quantity),
"Invalid post transfer balance"
);
}
}
/**
* Instructs the SetToken to unwrap the passed quantity of WETH
*
* @param _setToken SetToken instance to invoke
* @param _weth WETH address
* @param _quantity The quantity to unwrap
*/
function invokeUnwrapWETH(ISetToken _setToken, address _weth, uint256 _quantity) internal {
bytes memory callData = abi.encodeWithSignature("withdraw(uint256)", _quantity);
_setToken.invoke(_weth, 0, callData);
}
/**
* Instructs the SetToken to wrap the passed quantity of ETH
*
* @param _setToken SetToken instance to invoke
* @param _weth WETH address
* @param _quantity The quantity to unwrap
*/
function invokeWrapWETH(ISetToken _setToken, address _weth, uint256 _quantity) internal {
bytes memory callData = abi.encodeWithSignature("deposit()");
_setToken.invoke(_weth, _quantity, callData);
}
}
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
pragma experimental "ABIEncoderV2";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeCast } from "@openzeppelin/contracts/utils/SafeCast.sol";
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { SignedSafeMath } from "@openzeppelin/contracts/math/SignedSafeMath.sol";
import { ISetToken } from "../../interfaces/ISetToken.sol";
import { PreciseUnitMath } from "../../lib/PreciseUnitMath.sol";
/**
* @title Position
* @author Set Protocol
*
* Collection of helper functions for handling and updating SetToken Positions
*
* CHANGELOG:
* - Updated editExternalPosition to work when no external position is associated with module
*/
library Position {
using SafeCast for uint256;
using SafeMath for uint256;
using SafeCast for int256;
using SignedSafeMath for int256;
using PreciseUnitMath for uint256;
/* ============ Helper ============ */
/**
* Returns whether the SetToken has a default position for a given component (if the real unit is > 0)
*/
function hasDefaultPosition(ISetToken _setToken, address _component) internal view returns(bool) {
return _setToken.getDefaultPositionRealUnit(_component) > 0;
}
/**
* Returns whether the SetToken has an external position for a given component (if # of position modules is > 0)
*/
function hasExternalPosition(ISetToken _setToken, address _component) internal view returns(bool) {
return _setToken.getExternalPositionModules(_component).length > 0;
}
/**
* Returns whether the SetToken component default position real unit is greater than or equal to units passed in.
*/
function hasSufficientDefaultUnits(ISetToken _setToken, address _component, uint256 _unit) internal view returns(bool) {
return _setToken.getDefaultPositionRealUnit(_component) >= _unit.toInt256();
}
/**
* Returns whether the SetToken component external position is greater than or equal to the real units passed in.
*/
function hasSufficientExternalUnits(
ISetToken _setToken,
address _component,
address _positionModule,
uint256 _unit
)
internal
view
returns(bool)
{
return _setToken.getExternalPositionRealUnit(_component, _positionModule) >= _unit.toInt256();
}
/**
* If the position does not exist, create a new Position and add to the SetToken. If it already exists,
* then set the position units. If the new units is 0, remove the position. Handles adding/removing of
* components where needed (in light of potential external positions).
*
* @param _setToken Address of SetToken being modified
* @param _component Address of the component
* @param _newUnit Quantity of Position units - must be >= 0
*/
function editDefaultPosition(ISetToken _setToken, address _component, uint256 _newUnit) internal {
bool isPositionFound = hasDefaultPosition(_setToken, _component);
if (!isPositionFound && _newUnit > 0) {
// If there is no Default Position and no External Modules, then component does not exist
if (!hasExternalPosition(_setToken, _component)) {
_setToken.addComponent(_component);
}
} else if (isPositionFound && _newUnit == 0) {
// If there is a Default Position and no external positions, remove the component
if (!hasExternalPosition(_setToken, _component)) {
_setToken.removeComponent(_component);
}
}
_setToken.editDefaultPositionUnit(_component, _newUnit.toInt256());
}
/**
* Update an external position and remove and external positions or components if necessary. The logic flows as follows:
* 1) If component is not already added then add component and external position.
* 2) If component is added but no existing external position using the passed module exists then add the external position.
* 3) If the existing position is being added to then just update the unit and data
* 4) If the position is being closed and no other external positions or default positions are associated with the component
* then untrack the component and remove external position.
* 5) If the position is being closed and other existing positions still exist for the component then just remove the
* external position.
*
* @param _setToken SetToken being updated
* @param _component Component position being updated
* @param _module Module external position is associated with
* @param _newUnit Position units of new external position
* @param _data Arbitrary data associated with the position
*/
function editExternalPosition(
ISetToken _setToken,
address _component,
address _module,
int256 _newUnit,
bytes memory _data
)
internal
{
if (_newUnit != 0) {
if (!_setToken.isComponent(_component)) {
_setToken.addComponent(_component);
_setToken.addExternalPositionModule(_component, _module);
} else if (!_setToken.isExternalPositionModule(_component, _module)) {
_setToken.addExternalPositionModule(_component, _module);
}
_setToken.editExternalPositionUnit(_component, _module, _newUnit);
_setToken.editExternalPositionData(_component, _module, _data);
} else {
require(_data.length == 0, "Passed data must be null");
// If no default or external position remaining then remove component from components array
if (_setToken.getExternalPositionRealUnit(_component, _module) != 0) {
address[] memory positionModules = _setToken.getExternalPositionModules(_component);
if (_setToken.getDefaultPositionRealUnit(_component) == 0 && positionModules.length == 1) {
require(positionModules[0] == _module, "External positions must be 0 to remove component");
_setToken.removeComponent(_component);
}
_setToken.removeExternalPositionModule(_component, _module);
}
}
}
/**
* Get total notional amount of Default position
*
* @param _setTokenSupply Supply of SetToken in precise units (10^18)
* @param _positionUnit Quantity of Position units
*
* @return Total notional amount of units
*/
function getDefaultTotalNotional(uint256 _setTokenSupply, uint256 _positionUnit) internal pure returns (uint256) {
return _setTokenSupply.preciseMul(_positionUnit);
}
/**
* Get position unit from total notional amount
*
* @param _setTokenSupply Supply of SetToken in precise units (10^18)
* @param _totalNotional Total notional amount of component prior to
* @return Default position unit
*/
function getDefaultPositionUnit(uint256 _setTokenSupply, uint256 _totalNotional) internal pure returns (uint256) {
return _totalNotional.preciseDiv(_setTokenSupply);
}
/**
* Get the total tracked balance - total supply * position unit
*
* @param _setToken Address of the SetToken
* @param _component Address of the component
* @return Notional tracked balance
*/
function getDefaultTrackedBalance(ISetToken _setToken, address _component) internal view returns(uint256) {
int256 positionUnit = _setToken.getDefaultPositionRealUnit(_component);
return _setToken.totalSupply().preciseMul(positionUnit.toUint256());
}
/**
* Calculates the new default position unit and performs the edit with the new unit
*
* @param _setToken Address of the SetToken
* @param _component Address of the component
* @param _setTotalSupply Current SetToken supply
* @param _componentPreviousBalance Pre-action component balance
* @return Current component balance
* @return Previous position unit
* @return New position unit
*/
function calculateAndEditDefaultPosition(
ISetToken _setToken,
address _component,
uint256 _setTotalSupply,
uint256 _componentPreviousBalance
)
internal
returns(uint256, uint256, uint256)
{
uint256 currentBalance = IERC20(_component).balanceOf(address(_setToken));
uint256 positionUnit = _setToken.getDefaultPositionRealUnit(_component).toUint256();
uint256 newTokenUnit;
if (currentBalance > 0) {
newTokenUnit = calculateDefaultEditPositionUnit(
_setTotalSupply,
_componentPreviousBalance,
currentBalance,
positionUnit
);
} else {
newTokenUnit = 0;
}
editDefaultPosition(_setToken, _component, newTokenUnit);
return (currentBalance, positionUnit, newTokenUnit);
}
/**
* Calculate the new position unit given total notional values pre and post executing an action that changes SetToken state
* The intention is to make updates to the units without accidentally picking up airdropped assets as well.
*
* @param _setTokenSupply Supply of SetToken in precise units (10^18)
* @param _preTotalNotional Total notional amount of component prior to executing action
* @param _postTotalNotional Total notional amount of component after the executing action
* @param _prePositionUnit Position unit of SetToken prior to executing action
* @return New position unit
*/
function calculateDefaultEditPositionUnit(
uint256 _setTokenSupply,
uint256 _preTotalNotional,
uint256 _postTotalNotional,
uint256 _prePositionUnit
)
internal
pure
returns (uint256)
{
// If pre action total notional amount is greater then subtract post action total notional and calculate new position units
uint256 airdroppedAmount = _preTotalNotional.sub(_prePositionUnit.preciseMul(_setTokenSupply));
return _postTotalNotional.sub(airdroppedAmount).preciseDiv(_setTokenSupply);
}
}
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { SignedSafeMath } from "@openzeppelin/contracts/math/SignedSafeMath.sol";
/**
* @title PreciseUnitMath
* @author Set Protocol
*
* Arithmetic for fixed-point numbers with 18 decimals of precision. Some functions taken from
* dYdX's BaseMath library.
*
* CHANGELOG:
* - 9/21/20: Added safePower function
* - 4/21/21: Added approximatelyEquals function
*/
library PreciseUnitMath {
using SafeMath for uint256;
using SignedSafeMath for int256;
// The number One in precise units.
uint256 constant internal PRECISE_UNIT = 10 ** 18;
int256 constant internal PRECISE_UNIT_INT = 10 ** 18;
// Max unsigned integer value
uint256 constant internal MAX_UINT_256 = type(uint256).max;
// Max and min signed integer value
int256 constant internal MAX_INT_256 = type(int256).max;
int256 constant internal MIN_INT_256 = type(int256).min;
/**
* @dev Getter function since constants can't be read directly from libraries.
*/
function preciseUnit() internal pure returns (uint256) {
return PRECISE_UNIT;
}
/**
* @dev Getter function since constants can't be read directly from libraries.
*/
function preciseUnitInt() internal pure returns (int256) {
return PRECISE_UNIT_INT;
}
/**
* @dev Getter function since constants can't be read directly from libraries.
*/
function maxUint256() internal pure returns (uint256) {
return MAX_UINT_256;
}
/**
* @dev Getter function since constants can't be read directly from libraries.
*/
function maxInt256() internal pure returns (int256) {
return MAX_INT_256;
}
/**
* @dev Getter function since constants can't be read directly from libraries.
*/
function minInt256() internal pure returns (int256) {
return MIN_INT_256;
}
/**
* @dev Multiplies value a by value b (result is rounded down). It's assumed that the value b is the significand
* of a number with 18 decimals precision.
*/
function preciseMul(uint256 a, uint256 b) internal pure returns (uint256) {
return a.mul(b).div(PRECISE_UNIT);
}
/**
* @dev Multiplies value a by value b (result is rounded towards zero). It's assumed that the value b is the
* significand of a number with 18 decimals precision.
*/
function preciseMul(int256 a, int256 b) internal pure returns (int256) {
return a.mul(b).div(PRECISE_UNIT_INT);
}
/**
* @dev Multiplies value a by value b (result is rounded up). It's assumed that the value b is the significand
* of a number with 18 decimals precision.
*/
function preciseMulCeil(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0 || b == 0) {
return 0;
}
return a.mul(b).sub(1).div(PRECISE_UNIT).add(1);
}
/**
* @dev Divides value a by value b (result is rounded down).
*/
function preciseDiv(uint256 a, uint256 b) internal pure returns (uint256) {
return a.mul(PRECISE_UNIT).div(b);
}
/**
* @dev Divides value a by value b (result is rounded towards 0).
*/
function preciseDiv(int256 a, int256 b) internal pure returns (int256) {
return a.mul(PRECISE_UNIT_INT).div(b);
}
/**
* @dev Divides value a by value b (result is rounded up or away from 0).
*/
function preciseDivCeil(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "Cant divide by 0");
return a > 0 ? a.mul(PRECISE_UNIT).sub(1).div(b).add(1) : 0;
}
/**
* @dev Divides value a by value b (result is rounded down - positive numbers toward 0 and negative away from 0).
*/
function divDown(int256 a, int256 b) internal pure returns (int256) {
require(b != 0, "Cant divide by 0");
require(a != MIN_INT_256 || b != -1, "Invalid input");
int256 result = a.div(b);
if (a ^ b < 0 && a % b != 0) {
result -= 1;
}
return result;
}
/**
* @dev Multiplies value a by value b where rounding is towards the lesser number.
* (positive values are rounded towards zero and negative values are rounded away from 0).
*/
function conservativePreciseMul(int256 a, int256 b) internal pure returns (int256) {
return divDown(a.mul(b), PRECISE_UNIT_INT);
}
/**
* @dev Divides value a by value b where rounding is towards the lesser number.
* (positive values are rounded towards zero and negative values are rounded away from 0).
*/
function conservativePreciseDiv(int256 a, int256 b) internal pure returns (int256) {
return divDown(a.mul(PRECISE_UNIT_INT), b);
}
/**
* @dev Performs the power on a specified value, reverts on overflow.
*/
function safePower(
uint256 a,
uint256 pow
)
internal
pure
returns (uint256)
{
require(a > 0, "Value must be positive");
uint256 result = 1;
for (uint256 i = 0; i < pow; i++){
uint256 previousResult = result;
// Using safemath multiplication prevents overflows
result = previousResult.mul(a);
}
return result;
}
/**
* @dev Returns true if a =~ b within range, false otherwise.
*/
function approximatelyEquals(uint256 a, uint256 b, uint256 range) internal pure returns (bool) {
return a <= b.add(range) && a >= b.sub(range);
}
}
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
import { IController } from "../../interfaces/IController.sol";
import { IIntegrationRegistry } from "../../interfaces/IIntegrationRegistry.sol";
import { IPriceOracle } from "../../interfaces/IPriceOracle.sol";
import { ISetValuer } from "../../interfaces/ISetValuer.sol";
/**
* @title ResourceIdentifier
* @author Set Protocol
*
* A collection of utility functions to fetch information related to Resource contracts in the system
*/
library ResourceIdentifier {
// IntegrationRegistry will always be resource ID 0 in the system
uint256 constant internal INTEGRATION_REGISTRY_RESOURCE_ID = 0;
// PriceOracle will always be resource ID 1 in the system
uint256 constant internal PRICE_ORACLE_RESOURCE_ID = 1;
// SetValuer resource will always be resource ID 2 in the system
uint256 constant internal SET_VALUER_RESOURCE_ID = 2;
/* ============ Internal ============ */
/**
* Gets the instance of integration registry stored on Controller. Note: IntegrationRegistry is stored as index 0 on
* the Controller
*/
function getIntegrationRegistry(IController _controller) internal view returns (IIntegrationRegistry) {
return IIntegrationRegistry(_controller.resourceId(INTEGRATION_REGISTRY_RESOURCE_ID));
}
/**
* Gets instance of price oracle on Controller. Note: PriceOracle is stored as index 1 on the Controller
*/
function getPriceOracle(IController _controller) internal view returns (IPriceOracle) {
return IPriceOracle(_controller.resourceId(PRICE_ORACLE_RESOURCE_ID));
}
/**
* Gets the instance of Set valuer on Controller. Note: SetValuer is stored as index 2 on the Controller
*/
function getSetValuer(IController _controller) internal view returns (ISetValuer) {
return ISetValuer(_controller.resourceId(SET_VALUER_RESOURCE_ID));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*
* Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
* all math on `uint256` and `int256` and then downcasting.
*/
library SafeCast {
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v3.1._
*/
function toInt128(int256 value) internal pure returns (int128) {
require(value >= -2**127 && value < 2**127, "SafeCast: value doesn\'t fit in 128 bits");
return int128(value);
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v3.1._
*/
function toInt64(int256 value) internal pure returns (int64) {
require(value >= -2**63 && value < 2**63, "SafeCast: value doesn\'t fit in 64 bits");
return int64(value);
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v3.1._
*/
function toInt32(int256 value) internal pure returns (int32) {
require(value >= -2**31 && value < 2**31, "SafeCast: value doesn\'t fit in 32 bits");
return int32(value);
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v3.1._
*/
function toInt16(int256 value) internal pure returns (int16) {
require(value >= -2**15 && value < 2**15, "SafeCast: value doesn\'t fit in 16 bits");
return int16(value);
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*
* _Available since v3.1._
*/
function toInt8(int256 value) internal pure returns (int8) {
require(value >= -2**7 && value < 2**7, "SafeCast: value doesn\'t fit in 8 bits");
return int8(value);
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
require(value < 2**255, "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @title SignedSafeMath
* @dev Signed math operations with safety checks that revert on error.
*/
library SignedSafeMath {
int256 constant private _INT256_MIN = -2**255;
/**
* @dev Returns the multiplication of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(int256 a, int256 b) internal pure returns (int256) {
// 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;
}
require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow");
int256 c = a * b;
require(c / a == b, "SignedSafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two signed 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(int256 a, int256 b) internal pure returns (int256) {
require(b != 0, "SignedSafeMath: division by zero");
require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow");
int256 c = a / b;
return c;
}
/**
* @dev Returns the subtraction of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow");
return c;
}
/**
* @dev Returns the addition of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow");
return c;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
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);
}
}
}
}
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
interface IIntegrationRegistry {
function addIntegration(address _module, string memory _id, address _wrapper) external;
function getIntegrationAdapter(address _module, string memory _id) external view returns(address);
function getIntegrationAdapterWithHash(address _module, bytes32 _id) external view returns(address);
function isValidIntegration(address _module, string memory _id) external view returns(bool);
}
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
/**
* @title IPriceOracle
* @author Set Protocol
*
* Interface for interacting with PriceOracle
*/
interface IPriceOracle {
/* ============ Functions ============ */
function getPrice(address _assetOne, address _assetTwo) external view returns (uint256);
function masterQuoteAsset() external view returns (address);
}
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
import { ISetToken } from "../interfaces/ISetToken.sol";
interface ISetValuer {
function calculateSetTokenValuation(ISetToken _setToken, address _quoteAsset) external view returns (uint256);
}
| SetToken must be in a pending state and module must be in pending state/ | function _validateOnlyValidAndPendingSet(ISetToken _setToken) internal view {
require(controller.isSet(address(_setToken)), "Must be controller-enabled SetToken");
require(isSetPendingInitialization(_setToken), "Must be pending initialization");
}
| 462,824 |
./full_match/1/0xEb4A2ba7033a7E897D92dD5427824d9f3A1A3220/sources/erc721psi/contracts/ERC721PsiUpgradeable.sol | See {IERC721-transferFrom}./solhint-disable-next-line max-line-length | function transferFrom(address from, address to, uint256 tokenId) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), 'ERC721Psi: transfer caller is not owner nor approved');
_transfer(from, to, tokenId);
}
| 8,381,946 |
./full_match/43113/0x68cCe108A38E40942f1b490719d732C5f08f65C3/sources/contracts/modiferc721.sol | 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;
}
| 13,179,385 |
pragma solidity 0.6.12;
//----------------------------------------------------------------------------------
// I n s t a n t
//
// .:mmm. .:mmm:. .ii. .:SSSSSSSSSSSSS. .oOOOOOOOOOOOo.
// .mMM'':Mm. .:MM'':Mm:. .II: :SSs.......... .oOO'''''''''''OOo.
// .:Mm' ':Mm. .:Mm' 'MM:. .II: 'sSSSSSSSSSSSSS:. :OO. .OO:
// .'mMm' ':MM:.:MMm' ':MM:. .II: .:...........:SS. 'OOo:.........:oOO'
// 'mMm' ':MMmm' 'mMm: II: 'sSSSSSSSSSSSSS' 'oOOOOOOOOOOOO'
//
//----------------------------------------------------------------------------------
//
// Chef Gonpachi's Post Auction Launcher
//
// A post auction contract that takes the proceeds and creates a liquidity pool
//
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// Made for Sushi.com
//
// Enjoy. (c) Chef Gonpachi
// <https://github.com/chefgonpachi/MISO/>
//
// ---------------------------------------------------------------------
// SPDX-License-Identifier: GPL-3.0
// ---------------------------------------------------------------------
import "../OpenZeppelin/utils/ReentrancyGuard.sol";
import "../Access/MISOAccessControls.sol";
import "../Utils/SafeTransfer.sol";
import "../Utils/BoringMath.sol";
import "../UniswapV2/UniswapV2Library.sol";
import "../UniswapV2/interfaces/IUniswapV2Pair.sol";
import "../UniswapV2/interfaces/IUniswapV2Factory.sol";
import "../interfaces/IWETH9.sol";
import "../interfaces/IERC20.sol";
import "../interfaces/IMisoAuction.sol";
contract PostAuctionLauncher is MISOAccessControls, SafeTransfer, ReentrancyGuard {
using BoringMath for uint256;
using BoringMath128 for uint128;
using BoringMath64 for uint64;
using BoringMath32 for uint32;
using BoringMath16 for uint16;
address private constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
uint256 private constant LIQUIDITY_PRECISION = 10000;
/// @notice MISOLiquidity template id.
uint256 public constant liquidityTemplate = 3;
/// @notice First Token address.
IERC20 public token1;
/// @notice Second Token address.
IERC20 public token2;
/// @notice Uniswap V2 factory address.
IUniswapV2Factory public factory;
/// @notice WETH contract address.
address private immutable weth;
/// @notice LP pair address.
address public tokenPair;
/// @notice Withdraw wallet address.
address public wallet;
/// @notice Token market contract address.
IMisoAuction public market;
struct LauncherInfo {
uint32 locktime;
uint64 unlock;
uint16 liquidityPercent;
bool launched;
uint128 liquidityAdded;
}
LauncherInfo public launcherInfo;
/// @notice Emitted when LP contract is initialised.
event InitLiquidityLauncher(address indexed token1, address indexed token2, address factory, address sender);
/// @notice Emitted when LP is launched.
event LiquidityAdded(uint256 liquidity);
/// @notice Emitted when wallet is updated.
event WalletUpdated(address indexed wallet);
/// @notice Emitted when launcher is cancelled.
event LauncherCancelled(address indexed wallet);
constructor (address _weth) public {
weth = _weth;
}
/**
* @notice Initializes main contract variables (requires launchwindow to be more than 2 days.)
* @param _market Auction address for launcher.
* @param _factory Uniswap V2 factory address.
* @param _admin Contract owner address.
* @param _wallet Withdraw wallet address.
* @param _liquidityPercent Percentage of payment currency sent to liquidity pool.
* @param _locktime How long the liquidity will be locked. Number of seconds.
*/
function initAuctionLauncher(
address _market,
address _factory,
address _admin,
address _wallet,
uint256 _liquidityPercent,
uint256 _locktime
)
public
{
require(_locktime < 10000000000, 'PostAuction: Enter an unix timestamp in seconds, not miliseconds');
require(_liquidityPercent <= LIQUIDITY_PRECISION, 'PostAuction: Liquidity percentage greater than 100.00% (>10000)');
require(_liquidityPercent > 0, 'PostAuction: Liquidity percentage equals zero');
require(_admin != address(0), "PostAuction: admin is the zero address");
require(_wallet != address(0), "PostAuction: wallet is the zero address");
initAccessControls(_admin);
market = IMisoAuction(_market);
token1 = IERC20(market.paymentCurrency());
token2 = IERC20(market.auctionToken());
if (address(token1) == ETH_ADDRESS) {
token1 = IERC20(weth);
}
uint256 d1 = uint256(token1.decimals());
uint256 d2 = uint256(token2.decimals());
require(d2 >= d1);
factory = IUniswapV2Factory(_factory);
bytes32 pairCodeHash = IUniswapV2Factory(_factory).pairCodeHash();
tokenPair = UniswapV2Library.pairFor(_factory, address(token1), address(token2), pairCodeHash);
wallet = _wallet;
launcherInfo.liquidityPercent = BoringMath.to16(_liquidityPercent);
launcherInfo.locktime = BoringMath.to32(_locktime);
uint256 initalTokenAmount = market.getTotalTokens().mul(_liquidityPercent).div(LIQUIDITY_PRECISION);
_safeTransferFrom(address(token2), msg.sender, initalTokenAmount);
emit InitLiquidityLauncher(address(token1), address(token2), address(_factory), _admin);
}
receive() external payable {
if(msg.sender != weth ){
depositETH();
}
}
/// @notice Deposits ETH to the contract.
function depositETH() public payable {
require(address(token1) == weth || address(token2) == weth, "PostAuction: Launcher not accepting ETH");
if (msg.value > 0 ) {
IWETH(weth).deposit{value : msg.value}();
}
}
/**
* @notice Deposits first Token to the contract.
* @param _amount Number of tokens to deposit.
*/
function depositToken1(uint256 _amount) external returns (bool success) {
return _deposit( address(token1), msg.sender, _amount);
}
/**
* @notice Deposits second Token to the contract.
* @param _amount Number of tokens to deposit.
*/
function depositToken2(uint256 _amount) external returns (bool success) {
return _deposit( address(token2), msg.sender, _amount);
}
/**
* @notice Deposits Tokens to the contract.
* @param _amount Number of tokens to deposit.
* @param _from Where the tokens to deposit will come from.
* @param _token Token address.
*/
function _deposit(address _token, address _from, uint _amount) internal returns (bool success) {
require(!launcherInfo.launched, "PostAuction: Must first launch liquidity");
require(launcherInfo.liquidityAdded == 0, "PostAuction: Liquidity already added");
require(_amount > 0, "PostAuction: Token amount must be greater than 0");
_safeTransferFrom(_token, _from, _amount);
return true;
}
/**
* @notice Checks if market wallet is set to this launcher
*/
function marketConnected() public view returns (bool) {
return market.wallet() == address(this);
}
/**
* @notice Finalizes Token sale and launches LP.
* @return liquidity Number of LPs.
*/
function finalize() external nonReentrant returns (uint256 liquidity) {
// GP: Can we remove admin, let anyone can finalise and launch?
// require(hasAdminRole(msg.sender) || hasOperatorRole(msg.sender), "PostAuction: Sender must be operator");
require(marketConnected(), "PostAuction: Auction must have this launcher address set as the destination wallet");
require(!launcherInfo.launched);
if (!market.finalized()) {
market.finalize();
}
launcherInfo.launched = true;
if (!market.auctionSuccessful() ) {
return 0;
}
/// @dev if the auction is settled in weth, wrap any contract balance
uint256 launcherBalance = address(this).balance;
if (launcherBalance > 0 ) {
IWETH(weth).deposit{value : launcherBalance}();
}
(uint256 token1Amount, uint256 token2Amount) = getTokenAmounts();
/// @dev cannot start a liquidity pool with no tokens on either side
if (token1Amount == 0 || token2Amount == 0 ) {
return 0;
}
address pair = factory.getPair(address(token1), address(token2));
require(pair == address(0) || getLPBalance() == 0, "PostLiquidity: Pair not new");
if(pair == address(0)) {
createPool();
}
/// @dev add liquidity to pool via the pair directly
_safeTransfer(address(token1), tokenPair, token1Amount);
_safeTransfer(address(token2), tokenPair, token2Amount);
liquidity = IUniswapV2Pair(tokenPair).mint(address(this));
launcherInfo.liquidityAdded = BoringMath.to128(uint256(launcherInfo.liquidityAdded).add(liquidity));
/// @dev if unlock time not yet set, add it.
if (launcherInfo.unlock == 0 ) {
launcherInfo.unlock = BoringMath.to64(block.timestamp + uint256(launcherInfo.locktime));
}
emit LiquidityAdded(liquidity);
}
function getTokenAmounts() public view returns (uint256 token1Amount, uint256 token2Amount) {
token1Amount = getToken1Balance().mul(uint256(launcherInfo.liquidityPercent)).div(LIQUIDITY_PRECISION);
token2Amount = getToken2Balance();
uint256 tokenPrice = market.tokenPrice();
uint256 d2 = uint256(token2.decimals());
uint256 maxToken1Amount = token2Amount.mul(tokenPrice).div(10**(d2));
uint256 maxToken2Amount = token1Amount
.mul(10**(d2))
.div(tokenPrice);
/// @dev if more than the max.
if (token2Amount > maxToken2Amount) {
token2Amount = maxToken2Amount;
}
/// @dev if more than the max.
if (token1Amount > maxToken1Amount) {
token1Amount = maxToken1Amount;
}
}
/**
* @notice Withdraws LPs from the contract.
* @return liquidity Number of LPs.
*/
function withdrawLPTokens() external returns (uint256 liquidity) {
require(hasAdminRole(msg.sender) || hasOperatorRole(msg.sender), "PostAuction: Sender must be operator");
require(launcherInfo.launched, "PostAuction: Must first launch liquidity");
require(block.timestamp >= uint256(launcherInfo.unlock), "PostAuction: Liquidity is locked");
liquidity = IERC20(tokenPair).balanceOf(address(this));
require(liquidity > 0, "PostAuction: Liquidity must be greater than 0");
_safeTransfer(tokenPair, wallet, liquidity);
}
/// @notice Withraws deposited tokens and ETH from the contract to wallet.
function withdrawDeposits() external {
require(hasAdminRole(msg.sender) || hasOperatorRole(msg.sender), "PostAuction: Sender must be operator");
require(launcherInfo.launched, "PostAuction: Must first launch liquidity");
uint256 token1Amount = getToken1Balance();
if (token1Amount > 0 ) {
_safeTransfer(address(token1), wallet, token1Amount);
}
uint256 token2Amount = getToken2Balance();
if (token2Amount > 0 ) {
_safeTransfer(address(token2), wallet, token2Amount);
}
}
// TODO
// GP: Sweep non relevant ERC20s / ETH
//--------------------------------------------------------
// Setter functions
//--------------------------------------------------------
/**
* @notice Admin can set the wallet through this function.
* @param _wallet Wallet is where funds will be sent.
*/
function setWallet(address payable _wallet) external {
require(hasAdminRole(msg.sender));
require(_wallet != address(0), "Wallet is the zero address");
wallet = _wallet;
emit WalletUpdated(_wallet);
}
function cancelLauncher() external {
require(hasAdminRole(msg.sender));
require(!launcherInfo.launched);
launcherInfo.launched = true;
emit LauncherCancelled(msg.sender);
}
//--------------------------------------------------------
// Helper functions
//--------------------------------------------------------
/**
* @notice Creates new SLP pair through SushiSwap.
*/
function createPool() internal {
factory.createPair(address(token1), address(token2));
}
//--------------------------------------------------------
// Getter functions
//--------------------------------------------------------
/**
* @notice Gets the number of first token deposited into this contract.
* @return uint256 Number of WETH.
*/
function getToken1Balance() public view returns (uint256) {
return token1.balanceOf(address(this));
}
/**
* @notice Gets the number of second token deposited into this contract.
* @return uint256 Number of WETH.
*/
function getToken2Balance() public view returns (uint256) {
return token2.balanceOf(address(this));
}
/**
* @notice Returns LP token address..
* @return address LP address.
*/
function getLPTokenAddress() public view returns (address) {
return tokenPair;
}
/**
* @notice Returns LP Token balance.
* @return uint256 LP Token balance.
*/
function getLPBalance() public view returns (uint256) {
return IERC20(tokenPair).balanceOf(address(this));
}
//--------------------------------------------------------
// Init functions
//--------------------------------------------------------
/**
* @notice Decodes and hands auction data to the initAuction function.
* @param _data Encoded data for initialization.
*/
function init(bytes calldata _data) external payable {
}
function initLauncher(
bytes calldata _data
) public {
(
address _market,
address _factory,
address _admin,
address _wallet,
uint256 _liquidityPercent,
uint256 _locktime
) = abi.decode(_data, (
address,
address,
address,
address,
uint256,
uint256
));
initAuctionLauncher( _market, _factory,_admin,_wallet,_liquidityPercent,_locktime);
}
/**
* @notice Collects data to initialize the auction and encodes them.
* @param _market Auction address for launcher.
* @param _factory Uniswap V2 factory address.
* @param _admin Contract owner address.
* @param _wallet Withdraw wallet address.
* @param _liquidityPercent Percentage of payment currency sent to liquidity pool.
* @param _locktime How long the liquidity will be locked. Number of seconds.
* @return _data All the data in bytes format.
*/
function getLauncherInitData(
address _market,
address _factory,
address _admin,
address _wallet,
uint256 _liquidityPercent,
uint256 _locktime
)
external
pure
returns (bytes memory _data)
{
return abi.encode(_market,
_factory,
_admin,
_wallet,
_liquidityPercent,
_locktime
);
}
}
pragma solidity 0.6.12;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () internal {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.6.12;
import "./MISOAdminAccess.sol";
/**
* @notice Access Controls
* @author Attr: BlockRocket.tech
*/
contract MISOAccessControls is MISOAdminAccess {
/// @notice Role definitions
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 public constant SMART_CONTRACT_ROLE = keccak256("SMART_CONTRACT_ROLE");
bytes32 public constant OPERATOR_ROLE = keccak256("OPERATOR_ROLE");
/**
* @notice The deployer is automatically given the admin role which will allow them to then grant roles to other addresses
*/
constructor() public {
}
/////////////
// Lookups //
/////////////
/**
* @notice Used to check whether an address has the minter role
* @param _address EOA or contract being checked
* @return bool True if the account has the role or false if it does not
*/
function hasMinterRole(address _address) public view returns (bool) {
return hasRole(MINTER_ROLE, _address);
}
/**
* @notice Used to check whether an address has the smart contract role
* @param _address EOA or contract being checked
* @return bool True if the account has the role or false if it does not
*/
function hasSmartContractRole(address _address) public view returns (bool) {
return hasRole(SMART_CONTRACT_ROLE, _address);
}
/**
* @notice Used to check whether an address has the operator role
* @param _address EOA or contract being checked
* @return bool True if the account has the role or false if it does not
*/
function hasOperatorRole(address _address) public view returns (bool) {
return hasRole(OPERATOR_ROLE, _address);
}
///////////////
// Modifiers //
///////////////
/**
* @notice Grants the minter role to an address
* @dev The sender must have the admin role
* @param _address EOA or contract receiving the new role
*/
function addMinterRole(address _address) external {
grantRole(MINTER_ROLE, _address);
}
/**
* @notice Removes the minter role from an address
* @dev The sender must have the admin role
* @param _address EOA or contract affected
*/
function removeMinterRole(address _address) external {
revokeRole(MINTER_ROLE, _address);
}
/**
* @notice Grants the smart contract role to an address
* @dev The sender must have the admin role
* @param _address EOA or contract receiving the new role
*/
function addSmartContractRole(address _address) external {
grantRole(SMART_CONTRACT_ROLE, _address);
}
/**
* @notice Removes the smart contract role from an address
* @dev The sender must have the admin role
* @param _address EOA or contract affected
*/
function removeSmartContractRole(address _address) external {
revokeRole(SMART_CONTRACT_ROLE, _address);
}
/**
* @notice Grants the operator role to an address
* @dev The sender must have the admin role
* @param _address EOA or contract receiving the new role
*/
function addOperatorRole(address _address) external {
grantRole(OPERATOR_ROLE, _address);
}
/**
* @notice Removes the operator role from an address
* @dev The sender must have the admin role
* @param _address EOA or contract affected
*/
function removeOperatorRole(address _address) external {
revokeRole(OPERATOR_ROLE, _address);
}
}
pragma solidity 0.6.12;
contract SafeTransfer {
address private constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
/// @notice Event for token withdrawals.
event TokensWithdrawn(address token, address to, uint256 amount);
/// @dev Helper function to handle both ETH and ERC20 payments
function _safeTokenPayment(
address _token,
address payable _to,
uint256 _amount
) internal {
if (address(_token) == ETH_ADDRESS) {
_safeTransferETH(_to,_amount );
} else {
_safeTransfer(_token, _to, _amount);
}
emit TokensWithdrawn(_token, _to, _amount);
}
/// @dev Helper function to handle both ETH and ERC20 payments
function _tokenPayment(
address _token,
address payable _to,
uint256 _amount
) internal {
if (address(_token) == ETH_ADDRESS) {
_to.transfer(_amount);
} else {
_safeTransfer(_token, _to, _amount);
}
emit TokensWithdrawn(_token, _to, _amount);
}
/// @dev Transfer helper from UniswapV2 Router
function _safeApprove(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED');
}
/**
* There are many non-compliant ERC20 tokens... this can handle most, adapted from UniSwap V2
* Im trying to make it a habit to put external calls last (reentrancy)
* You can put this in an internal function if you like.
*/
function _safeTransfer(
address token,
address to,
uint256 amount
) internal virtual {
// solium-disable-next-line security/no-low-level-calls
(bool success, bytes memory data) =
token.call(
// 0xa9059cbb = bytes4(keccak256("transfer(address,uint256)"))
abi.encodeWithSelector(0xa9059cbb, to, amount)
);
require(success && (data.length == 0 || abi.decode(data, (bool)))); // ERC20 Transfer failed
}
function _safeTransferFrom(
address token,
address from,
uint256 amount
) internal virtual {
// solium-disable-next-line security/no-low-level-calls
(bool success, bytes memory data) =
token.call(
// 0x23b872dd = bytes4(keccak256("transferFrom(address,address,uint256)"))
abi.encodeWithSelector(0x23b872dd, from, address(this), amount)
);
require(success && (data.length == 0 || abi.decode(data, (bool)))); // ERC20 TransferFrom failed
}
function _safeTransferFrom(address token, address from, address to, uint value) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED');
}
function _safeTransferETH(address to, uint value) internal {
(bool success,) = to.call{value:value}(new bytes(0));
require(success, 'TransferHelper: ETH_TRANSFER_FAILED');
}
}
pragma solidity 0.6.12;
/// @notice A library for performing overflow-/underflow-safe math,
/// updated with awesomeness from of DappHub (https://github.com/dapphub/ds-math).
library BoringMath {
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
require((c = a + b) >= b, "BoringMath: Add Overflow");
}
function sub(uint256 a, uint256 b) internal pure returns (uint256 c) {
require((c = a - b) <= a, "BoringMath: Underflow");
}
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
require(b == 0 || (c = a * b) / b == a, "BoringMath: Mul Overflow");
}
function div(uint256 a, uint256 b) internal pure returns (uint256 c) {
require(b > 0, "BoringMath: Div zero");
c = a / b;
}
function to128(uint256 a) internal pure returns (uint128 c) {
require(a <= uint128(-1), "BoringMath: uint128 Overflow");
c = uint128(a);
}
function to64(uint256 a) internal pure returns (uint64 c) {
require(a <= uint64(-1), "BoringMath: uint64 Overflow");
c = uint64(a);
}
function to32(uint256 a) internal pure returns (uint32 c) {
require(a <= uint32(-1), "BoringMath: uint32 Overflow");
c = uint32(a);
}
function to16(uint256 a) internal pure returns (uint16 c) {
require(a <= uint16(-1), "BoringMath: uint16 Overflow");
c = uint16(a);
}
}
/// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint128.
library BoringMath128 {
function add(uint128 a, uint128 b) internal pure returns (uint128 c) {
require((c = a + b) >= b, "BoringMath: Add Overflow");
}
function sub(uint128 a, uint128 b) internal pure returns (uint128 c) {
require((c = a - b) <= a, "BoringMath: Underflow");
}
}
/// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint64.
library BoringMath64 {
function add(uint64 a, uint64 b) internal pure returns (uint64 c) {
require((c = a + b) >= b, "BoringMath: Add Overflow");
}
function sub(uint64 a, uint64 b) internal pure returns (uint64 c) {
require((c = a - b) <= a, "BoringMath: Underflow");
}
}
/// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint32.
library BoringMath32 {
function add(uint32 a, uint32 b) internal pure returns (uint32 c) {
require((c = a + b) >= b, "BoringMath: Add Overflow");
}
function sub(uint32 a, uint32 b) internal pure returns (uint32 c) {
require((c = a - b) <= a, "BoringMath: Underflow");
}
}
/// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint32.
library BoringMath16 {
function add(uint16 a, uint16 b) internal pure returns (uint16 c) {
require((c = a + b) >= b, "BoringMath: Add Overflow");
}
function sub(uint16 a, uint16 b) internal pure returns (uint16 c) {
require((c = a - b) <= a, "BoringMath: Underflow");
}
}
pragma solidity 0.6.12;
import './interfaces/IUniswapV2Pair.sol';
import "./libraries/SafeMath.sol";
library UniswapV2Library {
using SafeMathUniswap 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, bytes32 pairCodeHash) 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)),
pairCodeHash // init code hash
))));
}
// fetches and sorts the reserves for a pair
function getReserves(address factory, address tokenA, address tokenB, bytes32 pairCodeHash) internal view returns (uint reserveA, uint reserveB) {
(address token0,) = sortTokens(tokenA, tokenB);
(uint reserve0, uint reserve1,) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB, pairCodeHash)).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, bytes32 pairCodeHash) 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], pairCodeHash);
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, bytes32 pairCodeHash) 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], pairCodeHash);
amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut);
}
}
}
pragma solidity 0.6.12;
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;
}
pragma solidity 0.6.12;
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function migrator() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function pairCodeHash() external pure returns (bytes32);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
function setMigrator(address) external;
}
pragma solidity 0.6.12;
import "./IERC20.sol";
interface IWETH is IERC20 {
function deposit() external payable;
function withdraw(uint) external;
function transfer(address, uint) external returns (bool);
}
pragma solidity 0.6.12;
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
function transferFrom(
address from,
address to,
uint256 amount
) external returns (bool);
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
}
pragma solidity 0.6.12;
interface IMisoAuction {
function initAuction(
address _funder,
address _token,
uint256 _tokenSupply,
uint256 _startDate,
uint256 _endDate,
address _paymentCurrency,
uint256 _startPrice,
uint256 _minimumPrice,
address _operator,
address _pointList,
address payable _wallet
) external;
function auctionSuccessful() external view returns (bool);
function finalized() external view returns (bool);
function wallet() external view returns (address);
function paymentCurrency() external view returns (address);
function auctionToken() external view returns (address);
function finalize() external;
function tokenPrice() external view returns (uint256);
function getTotalTokens() external view returns (uint256);
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.6.12;
import "../OpenZeppelin/access/AccessControl.sol";
contract MISOAdminAccess is AccessControl {
/// @dev Whether access is initialised.
bool private initAccess;
/// @notice The deployer is automatically given the admin role which will allow them to then grant roles to other addresses.
constructor() public {
}
/**
* @notice Initializes access controls.
* @param _admin Admins address.
*/
function initAccessControls(address _admin) public {
require(!initAccess, "Already initialised");
require(_admin != address(0), "Incorrect input");
_setupRole(DEFAULT_ADMIN_ROLE, _admin);
initAccess = true;
}
/////////////
// Lookups //
/////////////
/**
* @notice Used to check whether an address has the admin role.
* @param _address EOA or contract being checked.
* @return bool True if the account has the role or false if it does not.
*/
function hasAdminRole(address _address) public view returns (bool) {
return hasRole(DEFAULT_ADMIN_ROLE, _address);
}
///////////////
// Modifiers //
///////////////
/**
* @notice Grants the admin role to an address.
* @dev The sender must have the admin role.
* @param _address EOA or contract receiving the new role.
*/
function addAdminRole(address _address) external {
grantRole(DEFAULT_ADMIN_ROLE, _address);
}
/**
* @notice Removes the admin role from an address.
* @dev The sender must have the admin role.
* @param _address EOA or contract affected.
*/
function removeAdminRole(address _address) external {
revokeRole(DEFAULT_ADMIN_ROLE, _address);
}
}
pragma solidity 0.6.12;
import "../utils/EnumerableSet.sol";
import "../utils/Context.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context {
using EnumerableSet for EnumerableSet.AddressSet;
struct RoleData {
EnumerableSet.AddressSet members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view returns (bool) {
return _roles[role].members.contains(account);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view returns (uint256) {
return _roles[role].members.length();
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view returns (address) {
return _roles[role].members.at(index);
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant");
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke");
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, _roles[role].adminRole, adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
}
pragma solidity 0.6.12;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
pragma solidity 0.6.12;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
pragma solidity =0.6.12;
// a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math)
library SafeMathUniswap {
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x, 'ds-math-add-overflow');
}
function sub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x, 'ds-math-sub-underflow');
}
function mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow');
}
} | Collects data to initialize the auction and encodes them. _market Auction address for launcher. _factory Uniswap V2 factory address. _admin Contract owner address. _wallet Withdraw wallet address. _liquidityPercent Percentage of payment currency sent to liquidity pool. _locktime How long the liquidity will be locked. Number of seconds. return _data All the data in bytes format./ | function getLauncherInitData(
address _market,
address _factory,
address _admin,
address _wallet,
uint256 _liquidityPercent,
uint256 _locktime
)
external
pure
returns (bytes memory _data)
{
return abi.encode(_market,
_factory,
_admin,
_wallet,
_liquidityPercent,
_locktime
);
}
| 82,040 |
pragma solidity 0.4.26;
library SafeMath {
/** SafeMath **
* SafeMath based on the OpenZeppelin framework
* https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/SafeMath.sol
*/
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) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
uint256 c = a - b;
return c;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function max64(uint64 a, uint64 b) internal pure returns (uint64) {
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b) internal pure returns (uint64) {
return a < b ? a : b;
}
function max256(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
function abs128(int128 a) internal pure returns (int128) {
return a < 0 ? a * -1 : a;
}
}
contract Accessible {
/** Access Right Management **
* Copyright 2019
* Florian Weigand
* Synalytix UG, Munich
* florian(at)synalytix.de
*/
address public owner;
mapping(address => bool) public accessAllowed;
constructor() public {
owner = msg.sender;
}
modifier ownership() {
require(owner == msg.sender, "Accessible: Only the owner of contract can call this method");
_;
}
modifier accessible() {
require(accessAllowed[msg.sender], "Accessible: This address has no allowence to access this method");
_;
}
function allowAccess(address _address) public ownership {
if (_address != address(0)) {
accessAllowed[_address] = true;
}
}
function denyAccess(address _address) public ownership {
if (_address != address(0)) {
accessAllowed[_address] = false;
}
}
function transferOwnership(address _address) public ownership {
if (_address != address(0)) {
owner = _address;
}
}
}
contract Repaying is Accessible {
/** Repaying Contract **
* Idea based on https://ethereum.stackexchange.com/a/38517/55678
* Stackexchange user: medvedev1088
* ---------------------
* ReentrancyGuard based on the OpenZeppelin framework
* https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/ReentrancyGuard.sol
* ---------------------
* Copyright 2019 (only modifications)
* Florian Weigand
* Synalytix UG, Munich
* florian(at)synalytix.de
*/
using SafeMath for uint256;
uint256 private guardCounter;
bool stopRepaying = false;
// the max gas price is set to 65 gwei this is the same as local server max fee setting
uint256 maxGasPrice = 65000000000;
// gas consomption of the repayable function
uint256 additionalGasConsumption = 42492;
constructor () internal {
// the counter starts at one to prevent changing it from zero to a non-zero
// value, which is a more expensive operation.
guardCounter = 1;
}
modifier repayable {
guardCounter += 1;
uint256 localCounter = guardCounter;
// repayable logic with kill swtich
if(!stopRepaying) {
uint256 startGas = gasleft();
_;
uint256 gasUsed = startGas.sub(gasleft());
// use maxGasPrice as upper bound for the gas price
uint256 gasPrice = maxGasPrice.min256(tx.gasprice);
uint256 repayal = gasPrice.mul(gasUsed.add(additionalGasConsumption));
msg.sender.transfer(repayal);
}
else {
_;
}
// if the counters don't match a reentrance is happening, stop the execution
require(localCounter == guardCounter, "Repaying: reentrant call detected");
}
function() external payable {
require(msg.data.length == 0, "Repaying: You can only transfer Ether to this contract *without* any data");
}
function withdraw(address _address) public ownership {
require(_address != address(0) && (accessAllowed[_address] || _address == owner),
"Repaying: Address is not allowed to withdraw the balance");
_address.transfer(address(this).balance);
}
function setMaxGasPrice(uint256 _maxGasPrice) public ownership {
// define absolute max. with 125 gwei
maxGasPrice = _maxGasPrice.min256(125000000000);
}
function getMaxGasPrice() external view returns (uint256) {
return maxGasPrice;
}
function setAdditionalGasConsumption(uint256 _additionalGasConsumption) public ownership {
// define absolute max. with 65.000 gas limit
additionalGasConsumption = _additionalGasConsumption.min256(65000);
}
function getAdditionalGasConsumption() external view returns (uint256) {
return additionalGasConsumption;
}
function setStopRepaying(bool _stopRepaying) public ownership {
stopRepaying = _stopRepaying;
}
}
contract TrueProfileStorage is Accessible {
/** Data Storage Contract **
* Copyright 2019
* Florian Weigand
* Synalytix UG, Munich
* florian(at)synalytix.de
*/
/**** signature struct ****/
struct Signature {
uint8 v;
bytes32 r;
bytes32 s;
uint8 revocationReasonId;
bool isValue;
}
/**** signature storage ****/
mapping(bytes32 => Signature) public signatureStorage;
/**** general storage of non-struct data which might
be needed for further development of main contract ****/
mapping(bytes32 => uint256) public uIntStorage;
mapping(bytes32 => string) public stringStorage;
mapping(bytes32 => address) public addressStorage;
mapping(bytes32 => bytes) public bytesStorage;
mapping(bytes32 => bool) public boolStorage;
mapping(bytes32 => int256) public intStorage;
/**** CRUD for Signature storage ****/
function getSignature(bytes32 _key) external view returns (uint8 v, bytes32 r, bytes32 s, uint8 revocationReasonId) {
Signature memory tempSignature = signatureStorage[_key];
if (tempSignature.isValue) {
return(tempSignature.v, tempSignature.r, tempSignature.s, tempSignature.revocationReasonId);
} else {
return(0, bytes32(0), bytes32(0), 0);
}
}
function setSignature(bytes32 _key, uint8 _v, bytes32 _r, bytes32 _s, uint8 _revocationReasonId) external accessible {
require(ecrecover(_key, _v, _r, _s) != 0x0, "TrueProfileStorage: Signature does not resolve to valid address");
Signature memory tempSignature = Signature({
v: _v,
r: _r,
s: _s,
revocationReasonId: _revocationReasonId,
isValue: true
});
signatureStorage[_key] = tempSignature;
}
function deleteSignature(bytes32 _key) external accessible {
require(signatureStorage[_key].isValue, "TrueProfileStorage: Signature to delete was not found");
Signature memory tempSignature = Signature({
v: 0,
r: bytes32(0),
s: bytes32(0),
revocationReasonId: 0,
isValue: false
});
signatureStorage[_key] = tempSignature;
}
/**** Get Methods for additional storage ****/
function getAddress(bytes32 _key) external view returns (address) {
return addressStorage[_key];
}
function getUint(bytes32 _key) external view returns (uint) {
return uIntStorage[_key];
}
function getString(bytes32 _key) external view returns (string) {
return stringStorage[_key];
}
function getBytes(bytes32 _key) external view returns (bytes) {
return bytesStorage[_key];
}
function getBool(bytes32 _key) external view returns (bool) {
return boolStorage[_key];
}
function getInt(bytes32 _key) external view returns (int) {
return intStorage[_key];
}
/**** Set Methods for additional storage ****/
function setAddress(bytes32 _key, address _value) external accessible {
addressStorage[_key] = _value;
}
function setUint(bytes32 _key, uint _value) external accessible {
uIntStorage[_key] = _value;
}
function setString(bytes32 _key, string _value) external accessible {
stringStorage[_key] = _value;
}
function setBytes(bytes32 _key, bytes _value) external accessible {
bytesStorage[_key] = _value;
}
function setBool(bytes32 _key, bool _value) external accessible {
boolStorage[_key] = _value;
}
function setInt(bytes32 _key, int _value) external accessible {
intStorage[_key] = _value;
}
/**** Delete Methods for additional storage ****/
function deleteAddress(bytes32 _key) external accessible {
delete addressStorage[_key];
}
function deleteUint(bytes32 _key) external accessible {
delete uIntStorage[_key];
}
function deleteString(bytes32 _key) external accessible {
delete stringStorage[_key];
}
function deleteBytes(bytes32 _key) external accessible {
delete bytesStorage[_key];
}
function deleteBool(bytes32 _key) external accessible {
delete boolStorage[_key];
}
function deleteInt(bytes32 _key) external accessible {
delete intStorage[_key];
}
}
contract TrueProfileLogic is Repaying {
/** Logic Contract (updatable) **
* Copyright 2019
* Florian Weigand
* Synalytix UG, Munich
* florian(at)synalytix.de
*/
TrueProfileStorage trueProfileStorage;
constructor(address _trueProfileStorage) public {
trueProfileStorage = TrueProfileStorage(_trueProfileStorage);
}
/**** Signature logic methods ****/
// add or update TrueProof
// if not present add to array
// if present the old TrueProof can be replaced with a new TrueProof
function addTrueProof(bytes32 _key, uint8 _v, bytes32 _r, bytes32 _s) external repayable accessible {
require(accessAllowed[ecrecover(_key, _v, _r, _s)], "TrueProfileLogic: Signature creator has no access to this contract");
// the certifcate is valid, so set the revokationReasonId to 0
uint8 revokationReasonId = 0;
trueProfileStorage.setSignature(_key, _v, _r, _s, revokationReasonId);
}
// if the TrueProof was issued by error it can be revoked
// for revocation a reason id needs to be given
function revokeTrueProof(bytes32 _key, uint8 _revocationReasonId) external repayable accessible {
require(_revocationReasonId != 0, "TrueProfileLogic: Revocation reason needs to be unequal to 0");
uint8 v;
bytes32 r;
bytes32 s;
uint8 oldRevocationReasonId;
(v, r, s, oldRevocationReasonId) = trueProfileStorage.getSignature(_key);
require(v != 0, "TrueProfileLogic: This TrueProof was already revoked");
// set the revokation reason id to the new value
trueProfileStorage.setSignature(_key, v, r, s, _revocationReasonId);
}
function isValidTrueProof(bytes32 _key) external view returns (bool) {
// needs to be not revoked AND needs to have a valid signature
return this.isValidSignatureTrueProof(_key) && this.isNotRevokedTrueProof(_key);
}
function isValidSignatureTrueProof(bytes32 _key) external view returns (bool) {
uint8 v;
bytes32 r;
bytes32 s;
uint8 revocationReasonId;
(v, r, s, revocationReasonId) = trueProfileStorage.getSignature(_key);
// needs to have a valid signature
return accessAllowed[ecrecover(_key, v, r, s)];
}
function isNotRevokedTrueProof(bytes32 _key) external view returns (bool) {
uint8 v;
bytes32 r;
bytes32 s;
uint8 revocationReasonId;
(v, r, s, revocationReasonId) = trueProfileStorage.getSignature(_key);
// needs to be not revoked
return revocationReasonId == 0;
}
function getSignature(bytes32 _key) external view returns (uint8 v, bytes32 r, bytes32 s, uint8 revocationReasonId) {
return trueProfileStorage.getSignature(_key);
}
function getRevocationReasonId(bytes32 _key) external view returns (uint8) {
uint8 v;
bytes32 r;
bytes32 s;
uint8 revocationReasonId;
(v, r, s, revocationReasonId) = trueProfileStorage.getSignature(_key);
return revocationReasonId;
}
} | if the TrueProof was issued by error it can be revoked for revocation a reason id needs to be given set the revokation reason id to the new value | function revokeTrueProof(bytes32 _key, uint8 _revocationReasonId) external repayable accessible {
require(_revocationReasonId != 0, "TrueProfileLogic: Revocation reason needs to be unequal to 0");
uint8 v;
bytes32 r;
bytes32 s;
uint8 oldRevocationReasonId;
(v, r, s, oldRevocationReasonId) = trueProfileStorage.getSignature(_key);
require(v != 0, "TrueProfileLogic: This TrueProof was already revoked");
trueProfileStorage.setSignature(_key, v, r, s, _revocationReasonId);
}
| 2,570,945 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.9;
import "../whitelist/WhitelistRolesWithAirnode.sol";
import "./RequesterAuthorizer.sol";
import "./interfaces/IRequesterAuthorizerWithAirnode.sol";
/// @title Authorizer contract that Airnode operators can use to temporarily or
/// indefinitely whitelist requesters for Airnode–endpoint pairs
contract RequesterAuthorizerWithAirnode is
WhitelistRolesWithAirnode,
RequesterAuthorizer,
IRequesterAuthorizerWithAirnode
{
/// @param _accessControlRegistry AccessControlRegistry contract address
/// @param _adminRoleDescription Admin role description
constructor(
address _accessControlRegistry,
string memory _adminRoleDescription
)
WhitelistRolesWithAirnode(_accessControlRegistry, _adminRoleDescription)
{}
/// @notice Extends the expiration of the temporary whitelist of
/// `requester` for the `airnode`–`endpointId` pair if the sender has the
/// whitelist expiration extender role
/// @param airnode Airnode address
/// @param endpointId Endpoint ID
/// @param requester Requester address
/// @param expirationTimestamp Timestamp at which the temporary whitelist
/// will expire
function extendWhitelistExpiration(
address airnode,
bytes32 endpointId,
address requester,
uint64 expirationTimestamp
) external override {
require(
hasWhitelistExpirationExtenderRoleOrIsAirnode(airnode, msg.sender),
"Cannot extend expiration"
);
_extendWhitelistExpirationAndEmit(
airnode,
endpointId,
requester,
expirationTimestamp
);
}
/// @notice Sets the expiration of the temporary whitelist of `requester`
/// for the `airnode`–`endpointId` pair if the sender has the whitelist
/// expiration setter role
/// @dev Unlike `extendWhitelistExpiration()`, this can hasten expiration
/// @param airnode Airnode address
/// @param endpointId Endpoint ID
/// @param requester Requester address
/// @param expirationTimestamp Timestamp at which the temporary whitelist
/// will expire
function setWhitelistExpiration(
address airnode,
bytes32 endpointId,
address requester,
uint64 expirationTimestamp
) external override {
require(
hasWhitelistExpirationSetterRoleOrIsAirnode(airnode, msg.sender),
"Cannot set expiration"
);
_setWhitelistExpirationAndEmit(
airnode,
endpointId,
requester,
expirationTimestamp
);
}
/// @notice Sets the indefinite whitelist status of `requester` for the
/// `airnode`–`endpointId` pair if the sender has the indefinite
/// whitelister role
/// @param airnode Airnode address
/// @param endpointId Endpoint ID
/// @param requester Requester address
/// @param status Indefinite whitelist status
function setIndefiniteWhitelistStatus(
address airnode,
bytes32 endpointId,
address requester,
bool status
) external override {
require(
hasIndefiniteWhitelisterRoleOrIsAirnode(airnode, msg.sender),
"Cannot set indefinite status"
);
_setIndefiniteWhitelistStatusAndEmit(
airnode,
endpointId,
requester,
status
);
}
/// @notice Revokes the indefinite whitelist status granted by a specific
/// account that no longer has the indefinite whitelister role
/// @param airnode Airnode address
/// @param endpointId Endpoint ID
/// @param requester Requester address
/// @param setter Setter of the indefinite whitelist status
function revokeIndefiniteWhitelistStatus(
address airnode,
bytes32 endpointId,
address requester,
address setter
) external override {
require(
!hasIndefiniteWhitelisterRoleOrIsAirnode(airnode, setter),
"setter can set indefinite status"
);
_revokeIndefiniteWhitelistStatusAndEmit(
airnode,
endpointId,
requester,
setter
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./WhitelistRoles.sol";
import "../access-control-registry/AccessControlRegistryAdminned.sol";
import "./interfaces/IWhitelistRolesWithAirnode.sol";
import "../access-control-registry/interfaces/IAccessControlRegistry.sol";
/// @title Contract to be inherited by Whitelist contracts that will use
/// roles where each individual Airnode address is its own manager
contract WhitelistRolesWithAirnode is
WhitelistRoles,
AccessControlRegistryAdminned,
IWhitelistRolesWithAirnode
{
/// @param _accessControlRegistry AccessControlRegistry contract address
/// @param _adminRoleDescription Admin role description
constructor(
address _accessControlRegistry,
string memory _adminRoleDescription
)
AccessControlRegistryAdminned(
_accessControlRegistry,
_adminRoleDescription
)
{}
/// @notice Derives the admin role for the Airnode
/// @param airnode Airnode address
/// @return adminRole Admin role
function deriveAdminRole(address airnode)
external
view
override
returns (bytes32 adminRole)
{
adminRole = _deriveAdminRole(airnode);
}
/// @notice Derives the whitelist expiration extender role for the Airnode
/// @param airnode Airnode address
/// @return whitelistExpirationExtenderRole Whitelist expiration extender
/// role
function deriveWhitelistExpirationExtenderRole(address airnode)
public
view
override
returns (bytes32 whitelistExpirationExtenderRole)
{
whitelistExpirationExtenderRole = _deriveRole(
_deriveAdminRole(airnode),
WHITELIST_EXPIRATION_EXTENDER_ROLE_DESCRIPTION_HASH
);
}
/// @notice Derives the whitelist expiration setter role for the Airnode
/// @param airnode Airnode address
/// @return whitelistExpirationSetterRole Whitelist expiration setter role
function deriveWhitelistExpirationSetterRole(address airnode)
public
view
override
returns (bytes32 whitelistExpirationSetterRole)
{
whitelistExpirationSetterRole = _deriveRole(
_deriveAdminRole(airnode),
WHITELIST_EXPIRATION_SETTER_ROLE_DESCRIPTION_HASH
);
}
/// @notice Derives the indefinite whitelister role for the Airnode
/// @param airnode Airnode address
/// @return indefiniteWhitelisterRole Indefinite whitelister role
function deriveIndefiniteWhitelisterRole(address airnode)
public
view
override
returns (bytes32 indefiniteWhitelisterRole)
{
indefiniteWhitelisterRole = _deriveRole(
_deriveAdminRole(airnode),
INDEFINITE_WHITELISTER_ROLE_DESCRIPTION_HASH
);
}
/// @dev Returns if the account has the whitelist expiration extender role
/// or is the Airnode address
/// @param airnode Airnode address
/// @param account Account address
/// @return If the account has the whitelist extender role or is the
/// Airnode address
function hasWhitelistExpirationExtenderRoleOrIsAirnode(
address airnode,
address account
) internal view returns (bool) {
return
airnode == account ||
IAccessControlRegistry(accessControlRegistry).hasRole(
deriveWhitelistExpirationExtenderRole(airnode),
account
);
}
/// @dev Returns if the account has the whitelist expriation setter role or
/// is the Airnode address
/// @param airnode Airnode address
/// @param account Account address
/// @return If the account has the whitelist setter role or is the Airnode
/// address
function hasWhitelistExpirationSetterRoleOrIsAirnode(
address airnode,
address account
) internal view returns (bool) {
return
airnode == account ||
IAccessControlRegistry(accessControlRegistry).hasRole(
deriveWhitelistExpirationSetterRole(airnode),
account
);
}
/// @dev Returns if the account has the indefinite whitelister role or is the
/// Airnode address
/// @param airnode Airnode address
/// @param account Account address
/// @return If the account has the indefinite whitelister role or is the
/// Airnode addrss
function hasIndefiniteWhitelisterRoleOrIsAirnode(
address airnode,
address account
) internal view returns (bool) {
return
airnode == account ||
IAccessControlRegistry(accessControlRegistry).hasRole(
deriveIndefiniteWhitelisterRole(airnode),
account
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../whitelist/Whitelist.sol";
import "./interfaces/IRequesterAuthorizer.sol";
/// @title Abstract contract to be inherited by Authorizer contracts that
/// temporarily or permanently whitelist requesters for Airnode–endpoint pairs
abstract contract RequesterAuthorizer is Whitelist, IRequesterAuthorizer {
/// @notice Extends the expiration of the temporary whitelist of
/// `requester` for the `airnode`–`endpointId` pair and emits an event
/// @param airnode Airnode address
/// @param endpointId Endpoint ID (allowed to be `bytes32(0)`)
/// @param requester Requester address
/// @param expirationTimestamp Timestamp at which the temporary whitelist
/// will expire
function _extendWhitelistExpirationAndEmit(
address airnode,
bytes32 endpointId,
address requester,
uint64 expirationTimestamp
) internal {
require(airnode != address(0), "Airnode address zero");
require(requester != address(0), "Requester address zero");
_extendWhitelistExpiration(
deriveServiceId(airnode, endpointId),
requester,
expirationTimestamp
);
emit ExtendedWhitelistExpiration(
airnode,
endpointId,
requester,
msg.sender,
expirationTimestamp
);
}
/// @notice Sets the expiration of the temporary whitelist of `requester`
/// for the `airnode`–`endpointId` pair and emits an event
/// @dev Unlike `_extendWhitelistExpiration()`, this can hasten expiration
/// @param airnode Airnode address
/// @param endpointId Endpoint ID (allowed to be `bytes32(0)`)
/// @param requester Requester address
/// @param expirationTimestamp Timestamp at which the temporary whitelist
/// will expire
function _setWhitelistExpirationAndEmit(
address airnode,
bytes32 endpointId,
address requester,
uint64 expirationTimestamp
) internal {
require(airnode != address(0), "Airnode address zero");
require(requester != address(0), "Requester address zero");
_setWhitelistExpiration(
deriveServiceId(airnode, endpointId),
requester,
expirationTimestamp
);
emit SetWhitelistExpiration(
airnode,
endpointId,
requester,
msg.sender,
expirationTimestamp
);
}
/// @notice Sets the indefinite whitelist status of `requester` for the
/// `airnode`–`endpointId` pair and emits an event
/// @dev Emits the event even if it does not change the state.
/// @param airnode Airnode address
/// @param endpointId Endpoint ID (allowed to be `bytes32(0)`)
/// @param requester Requester address
/// @param status Indefinite whitelist status
function _setIndefiniteWhitelistStatusAndEmit(
address airnode,
bytes32 endpointId,
address requester,
bool status
) internal {
require(airnode != address(0), "Airnode address zero");
require(requester != address(0), "Requester address zero");
uint192 indefiniteWhitelistCount = _setIndefiniteWhitelistStatus(
deriveServiceId(airnode, endpointId),
requester,
status
);
emit SetIndefiniteWhitelistStatus(
airnode,
endpointId,
requester,
msg.sender,
status,
indefiniteWhitelistCount
);
}
/// @notice Revokes the indefinite whitelist status granted to `requester`
/// for the `airnode`–`endpointId` pair by a specific account and emits an
/// event
/// @dev Only emits the event if it changes the state
/// @param airnode Airnode address
/// @param endpointId Endpoint ID (allowed to be `bytes32(0)`)
/// @param requester Requester address
/// @param setter Setter of the indefinite whitelist status
function _revokeIndefiniteWhitelistStatusAndEmit(
address airnode,
bytes32 endpointId,
address requester,
address setter
) internal {
require(airnode != address(0), "Airnode address zero");
require(requester != address(0), "Requester address zero");
require(setter != address(0), "Setter address zero");
(
bool revoked,
uint192 indefiniteWhitelistCount
) = _revokeIndefiniteWhitelistStatus(
deriveServiceId(airnode, endpointId),
requester,
setter
);
if (revoked) {
emit RevokedIndefiniteWhitelistStatus(
airnode,
endpointId,
requester,
setter,
msg.sender,
indefiniteWhitelistCount
);
}
}
/// @notice Verifies the authorization status of a request
/// @param airnode Airnode address
/// @param endpointId Endpoint ID
/// @param requester Requester address
/// @return Authorization status of the request
function isAuthorized(
address airnode,
bytes32 endpointId,
address requester
) external view override returns (bool) {
return
userIsWhitelisted(deriveServiceId(airnode, endpointId), requester);
}
/// @notice Verifies the authorization status of a request
/// @dev This method has redundant arguments because V0 authorizer
/// contracts have to have the same interface and potential authorizer
/// contracts may require to access the arguments that are redundant here
/// @param requestId Request ID
/// @param airnode Airnode address
/// @param endpointId Endpoint ID
/// @param sponsor Sponsor address
/// @param requester Requester address
/// @return Authorization status of the request
function isAuthorizedV0(
bytes32 requestId, // solhint-disable-line no-unused-vars
address airnode,
bytes32 endpointId,
address sponsor, // solhint-disable-line no-unused-vars
address requester
) external view override returns (bool) {
return
userIsWhitelisted(deriveServiceId(airnode, endpointId), requester);
}
/// @notice Returns the whitelist status of `requester` for the
/// `airnode`–`endpointId` pair
/// @param airnode Airnode address
/// @param endpointId Endpoint ID
/// @param requester Requester address
/// @return expirationTimestamp Timestamp at which the temporary whitelist
/// will expire
/// @return indefiniteWhitelistCount Number of times `requester` was
/// whitelisted indefinitely for the `airnode`–`endpointId` pair
function airnodeToEndpointIdToRequesterToWhitelistStatus(
address airnode,
bytes32 endpointId,
address requester
)
external
view
override
returns (uint64 expirationTimestamp, uint192 indefiniteWhitelistCount)
{
WhitelistStatus
storage whitelistStatus = serviceIdToUserToWhitelistStatus[
deriveServiceId(airnode, endpointId)
][requester];
expirationTimestamp = whitelistStatus.expirationTimestamp;
indefiniteWhitelistCount = whitelistStatus.indefiniteWhitelistCount;
}
/// @notice Returns if an account has indefinitely whitelisted `requester`
/// for the `airnode`–`endpointId` pair
/// @param airnode Airnode address
/// @param endpointId Endpoint ID
/// @param requester Requester address
/// @param setter Address of the account that has potentially whitelisted
/// `requester` for the `airnode`–`endpointId` pair indefinitely
/// @return indefiniteWhitelistStatus If `setter` has indefinitely
/// whitelisted `requester` for the `airnode`–`endpointId` pair
function airnodeToEndpointIdToRequesterToSetterToIndefiniteWhitelistStatus(
address airnode,
bytes32 endpointId,
address requester,
address setter
) external view override returns (bool indefiniteWhitelistStatus) {
indefiniteWhitelistStatus = serviceIdToUserToSetterToIndefiniteWhitelistStatus[
deriveServiceId(airnode, endpointId)
][requester][setter];
}
/// @notice Called privately to derive a service ID out of the Airnode
/// address and the endpoint ID
/// @dev This is done to re-use the more general Whitelist contract for
/// the specific case of Airnode–endpoint pairs
/// @param airnode Airnode address
/// @param endpointId Endpoint ID
/// @return serviceId Service ID
function deriveServiceId(address airnode, bytes32 endpointId)
private
pure
returns (bytes32 serviceId)
{
serviceId = keccak256(abi.encodePacked(airnode, endpointId));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../whitelist/interfaces/IWhitelistRolesWithAirnode.sol";
import "./IRequesterAuthorizer.sol";
interface IRequesterAuthorizerWithAirnode is
IWhitelistRolesWithAirnode,
IRequesterAuthorizer
{}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./interfaces/IWhitelistRoles.sol";
/// @title Contract to be inherited by Whitelist contracts that will use
/// generic AccessControlRegistry roles
contract WhitelistRoles is IWhitelistRoles {
// There are four roles implemented in this contract:
// Root
// └── (1) Admin (can grant and revoke the roles below)
// ├── (2) Whitelist expiration extender
// ├── (3) Whitelist expiration setter
// └── (4) Indefinite whitelister
// Their IDs are derived from the descriptions below. Refer to
// AccessControlRegistry for more information.
// To clarify, the root role of the manager is the admin of (1), while (1)
// is the admin of (2), (3) and (4). So (1) is more of a "contract admin",
// while the `adminRole` used in AccessControl and AccessControlRegistry
// refers to a more general adminship relationship between roles.
/// @notice Whitelist expiration extender role description
string
public constant
override WHITELIST_EXPIRATION_EXTENDER_ROLE_DESCRIPTION =
"Whitelist expiration extender";
/// @notice Whitelist expiration setter role description
string
public constant
override WHITELIST_EXPIRATION_SETTER_ROLE_DESCRIPTION =
"Whitelist expiration setter";
/// @notice Indefinite whitelister role description
string public constant override INDEFINITE_WHITELISTER_ROLE_DESCRIPTION =
"Indefinite whitelister";
bytes32
internal constant WHITELIST_EXPIRATION_EXTENDER_ROLE_DESCRIPTION_HASH =
keccak256(
abi.encodePacked(WHITELIST_EXPIRATION_EXTENDER_ROLE_DESCRIPTION)
);
bytes32
internal constant WHITELIST_EXPIRATION_SETTER_ROLE_DESCRIPTION_HASH =
keccak256(
abi.encodePacked(WHITELIST_EXPIRATION_SETTER_ROLE_DESCRIPTION)
);
bytes32 internal constant INDEFINITE_WHITELISTER_ROLE_DESCRIPTION_HASH =
keccak256(abi.encodePacked(INDEFINITE_WHITELISTER_ROLE_DESCRIPTION));
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/utils/Multicall.sol";
import "./RoleDeriver.sol";
import "./AccessControlRegistryUser.sol";
import "./interfaces/IAccessControlRegistryAdminned.sol";
/// @title Contract to be inherited by contracts whose adminship functionality
/// will be implemented using AccessControlRegistry
contract AccessControlRegistryAdminned is
Multicall,
RoleDeriver,
AccessControlRegistryUser,
IAccessControlRegistryAdminned
{
/// @notice Admin role description
string public override adminRoleDescription;
bytes32 internal immutable adminRoleDescriptionHash;
/// @dev Contracts deployed with the same admin role descriptions will have
/// the same roles, meaning that granting an account a role will authorize
/// it in multiple contracts. Unless you want your deployed contract to
/// share the role configuration of another contract, use a unique admin
/// role description.
/// @param _accessControlRegistry AccessControlRegistry contract address
/// @param _adminRoleDescription Admin role description
constructor(
address _accessControlRegistry,
string memory _adminRoleDescription
) AccessControlRegistryUser(_accessControlRegistry) {
require(
bytes(_adminRoleDescription).length > 0,
"Admin role description empty"
);
adminRoleDescription = _adminRoleDescription;
adminRoleDescriptionHash = keccak256(
abi.encodePacked(_adminRoleDescription)
);
}
/// @notice Derives the admin role for the specific manager address
/// @param manager Manager address
/// @return adminRole Admin role
function _deriveAdminRole(address manager)
internal
view
returns (bytes32 adminRole)
{
adminRole = _deriveRole(
_deriveRootRole(manager),
adminRoleDescriptionHash
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IWhitelistRoles.sol";
import "../../access-control-registry/interfaces/IAccessControlRegistryAdminned.sol";
interface IWhitelistRolesWithAirnode is
IWhitelistRoles,
IAccessControlRegistryAdminned
{
function deriveAdminRole(address airnode)
external
view
returns (bytes32 role);
function deriveWhitelistExpirationExtenderRole(address airnode)
external
view
returns (bytes32 role);
function deriveWhitelistExpirationSetterRole(address airnode)
external
view
returns (bytes32 role);
function deriveIndefiniteWhitelisterRole(address airnode)
external
view
returns (bytes32 role);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/IAccessControl.sol";
interface IAccessControlRegistry is IAccessControl {
event InitializedManager(bytes32 indexed rootRole, address indexed manager);
event InitializedRole(
bytes32 indexed role,
bytes32 indexed adminRole,
string description,
address sender
);
function initializeManager(address manager) external;
function initializeRoleAndGrantToSender(
bytes32 adminRole,
string calldata description
) external returns (bytes32 role);
function deriveRootRole(address manager)
external
pure
returns (bytes32 rootRole);
function deriveRole(bytes32 adminRole, string calldata description)
external
pure
returns (bytes32 role);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IWhitelistRoles {
// solhint-disable-next-line func-name-mixedcase
function WHITELIST_EXPIRATION_EXTENDER_ROLE_DESCRIPTION()
external
view
returns (string memory);
// solhint-disable-next-line func-name-mixedcase
function WHITELIST_EXPIRATION_SETTER_ROLE_DESCRIPTION()
external
view
returns (string memory);
// solhint-disable-next-line func-name-mixedcase
function INDEFINITE_WHITELISTER_ROLE_DESCRIPTION()
external
view
returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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 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: MIT
pragma solidity ^0.8.0;
/// @title Contract to be inherited by contracts that will derive
/// AccessControlRegistry roles
/// @notice If a contract interfaces with AccessControlRegistry and needs to
/// derive roles, it should inherit this contract instead of re-implementing
/// the logic
contract RoleDeriver {
/// @notice Derives the root role of the manager
/// @param manager Manager address
/// @return rootRole Root role
function _deriveRootRole(address manager)
internal
pure
returns (bytes32 rootRole)
{
rootRole = keccak256(abi.encodePacked(manager));
}
/// @notice Derives the role using its admin role and description
/// @dev This implies that roles adminned by the same role cannot have the
/// same description
/// @param adminRole Admin role
/// @param description Human-readable description of the role
/// @return role Role
function _deriveRole(bytes32 adminRole, string memory description)
internal
pure
returns (bytes32 role)
{
role = _deriveRole(adminRole, keccak256(abi.encodePacked(description)));
}
/// @notice Derives the role using its admin role and description hash
/// @dev This implies that roles adminned by the same role cannot have the
/// same description
/// @param adminRole Admin role
/// @param descriptionHash Hash of the human-readable description of the
/// role
/// @return role Role
function _deriveRole(bytes32 adminRole, bytes32 descriptionHash)
internal
pure
returns (bytes32 role)
{
role = keccak256(abi.encodePacked(adminRole, descriptionHash));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./interfaces/IAccessControlRegistry.sol";
import "./interfaces/IAccessControlRegistryUser.sol";
/// @title Contract to be inherited by contracts that will interact with
/// AccessControlRegistry
contract AccessControlRegistryUser is IAccessControlRegistryUser {
/// @notice AccessControlRegistry contract address
address public immutable override accessControlRegistry;
/// @param _accessControlRegistry AccessControlRegistry contract address
constructor(address _accessControlRegistry) {
require(_accessControlRegistry != address(0), "ACR address zero");
accessControlRegistry = _accessControlRegistry;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IAccessControlRegistryUser.sol";
interface IAccessControlRegistryAdminned is IAccessControlRegistryUser {
function adminRoleDescription() external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IAccessControlRegistryUser {
function accessControlRegistry() external view returns (address);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface 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;
/// @title Contract to be inherited by contracts that need temporary and
/// permanent whitelists for services identified by hashes
/// @notice This contract implements two kinds of whitelisting:
/// (1) Temporary, ends when the expiration timestamp is in the past
/// (2) Indefinite, ends when the indefinite whitelist count is zero
/// Multiple senders can indefinitely whitelist/unwhitelist independently. The
/// user will be considered whitelisted as long as there is at least one active
/// indefinite whitelisting.
/// @dev The interface of this contract is not implemented. It should be
/// inherited and its functions should be exposed with a sort of an
/// authorization scheme.
contract Whitelist {
struct WhitelistStatus {
uint64 expirationTimestamp;
uint192 indefiniteWhitelistCount;
}
mapping(bytes32 => mapping(address => WhitelistStatus))
internal serviceIdToUserToWhitelistStatus;
mapping(bytes32 => mapping(address => mapping(address => bool)))
internal serviceIdToUserToSetterToIndefiniteWhitelistStatus;
/// @notice Extends the expiration of the temporary whitelist of the user
/// for the service
/// @param serviceId Service ID
/// @param user User address
/// @param expirationTimestamp Timestamp at which the temporary whitelist
/// will expire
function _extendWhitelistExpiration(
bytes32 serviceId,
address user,
uint64 expirationTimestamp
) internal {
require(
expirationTimestamp >
serviceIdToUserToWhitelistStatus[serviceId][user]
.expirationTimestamp,
"Does not extend expiration"
);
serviceIdToUserToWhitelistStatus[serviceId][user]
.expirationTimestamp = expirationTimestamp;
}
/// @notice Sets the expiration of the temporary whitelist of the user for
/// the service
/// @dev Unlike `extendWhitelistExpiration()`, this can hasten expiration
/// @param serviceId Service ID
/// @param user User address
/// @param expirationTimestamp Timestamp at which the temporary whitelist
/// will expire
function _setWhitelistExpiration(
bytes32 serviceId,
address user,
uint64 expirationTimestamp
) internal {
serviceIdToUserToWhitelistStatus[serviceId][user]
.expirationTimestamp = expirationTimestamp;
}
/// @notice Sets the indefinite whitelist status of the user for the
/// service
/// @dev As long as at least there is at least one account that has set the
/// indefinite whitelist status of the user for the service as true, the
/// user will be considered whitelisted
/// @param serviceId Service ID
/// @param user User address
/// @param status Indefinite whitelist status
function _setIndefiniteWhitelistStatus(
bytes32 serviceId,
address user,
bool status
) internal returns (uint192 indefiniteWhitelistCount) {
indefiniteWhitelistCount = serviceIdToUserToWhitelistStatus[serviceId][
user
].indefiniteWhitelistCount;
if (
status &&
!serviceIdToUserToSetterToIndefiniteWhitelistStatus[serviceId][
user
][msg.sender]
) {
serviceIdToUserToSetterToIndefiniteWhitelistStatus[serviceId][user][
msg.sender
] = true;
indefiniteWhitelistCount++;
serviceIdToUserToWhitelistStatus[serviceId][user]
.indefiniteWhitelistCount = indefiniteWhitelistCount;
} else if (
!status &&
serviceIdToUserToSetterToIndefiniteWhitelistStatus[serviceId][user][
msg.sender
]
) {
serviceIdToUserToSetterToIndefiniteWhitelistStatus[serviceId][user][
msg.sender
] = false;
indefiniteWhitelistCount--;
serviceIdToUserToWhitelistStatus[serviceId][user]
.indefiniteWhitelistCount = indefiniteWhitelistCount;
}
}
/// @notice Revokes the indefinite whitelist status granted to the user for
/// the service by a specific account
/// @param serviceId Service ID
/// @param user User address
/// @param setter Setter of the indefinite whitelist status
function _revokeIndefiniteWhitelistStatus(
bytes32 serviceId,
address user,
address setter
) internal returns (bool revoked, uint192 indefiniteWhitelistCount) {
indefiniteWhitelistCount = serviceIdToUserToWhitelistStatus[serviceId][
user
].indefiniteWhitelistCount;
if (
serviceIdToUserToSetterToIndefiniteWhitelistStatus[serviceId][user][
setter
]
) {
serviceIdToUserToSetterToIndefiniteWhitelistStatus[serviceId][user][
setter
] = false;
indefiniteWhitelistCount--;
serviceIdToUserToWhitelistStatus[serviceId][user]
.indefiniteWhitelistCount = indefiniteWhitelistCount;
revoked = true;
}
}
/// @notice Returns if the user is whitelised to use the service
/// @param serviceId Service ID
/// @param user User address
/// @return isWhitelisted If the user is whitelisted
function userIsWhitelisted(bytes32 serviceId, address user)
internal
view
returns (bool isWhitelisted)
{
WhitelistStatus
storage whitelistStatus = serviceIdToUserToWhitelistStatus[
serviceId
][user];
return
whitelistStatus.indefiniteWhitelistCount > 0 ||
whitelistStatus.expirationTimestamp > block.timestamp;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IAuthorizerV0.sol";
interface IRequesterAuthorizer is IAuthorizerV0 {
event ExtendedWhitelistExpiration(
address indexed airnode,
bytes32 endpointId,
address indexed requester,
address indexed sender,
uint256 expiration
);
event SetWhitelistExpiration(
address indexed airnode,
bytes32 endpointId,
address indexed requester,
address indexed sender,
uint256 expiration
);
event SetIndefiniteWhitelistStatus(
address indexed airnode,
bytes32 endpointId,
address indexed requester,
address indexed sender,
bool status,
uint192 indefiniteWhitelistCount
);
event RevokedIndefiniteWhitelistStatus(
address indexed airnode,
bytes32 endpointId,
address indexed requester,
address indexed setter,
address sender,
uint192 indefiniteWhitelistCount
);
function extendWhitelistExpiration(
address airnode,
bytes32 endpointId,
address requester,
uint64 expirationTimestamp
) external;
function setWhitelistExpiration(
address airnode,
bytes32 endpointId,
address requester,
uint64 expirationTimestamp
) external;
function setIndefiniteWhitelistStatus(
address airnode,
bytes32 endpointId,
address requester,
bool status
) external;
function revokeIndefiniteWhitelistStatus(
address airnode,
bytes32 endpointId,
address requester,
address setter
) external;
function airnodeToEndpointIdToRequesterToWhitelistStatus(
address airnode,
bytes32 endpointId,
address requester
)
external
view
returns (uint64 expirationTimestamp, uint192 indefiniteWhitelistCount);
function airnodeToEndpointIdToRequesterToSetterToIndefiniteWhitelistStatus(
address airnode,
bytes32 endpointId,
address requester,
address setter
) external view returns (bool indefiniteWhitelistStatus);
function isAuthorized(
address airnode,
bytes32 endpointId,
address requester
) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IAuthorizerV0 {
function isAuthorizedV0(
bytes32 requestId,
address airnode,
bytes32 endpointId,
address sponsor,
address requester
) external view returns (bool);
} | Sets the indefinite whitelist status of `requester` for the `airnode`–`endpointId` pair and emits an event Emits the event even if it does not change the state. airnode Airnode address endpointId Endpoint ID (allowed to be `bytes32(0)`) requester Requester address status Indefinite whitelist status | function _setIndefiniteWhitelistStatusAndEmit(
address airnode,
bytes32 endpointId,
address requester,
bool status
) internal {
require(airnode != address(0), "Airnode address zero");
require(requester != address(0), "Requester address zero");
uint192 indefiniteWhitelistCount = _setIndefiniteWhitelistStatus(
deriveServiceId(airnode, endpointId),
requester,
status
);
emit SetIndefiniteWhitelistStatus(
airnode,
endpointId,
requester,
msg.sender,
status,
indefiniteWhitelistCount
);
}
| 1,198,332 |
// SPDX-License-Identifier: MIT
// Sources flattened with hardhat v2.0.11 https://hardhat.org
// File @openzeppelin/contracts/token/ERC20/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File @openzeppelin/contracts/utils/[email protected]
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);
}
}
}
}
// File @openzeppelin/contracts/token/ERC20/utils/[email protected]
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'
// 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");
}
}
}
// File @openzeppelin/contracts/utils/math/[email protected]
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;
}
}
}
// File @uniswap/v2-core/contracts/interfaces/[email protected]
pragma solidity >=0.5.0;
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
// File @uniswap/v2-periphery/contracts/interfaces/[email protected]
pragma solidity >=0.6.2;
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
// File @uniswap/v2-periphery/contracts/interfaces/[email protected]
pragma solidity >=0.6.2;
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
// File contracts/interfaces/ILiquidityProvider.sol
pragma solidity >=0.6.12 <0.9.0;
interface ILiquidityProvider {
function apis(uint256) external view returns(address, address, address);
function addExchange(IUniswapV2Router02) external;
function addLiquidityETH(
address,
address,
uint256,
uint256,
uint256,
uint256,
uint256
) external payable returns (uint256);
function addLiquidityETHByPair(
IUniswapV2Pair,
address,
uint256,
uint256,
uint256,
uint256,
uint256
) external payable returns (uint256);
function addLiquidity(
address,
address,
uint256,
uint256,
uint256,
uint256,
address,
uint256,
uint256
) external payable returns (uint256);
function addLiquidityByPair(
IUniswapV2Pair,
uint256,
uint256,
uint256,
uint256,
address,
uint256,
uint256
) external payable returns (uint256);
function removeLiquidityETH(
address,
uint256,
uint256,
uint256,
uint256,
address,
uint256,
uint256,
uint8
) external returns (uint256[3] memory);
function removeLiquidityETHByPair(
IUniswapV2Pair,
uint256,
uint256,
uint256,
uint256,
address,
uint256,
uint256,
uint8
) external returns (uint256[3] memory);
function removeLiquidityETHWithPermit(
address,
uint256,
uint256,
uint256,
uint256,
address,
uint256,
uint256,
uint8,
uint8,
bytes32,
bytes32
) external returns (uint256[3] memory);
function removeLiquidity(
address,
address,
uint256,
uint256[2] memory,
uint256[2] memory,
address,
uint256,
uint256,
uint8
) external returns (uint256[3] memory);
function removeLiquidityByPair(
IUniswapV2Pair,
uint256,
uint256[2] memory,
uint256[2] memory,
address,
uint256,
uint256,
uint8
) external returns (uint256[3] memory);
function removeLiquidityWithPermit(
address,
address,
uint256,
uint256[2] memory,
uint256[2] memory,
address,
uint256,
uint256,
uint8,
uint8,
bytes32,
bytes32
) external returns (uint256[3] memory);
}
// File hardhat/[email protected]
pragma solidity >= 0.4.22 <0.9.0;
library console {
address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67);
function _sendLogPayload(bytes memory payload) private view {
uint256 payloadLength = payload.length;
address consoleAddress = CONSOLE_ADDRESS;
assembly {
let payloadStart := add(payload, 32)
let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0)
}
}
function log() internal view {
_sendLogPayload(abi.encodeWithSignature("log()"));
}
function logInt(int p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(int)", p0));
}
function logUint(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function logString(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function logBool(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function logAddress(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function logBytes(bytes memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes)", p0));
}
function logBytes1(bytes1 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0));
}
function logBytes2(bytes2 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0));
}
function logBytes3(bytes3 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0));
}
function logBytes4(bytes4 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0));
}
function logBytes5(bytes5 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0));
}
function logBytes6(bytes6 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0));
}
function logBytes7(bytes7 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0));
}
function logBytes8(bytes8 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0));
}
function logBytes9(bytes9 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0));
}
function logBytes10(bytes10 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0));
}
function logBytes11(bytes11 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0));
}
function logBytes12(bytes12 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0));
}
function logBytes13(bytes13 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0));
}
function logBytes14(bytes14 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0));
}
function logBytes15(bytes15 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0));
}
function logBytes16(bytes16 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0));
}
function logBytes17(bytes17 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0));
}
function logBytes18(bytes18 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0));
}
function logBytes19(bytes19 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0));
}
function logBytes20(bytes20 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0));
}
function logBytes21(bytes21 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0));
}
function logBytes22(bytes22 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0));
}
function logBytes23(bytes23 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0));
}
function logBytes24(bytes24 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0));
}
function logBytes25(bytes25 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0));
}
function logBytes26(bytes26 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0));
}
function logBytes27(bytes27 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0));
}
function logBytes28(bytes28 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0));
}
function logBytes29(bytes29 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0));
}
function logBytes30(bytes30 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0));
}
function logBytes31(bytes31 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0));
}
function logBytes32(bytes32 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0));
}
function log(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function log(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function log(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function log(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function log(uint p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1));
}
function log(uint p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1));
}
function log(uint p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1));
}
function log(uint p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1));
}
function log(string memory p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1));
}
function log(string memory p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1));
}
function log(string memory p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1));
}
function log(string memory p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1));
}
function log(bool p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1));
}
function log(bool p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1));
}
function log(bool p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1));
}
function log(bool p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1));
}
function log(address p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1));
}
function log(address p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1));
}
function log(address p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1));
}
function log(address p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1));
}
function log(uint p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2));
}
function log(uint p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2));
}
function log(uint p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2));
}
function log(uint p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2));
}
function log(uint p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2));
}
function log(uint p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2));
}
function log(uint p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2));
}
function log(uint p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2));
}
function log(uint p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2));
}
function log(uint p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2));
}
function log(uint p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2));
}
function log(uint p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2));
}
function log(uint p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2));
}
function log(uint p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2));
}
function log(uint p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2));
}
function log(uint p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2));
}
function log(string memory p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2));
}
function log(string memory p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2));
}
function log(string memory p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2));
}
function log(string memory p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2));
}
function log(string memory p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2));
}
function log(string memory p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2));
}
function log(string memory p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2));
}
function log(string memory p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2));
}
function log(string memory p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2));
}
function log(string memory p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2));
}
function log(string memory p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2));
}
function log(string memory p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2));
}
function log(string memory p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2));
}
function log(string memory p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2));
}
function log(string memory p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2));
}
function log(string memory p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2));
}
function log(bool p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2));
}
function log(bool p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2));
}
function log(bool p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2));
}
function log(bool p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2));
}
function log(bool p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2));
}
function log(bool p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2));
}
function log(bool p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2));
}
function log(bool p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2));
}
function log(bool p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2));
}
function log(bool p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2));
}
function log(bool p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2));
}
function log(bool p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2));
}
function log(bool p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2));
}
function log(bool p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2));
}
function log(bool p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2));
}
function log(bool p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2));
}
function log(address p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2));
}
function log(address p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2));
}
function log(address p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2));
}
function log(address p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2));
}
function log(address p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2));
}
function log(address p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2));
}
function log(address p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2));
}
function log(address p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2));
}
function log(address p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2));
}
function log(address p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2));
}
function log(address p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2));
}
function log(address p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2));
}
function log(address p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2));
}
function log(address p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2));
}
function log(address p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2));
}
function log(address p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2));
}
function log(uint p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3));
}
}
// File @openzeppelin/contracts-upgradeable/proxy/utils/[email protected]
// 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;
}
}
}
// File @openzeppelin/contracts-upgradeable/utils/[email protected]
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 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;
}
// File @openzeppelin/contracts-upgradeable/access/[email protected]
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 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;
}
// File @openzeppelin/contracts-upgradeable/security/[email protected]
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 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;
}
// File contracts/eTacoChef.sol
pragma solidity 0.8.0;
interface IMigrator {
// Perform LP token migration from legacy UniswapV2 to TacoSwap.
// Take the current LP token address and return the new LP token address.
// Migrator should have full access to the caller's LP token.
// Return the new LP token address.
//
// XXX Migrator must have allowance access to UniswapV2 LP tokens.
// TacoSwap must mint EXACTLY the same amount of TacoSwap LP tokens or
// else something bad will happen. Traditional UniswapV2 does not
// do that so be careful!
function migrateLP(IERC20 token) external returns (IERC20);
}
/**
* @title eTacoChef is the master of eTaco
* @notice eTacoChef contract:
* - Users can:
* # Deposit
* # Harvest
* # Withdraw
* # SpeedStake
*/
contract eTacoChef is OwnableUpgradeable, ReentrancyGuardUpgradeable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
/**
* @notice Info of each user
* @param amount: How many LP tokens the user has provided
* @param rewardDebt: Reward debt. See explanation below
* @dev Any point in time, the amount of eTacos entitled to a user but is pending to be distributed is:
* pending reward = (user.amount * pool.accRewardPerShare) - user.rewardDebt
* Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
* 1. The pool's `accRewardPerShare` (and `lastRewardBlock`) gets updated.
* 2. User receives the pending reward sent to his/her address.
* 3. User's `amount` gets updated.
* 4. User's `rewardDebt` gets updated.
*/
struct UserInfo {
uint256 amount;
uint256 rewardDebt;
}
/**
* @notice Info of each pool
* @param lpToken: Address of LP token contract
* @param allocPoint: How many allocation points assigned to this pool. eTacos to distribute per block
* @param lastRewardBlock: Last block number that eTacos distribution occurs
* @param accRewardPerShare: Accumulated eTacos per share, times 1e12. See below
*/
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. eTacos to distribute per block.
uint256 lastRewardBlock; // Last block number that eTacos distribution occurs.
uint256 accRewardPerShare; // Accumulated eTacos per share, times 1e12. See below.
}
/// The eTaco TOKEN!
IERC20 public etaco;
/// Dev address.
address public devaddr;
/// The Liquidity Provider
ILiquidityProvider public provider;
/// Block number when bonus eTaco period ends.
uint256 public endBlock;
/// eTaco tokens created in first block.
uint256 public rewardPerBlock;
/// The migrator contract. Can only be set through governance (owner).
IMigrator public migrator;
/// Info of each pool.
PoolInfo[] public poolInfo;
/// Info of each user that stakes LP tokens.
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
mapping(address => bool) public isPoolExist;
/// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint;
/// The block number when eTaco mining starts.
uint256 public startBlock;
uint256 private _apiID;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Harvest(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event Provider(address oldProvider, address newProvider);
event Api(uint256 id);
event Migrator(address migratorAddress);
event EmergencyWithdraw(
address indexed user,
uint256 indexed pid,
uint256 amount
);
modifier poolExists(uint256 _pid) {
require(_pid < poolInfo.length, "Pool does not exist");
_;
}
modifier onlyMigrator() {
require(
msg.sender == address(migrator),
"eTacoChef: Only migrator can call"
);
_;
}
function initialize(
IERC20 _etaco,
uint256 _rewardPerBlock,
uint256 _startBlock
) public initializer {
__Ownable_init();
__ReentrancyGuard_init();
require(address(_etaco) != address(0x0), "eTacoChef::set zero address");
etaco = _etaco;
devaddr = msg.sender;
rewardPerBlock = _rewardPerBlock;
startBlock = _startBlock;
}
/// @return All pools amount
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
/**
* @notice Add a new lp to the pool. Can only be called by the owner
* @param _allocPoint: allocPoint for new pool
* @param _lpToken: address of lpToken for new pool
* @param _withUpdate: if true, update all pools
*/
function add(
uint256 _allocPoint,
IERC20 _lpToken,
bool _withUpdate
) public onlyOwner {
require(
!isPoolExist[address(_lpToken)],
"eTacoChef:: LP token already added"
);
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock
? block.number
: startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(
PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accRewardPerShare: 0
})
);
isPoolExist[address(_lpToken)] = true;
}
/**
* @notice Update the given pool's eTaco allocation point. Can only be called by the owner
*/
function set(
uint256 _pid,
address _lpToken,
uint256 _allocPoint,
bool _withUpdate
) public onlyOwner poolExists(_pid) {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(
_allocPoint
);
poolInfo[_pid].allocPoint = _allocPoint;
poolInfo[_pid].lpToken = IERC20(_lpToken);
}
/**
* @notice Set the migrator contract. Can only be called by the owner
* @param _migrator: migrator contract
*/
function setMigrator(IMigrator _migrator) public onlyOwner {
migrator = _migrator;
emit Migrator(address(_migrator));
}
function setConfigs(
ILiquidityProvider _provider,
uint256 _api,
uint256 _rewardPerBlock,
IERC20 _etaco
) public onlyOwner {
if (address(_provider) != address(0)) {
provider = _provider;
_apiID = _api;
}
if (address(_etaco) != address(0)) {
etaco = _etaco;
}
if (_rewardPerBlock > 0) {
massUpdatePools();
rewardPerBlock = _rewardPerBlock;
}
}
function approveDummies(address _token) external onlyMigrator {
IERC20(_token).safeApprove(
msg.sender,
type(uint256).max
);
}
/**
* @notice Migrate lp token to another lp contract. Can be called by anyone
* @param _pid: ID of pool which message sender wants to migrate
*/
function migrate(uint256 _pid) public onlyOwner {
require(address(migrator) != address(0), "migrate: no migrator");
PoolInfo storage pool = poolInfo[_pid];
IERC20 lpToken = pool.lpToken;
uint256 bal = lpToken.balanceOf(address(this));
lpToken.safeApprove(address(migrator), bal);
IERC20 newLpToken = migrator.migrateLP(lpToken);
require(bal == newLpToken.balanceOf(address(this)), "migrate: bad");
pool.lpToken = newLpToken;
}
/**
* @param _from: block number from which the reward is calculated
* @param _to: block number before which the reward is calculated
* @return Return reward multiplier over the given _from to _to block
*/
function getMultiplier(uint256 _from, uint256 _to)
public
view
returns (uint256)
{
if (_from < startBlock) {
_from = startBlock;
}
return rewardPerBlock.mul(_to.sub(_from));
}
/**
* @notice View function to see pending eTacos on frontend
* @param _pid: pool ID for which reward must be calculated
* @param _user: user address for which reward must be calculated
* @return Return reward for user
*/
function pendingReward(uint256 _pid, address _user)
external
view
poolExists(_pid)
returns (uint256)
{
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accRewardPerShare = pool.accRewardPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(
pool.lastRewardBlock,
block.number
);
uint256 etacoReward = multiplier.mul(pool.allocPoint).div(
totalAllocPoint
);
accRewardPerShare = accRewardPerShare.add(
etacoReward.mul(1e12).div(lpSupply)
);
}
return
user.amount.mul(accRewardPerShare).div(1e12).sub(user.rewardDebt);
}
/**
* @notice Update reward vairables for all pools
*/
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
/**
* @notice Update reward variables of the given pool to be up-to-date
* @param _pid: pool ID for which the reward variables should be updated
*/
function updatePool(uint256 _pid) public poolExists(_pid) {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 etacoReward = multiplier.mul(pool.allocPoint).div(
totalAllocPoint
);
safeETacoTransfer(devaddr, etacoReward.div(10));
pool.accRewardPerShare = pool.accRewardPerShare.add(
etacoReward.mul(1e12).div(lpSupply)
);
pool.lastRewardBlock = block.number;
}
/**
* @notice Deposit LP tokens to eTacoChef for eTaco allocation
* @param _pid: pool ID on which LP tokens should be deposited
* @param _amount: the amount of LP tokens that should be deposited
*/
function deposit(uint256 _pid, uint256 _amount) public poolExists(_pid) {
updatePool(_pid);
poolInfo[_pid].lpToken.safeTransferFrom(
address(msg.sender),
address(this),
_amount
);
_deposit(_pid, _amount);
}
/**
* @notice Function for updating user info
*/
function _deposit(uint256 _pid, uint256 _amount) private {
UserInfo storage user = userInfo[_pid][msg.sender];
harvest(_pid);
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(poolInfo[_pid].accRewardPerShare).div(
1e12
);
emit Deposit(msg.sender, _pid, _amount);
}
/**
* @notice Function which send accumulated eTaco tokens to messege sender
* @param _pid: pool ID from which the accumulated eTaco tokens should be received
*/
function harvest(uint256 _pid) public poolExists(_pid) {
UserInfo storage user = userInfo[_pid][msg.sender];
if (user.amount > 0) {
updatePool(_pid);
uint256 accRewardPerShare = poolInfo[_pid].accRewardPerShare;
uint256 pending = user.amount.mul(accRewardPerShare).div(1e12).sub(
user.rewardDebt
);
safeETacoTransfer(msg.sender, pending);
user.rewardDebt = user.amount.mul(accRewardPerShare).div(1e12);
emit Harvest(msg.sender, _pid, pending);
}
}
/**
* @notice Function which send accumulated eTaco tokens to messege sender from all pools
*/
function harvestAll() public {
uint256 length = poolInfo.length;
for (uint256 i = 0; i < length; i++) {
if (poolInfo[i].allocPoint > 0) {
harvest(i);
}
}
}
/**
* @notice Function which withdraw LP tokens to messege sender with the given amount
* @param _pid: pool ID from which the LP tokens should be withdrawn
* @param _amount: the amount of LP tokens that should be withdrawn
*/
function withdraw(uint256 _pid, uint256 _amount) public poolExists(_pid) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accRewardPerShare).div(1e12).sub(
user.rewardDebt
);
safeETacoTransfer(msg.sender, pending);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accRewardPerShare).div(1e12);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
emit Withdraw(msg.sender, _pid, _amount);
}
/**
* @notice Function which withdraw all LP tokens to messege sender without caring about rewards
*/
function emergencyWithdraw(uint256 _pid)
public
poolExists(_pid)
nonReentrant
{
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
pool.lpToken.safeTransfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
}
/**
* @notice Function which transfer eTaco tokens to _to with the given amount
* @param _to: transfer reciver address
* @param _amount: amount of eTaco token which should be transfer
*/
function safeETacoTransfer(address _to, uint256 _amount) internal {
if (_amount > 0) {
uint256 etacoBal = etaco.balanceOf(address(this));
if (_amount > etacoBal) {
etaco.transfer(_to, etacoBal);
} else {
etaco.transfer(_to, _amount);
}
}
}
/**
* @notice Function which take ETH, add liquidity with provider and deposit given LP's
* @param _pid: pool ID where we want deposit
* @param _amountAMin: bounds the extent to which the B/A price can go up before the transaction reverts.
Must be <= amountADesired.
* @param _amountBMin: bounds the extent to which the A/B price can go up before the transaction reverts.
Must be <= amountBDesired
* @param _minAmountOutA: the minimum amount of output A tokens that must be received
for the transaction not to revert
* @param _minAmountOutB: the minimum amount of output B tokens that must be received
for the transaction not to revert
*/
function speedStake(
uint256 _pid,
uint256 _amountAMin,
uint256 _amountBMin,
uint256 _minAmountOutA,
uint256 _minAmountOutB,
uint256 _deadline
) public payable poolExists(_pid) {
(address routerAddr, , ) = provider.apis(_apiID);
IUniswapV2Router02 router = IUniswapV2Router02(routerAddr);
delete routerAddr;
require(
address(router) != address(0),
"MasterChef: Exchange does not set yet"
);
PoolInfo storage pool = poolInfo[_pid];
uint256 lp;
updatePool(_pid);
IUniswapV2Pair lpToken = IUniswapV2Pair(address(pool.lpToken));
if (
(lpToken.token0() == router.WETH()) ||
((lpToken.token1() == router.WETH()))
) {
lp = provider.addLiquidityETHByPair{value: msg.value}(
lpToken,
address(this),
_amountAMin,
_amountBMin,
_minAmountOutA,
_deadline,
_apiID
);
} else {
lp = provider.addLiquidityByPair{value: msg.value}(
lpToken,
_amountAMin,
_amountBMin,
_minAmountOutA,
_minAmountOutB,
address(this),
_deadline,
_apiID
);
}
_deposit(_pid, lp);
}
/**
* @notice Function which migrate pool to eTacoChef. Can only be called by the migrator
*/
function setPool(
uint256 _pid,
IERC20 _lpToken,
uint256 _allocPoint,
uint256 _lastRewardBlock,
uint256 _accRewardPerShare
) public onlyMigrator {
if (poolInfo.length <= _pid) {
poolInfo.push(
PoolInfo(
IERC20(_lpToken),
_allocPoint,
_lastRewardBlock,
_accRewardPerShare
)
);
} else {
totalAllocPoint -= poolInfo[_pid].allocPoint;
poolInfo[_pid] = PoolInfo(
IERC20(_lpToken),
_allocPoint,
_lastRewardBlock,
_accRewardPerShare
);
totalAllocPoint += _allocPoint;
}
}
/**
* @notice Function which migrate user to eTacoChef
*/
function setUser(
uint256 _pid,
address _user,
uint256 _amount,
uint256 _rewardDebt
) public onlyMigrator {
require(poolInfo.length != 0, "eTacoChef: Pools must be migrated");
updatePool(_pid);
userInfo[_pid][_user] = UserInfo(_amount, _rewardDebt.mul(9).div(10));
}
}
| Function which send accumulated eTaco tokens to messege sender _pid: pool ID from which the accumulated eTaco tokens should be received/ | function harvest(uint256 _pid) public poolExists(_pid) {
UserInfo storage user = userInfo[_pid][msg.sender];
if (user.amount > 0) {
updatePool(_pid);
uint256 accRewardPerShare = poolInfo[_pid].accRewardPerShare;
uint256 pending = user.amount.mul(accRewardPerShare).div(1e12).sub(
user.rewardDebt
);
safeETacoTransfer(msg.sender, pending);
user.rewardDebt = user.amount.mul(accRewardPerShare).div(1e12);
emit Harvest(msg.sender, _pid, pending);
}
}
| 947,220 |
pragma solidity ^0.4.19;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev modifier to allow actions only when the contract IS paused
*/
modifier whenNotPaused() {
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()
public
onlyOwner
whenNotPaused
returns (bool)
{
paused = true;
Pause();
return true;
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause()
public
onlyOwner
whenPaused
returns (bool)
{
paused = false;
Unpause();
return true;
}
}
/// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens
/// @author Dieter Shirley <[email protected]> (https://github.com/dete)
contract ERC721 {
event Transfer(address indexed _from, address indexed _to, uint256 _tokenId);
event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId);
// Required methods for ERC-721 Compatibility.
function approve(address _to, uint256 _tokenId) external;
function transfer(address _to, uint256 _tokenId) external;
function transferFrom(address _from, address _to, uint256 _tokenId) external;
function ownerOf(uint256 _tokenId) external view returns (address _owner);
// ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165)
function supportsInterface(bytes4 _interfaceID) external view returns (bool);
function totalSupply() public view returns (uint256 total);
function balanceOf(address _owner) public view returns (uint256 _balance);
}
contract MasterpieceAccessControl {
/// - CEO: The CEO can reassign other roles, change the addresses of dependent smart contracts,
/// and pause/unpause the MasterpieceCore contract.
/// - CFO: The CFO can withdraw funds from its auction and sale contracts.
/// - Curator: The Curator can mint regular and promo Masterpieces.
/// @dev The addresses of the accounts (or contracts) that can execute actions within each role.
address public ceoAddress;
address public cfoAddress;
address public curatorAddress;
/// @dev Keeps track whether the contract is paused. When that is true, most actions are blocked.
bool public paused = false;
/// @dev Event is fired when contract is forked.
event ContractFork(address newContract);
/// @dev Access-modifier for CEO-only functionality.
modifier onlyCEO() {
require(msg.sender == ceoAddress);
_;
}
/// @dev Access-modifier for CFO-only functionality.
modifier onlyCFO() {
require(msg.sender == cfoAddress);
_;
}
/// @dev Access-modifier for Curator-only functionality.
modifier onlyCurator() {
require(msg.sender == curatorAddress);
_;
}
/// @dev Access-modifier for C-level-only functionality.
modifier onlyCLevel() {
require(
msg.sender == ceoAddress ||
msg.sender == cfoAddress ||
msg.sender == curatorAddress
);
_;
}
/// Assigns a new address to the CEO role. Only available to the current CEO.
/// @param _newCEO The address of the new CEO
function setCEO(address _newCEO) external onlyCEO {
require(_newCEO != address(0));
ceoAddress = _newCEO;
}
/// Assigns a new address to act as the CFO. Only available to the current CEO.
/// @param _newCFO The address of the new CFO
function setCFO(address _newCFO) external onlyCEO {
require(_newCFO != address(0));
cfoAddress = _newCFO;
}
/// Assigns a new address to the Curator role. Only available to the current CEO.
/// @param _newCurator The address of the new Curator
function setCurator(address _newCurator) external onlyCEO {
require(_newCurator != address(0));
curatorAddress = _newCurator;
}
/*** Pausable functionality adapted from OpenZeppelin ***/
/// @dev Modifier to allow actions only when the contract IS NOT paused
modifier whenNotPaused() {
require(!paused);
_;
}
/// @dev Modifier to allow actions only when the contract IS paused
modifier whenPaused {
require(paused);
_;
}
/// @dev Called by any "C-level" role to pause the contract. Used only when
/// a bug or exploit is detected and we need to limit damage.
function pause()
external
onlyCLevel
whenNotPaused
{
paused = true;
}
/// @dev Unpauses the smart contract. Can only be called by the CEO, since
/// one reason we may pause the contract is when CFO or COO accounts are
/// compromised.
/// @notice This is public rather than external so it can be called by
/// derived contracts.
function unpause()
public
onlyCEO
whenPaused
{
// can't unpause if contract was forked
paused = false;
}
}
/// Core functionality for CrytpoMasterpieces.
contract MasterpieceBase is MasterpieceAccessControl {
/*** DATA TYPES ***/
/// The main masterpiece struct.
struct Masterpiece {
/// Name of the masterpiece
string name;
/// Name of the artist who created the masterpiece
string artist;
// The timestamp from the block when this masterpiece was created
uint64 birthTime;
}
/*** EVENTS ***/
/// The Birth event is fired whenever a new masterpiece comes into existence.
event Birth(address owner, uint256 tokenId, uint256 snatchWindow, string name, string artist);
/// Transfer event as defined in current draft of ERC721. Fired every time masterpiece ownership
/// is assigned, including births.
event TransferToken(address from, address to, uint256 tokenId);
/// The TokenSold event is fired whenever a token is sold.
event TokenSold(uint256 tokenId, uint256 oldPrice, uint256 price, address prevOwner, address owner, string name);
/*** STORAGE ***/
/// An array containing all Masterpieces in existence. The id of each masterpiece
/// is an index in this array.
Masterpiece[] masterpieces;
/// @dev The address of the ClockAuction contract that handles sale auctions
/// for Masterpieces that users want to sell for less than or equal to the
/// next price, which is automatically set by the contract.
SaleClockAuction public saleAuction;
/// @dev A mapping from masterpiece ids to the address that owns them.
mapping (uint256 => address) public masterpieceToOwner;
/// @dev A mapping from masterpiece ids to their snatch window.
mapping (uint256 => uint256) public masterpieceToSnatchWindow;
/// @dev A mapping from owner address to count of masterpieces that address owns.
/// Used internally inside balanceOf() to resolve ownership count.
mapping (address => uint256) public ownerMasterpieceCount;
/// @dev A mapping from masterpiece ids to an address that has been approved to call
/// transferFrom(). Each masterpiece can only have 1 approved address for transfer
/// at any time. A 0 value means no approval is outstanding.
mapping (uint256 => address) public masterpieceToApproved;
// @dev A mapping from masterpiece ids to their price.
mapping (uint256 => uint256) public masterpieceToPrice;
// @dev Returns the snatch window of the given token.
function snatchWindowOf(uint256 _tokenId)
public
view
returns (uint256 price)
{
return masterpieceToSnatchWindow[_tokenId];
}
/// @dev Assigns ownership of a specific masterpiece to an address.
function _transfer(address _from, address _to, uint256 _tokenId) internal {
// Transfer ownership and update owner masterpiece counts.
ownerMasterpieceCount[_to]++;
masterpieceToOwner[_tokenId] = _to;
// When creating new tokens _from is 0x0, but we can't account that address.
if (_from != address(0)) {
ownerMasterpieceCount[_from]--;
// clear any previously approved ownership exchange
delete masterpieceToApproved[_tokenId];
}
// Fire the transfer event.
TransferToken(_from, _to, _tokenId);
}
/// @dev An internal method that creates a new masterpiece and stores it.
/// @param _name The name of the masterpiece, e.g. Mona Lisa
/// @param _artist The artist who created this masterpiece, e.g. Leonardo Da Vinci
/// @param _owner The initial owner of this masterpiece
function _createMasterpiece(
string _name,
string _artist,
uint256 _price,
uint256 _snatchWindow,
address _owner
)
internal
returns (uint)
{
Masterpiece memory _masterpiece = Masterpiece({
name: _name,
artist: _artist,
birthTime: uint64(now)
});
uint256 newMasterpieceId = masterpieces.push(_masterpiece) - 1;
// Fire the birth event.
Birth(
_owner,
newMasterpieceId,
_snatchWindow,
_masterpiece.name,
_masterpiece.artist
);
// Set the price for the masterpiece.
masterpieceToPrice[newMasterpieceId] = _price;
// Set the snatch window for the masterpiece.
masterpieceToSnatchWindow[newMasterpieceId] = _snatchWindow;
// This will assign ownership, and also fire the Transfer event as per ERC-721 draft.
_transfer(0, _owner, newMasterpieceId);
return newMasterpieceId;
}
}
/// Pricing logic for CrytpoMasterpieces.
contract MasterpiecePricing is MasterpieceBase {
/*** CONSTANTS ***/
// Pricing steps.
uint128 private constant FIRST_STEP_LIMIT = 0.05 ether;
uint128 private constant SECOND_STEP_LIMIT = 0.5 ether;
uint128 private constant THIRD_STEP_LIMIT = 2.0 ether;
uint128 private constant FOURTH_STEP_LIMIT = 5.0 ether;
/// @dev Computes the next listed price.
/// @notice This contract doesn't handle setting the Masterpiece's next listing price.
/// This next price is only used from inside bid() in MasterpieceAuction and inside
/// purchase() in MasterpieceSale to set the next listed price.
function setNextPriceOf(uint256 tokenId, uint256 salePrice)
external
whenNotPaused
{
// The next price of any token can only be set by the sale auction contract.
// To set the next price for a token sold through the regular sale, use only
// computeNextPrice and directly update the mapping.
require(msg.sender == address(saleAuction));
masterpieceToPrice[tokenId] = computeNextPrice(salePrice);
}
/// @dev Computes next price of token given the current sale price.
function computeNextPrice(uint256 salePrice)
internal
pure
returns (uint256)
{
if (salePrice < FIRST_STEP_LIMIT) {
return SafeMath.div(SafeMath.mul(salePrice, 200), 95);
} else if (salePrice < SECOND_STEP_LIMIT) {
return SafeMath.div(SafeMath.mul(salePrice, 135), 96);
} else if (salePrice < THIRD_STEP_LIMIT) {
return SafeMath.div(SafeMath.mul(salePrice, 125), 97);
} else if (salePrice < FOURTH_STEP_LIMIT) {
return SafeMath.div(SafeMath.mul(salePrice, 120), 97);
} else {
return SafeMath.div(SafeMath.mul(salePrice, 115), 98);
}
}
/// @dev Computes the payment for the token, which is the sale price of the token
/// minus the house's cut.
function computePayment(uint256 salePrice)
internal
pure
returns (uint256)
{
if (salePrice < FIRST_STEP_LIMIT) {
return SafeMath.div(SafeMath.mul(salePrice, 95), 100);
} else if (salePrice < SECOND_STEP_LIMIT) {
return SafeMath.div(SafeMath.mul(salePrice, 96), 100);
} else if (salePrice < FOURTH_STEP_LIMIT) {
return SafeMath.div(SafeMath.mul(salePrice, 97), 100);
} else {
return SafeMath.div(SafeMath.mul(salePrice, 98), 100);
}
}
}
/// Methods required for Non-Fungible Token Transactions in adherence to ERC721.
contract MasterpieceOwnership is MasterpiecePricing, ERC721 {
/// Name of the collection of NFTs managed by this contract, as defined in ERC721.
string public constant NAME = "Masterpieces";
/// Symbol referencing the entire collection of NFTs managed in this contract, as
/// defined in ERC721.
string public constant SYMBOL = "CMP";
bytes4 public constant INTERFACE_SIGNATURE_ERC165 =
bytes4(keccak256("supportsInterface(bytes4)"));
bytes4 public constant INTERFACE_SIGNATURE_ERC721 =
bytes4(keccak256("name()")) ^
bytes4(keccak256("symbol()")) ^
bytes4(keccak256("totalSupply()")) ^
bytes4(keccak256("balanceOf(address)")) ^
bytes4(keccak256("ownerOf(uint256)")) ^
bytes4(keccak256("approve(address,uint256)")) ^
bytes4(keccak256("transfer(address,uint256)")) ^
bytes4(keccak256("transferFrom(address,address,uint256)")) ^
bytes4(keccak256("tokensOfOwner(address)")) ^
bytes4(keccak256("tokenMetadata(uint256,string)"));
/// @dev Grant another address the right to transfer a specific Masterpiece via
/// transferFrom(). This is the preferred flow for transfering NFTs to contracts.
/// @param _to The address to be granted transfer approval. Pass address(0) to
/// clear all approvals.
/// @param _tokenId The ID of the Masterpiece that can be transferred if this call succeeds.
/// @notice Required for ERC-20 and ERC-721 compliance.
function approve(address _to, uint256 _tokenId)
external
whenNotPaused
{
// Only an owner can grant transfer approval.
require(_owns(msg.sender, _tokenId));
// Register the approval (replacing any previous approval).
_approve(_tokenId, _to);
// Fire approval event upon successful approval.
Approval(msg.sender, _to, _tokenId);
}
/// @dev Transfers a Masterpiece to another address. If transferring to a smart
/// contract be VERY CAREFUL to ensure that it is aware of ERC-721 or else your
/// Masterpiece may be lost forever.
/// @param _to The address of the recipient, can be a user or contract.
/// @param _tokenId The ID of the Masterpiece to transfer.
/// @notice Required for ERC-20 and ERC-721 compliance.
function transfer(address _to, uint256 _tokenId)
external
whenNotPaused
{
// Safety check to prevent against an unexpected 0x0 default.
require(_to != address(0));
// Disallow transfers to this contract to prevent accidental misuse.
// The contract should never own any Masterpieces (except very briefly
// after a Masterpiece is created.
require(_to != address(this));
// Disallow transfers to the auction contract to prevent accidental
// misuse. Auction contracts should only take ownership of Masterpieces
// through the approve and transferFrom flow.
require(_to != address(saleAuction));
// You can only send your own Masterpiece.
require(_owns(msg.sender, _tokenId));
// Reassign ownership, clear pending approvals, fire Transfer event.
_transfer(msg.sender, _to, _tokenId);
}
/// @dev Transfer a Masterpiece owned by another address, for which the calling address
/// has previously been granted transfer approval by the owner.
/// @param _from The address that owns the Masterpiece to be transfered.
/// @param _to The address that should take ownership of the Masterpiece. Can be any
/// address, including the caller.
/// @param _tokenId The ID of the Masterpiece to be transferred.
/// @notice Required for ERC-20 and ERC-721 compliance.
function transferFrom(address _from, address _to, uint256 _tokenId)
external
whenNotPaused
{
// Safety check to prevent against an unexpected 0x0 default.
require(_to != address(0));
// Check for approval and valid ownership
require(_approvedFor(msg.sender, _tokenId));
require(_owns(_from, _tokenId));
// Reassign ownership (also clears pending approvals and fires Transfer event).
_transfer(_from, _to, _tokenId);
}
/// @dev Returns a list of all Masterpiece IDs assigned to an address.
/// @param _owner The owner whose Masterpieces we are interested in.
/// This method MUST NEVER be called by smart contract code. First, it is fairly
/// expensive (it walks the entire Masterpiece array looking for Masterpieces belonging
/// to owner), but it also returns a dynamic array, which is only supported for web3
/// calls, and not contract-to-contract calls. Thus, this method is external rather
/// than public.
function tokensOfOwner(address _owner)
external
view
returns(uint256[] ownerTokens)
{
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
// Returns an empty array
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
uint256 totalMasterpieces = totalSupply();
uint256 resultIndex = 0;
uint256 masterpieceId;
for (masterpieceId = 0; masterpieceId <= totalMasterpieces; masterpieceId++) {
if (masterpieceToOwner[masterpieceId] == _owner) {
result[resultIndex] = masterpieceId;
resultIndex++;
}
}
return result;
}
}
/// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165).
/// Returns true for any standardized interfaces implemented by this contract. We implement
/// ERC-165 (obviously!) and ERC-721.
function supportsInterface(bytes4 _interfaceID)
external
view
returns (bool)
{
return ((_interfaceID == INTERFACE_SIGNATURE_ERC165) || (_interfaceID == INTERFACE_SIGNATURE_ERC721));
}
// @notice Optional for ERC-20 compliance.
function name() external pure returns (string) {
return NAME;
}
// @notice Optional for ERC-20 compliance.
function symbol() external pure returns (string) {
return SYMBOL;
}
/// @dev Returns the address currently assigned ownership of a given Masterpiece.
/// @notice Required for ERC-721 compliance.
function ownerOf(uint256 _tokenId)
external
view
returns (address owner)
{
owner = masterpieceToOwner[_tokenId];
require(owner != address(0));
}
/// @dev Returns the total number of Masterpieces currently in existence.
/// @notice Required for ERC-20 and ERC-721 compliance.
function totalSupply() public view returns (uint) {
return masterpieces.length;
}
/// @dev Returns the number of Masterpieces owned by a specific address.
/// @param _owner The owner address to check.
/// @notice Required for ERC-20 and ERC-721 compliance.
function balanceOf(address _owner)
public
view
returns (uint256 count)
{
return ownerMasterpieceCount[_owner];
}
/// @dev Checks if a given address is the current owner of a particular Masterpiece.
/// @param _claimant the address we are validating against.
/// @param _tokenId Masterpiece id, only valid when > 0
function _owns(address _claimant, uint256 _tokenId)
internal
view
returns (bool)
{
return masterpieceToOwner[_tokenId] == _claimant;
}
/// @dev Marks an address as being approved for transferFrom(), overwriting any previous
/// approval. Setting _approved to address(0) clears all transfer approval.
/// NOTE: _approve() does NOT send the Approval event. This is intentional because
/// _approve() and transferFrom() are used together for putting Masterpieces on auction, and
/// there is no value in spamming the log with Approval events in that case.
function _approve(uint256 _tokenId, address _approved) internal {
masterpieceToApproved[_tokenId] = _approved;
}
/// @dev Checks if a given address currently has transferApproval for a particular Masterpiece.
/// @param _claimant the address we are confirming Masterpiece is approved for.
/// @param _tokenId Masterpiece id, only valid when > 0
function _approvedFor(address _claimant, uint256 _tokenId)
internal
view
returns (bool)
{
return masterpieceToApproved[_tokenId] == _claimant;
}
/// Safety check on _to address to prevent against an unexpected 0x0 default.
function _addressNotNull(address _to) internal pure returns (bool) {
return _to != address(0);
}
}
/// @title Auction Core
/// @dev Contains models, variables, and internal methods for the auction.
/// @notice We omit a fallback function to prevent accidental sends to this contract.
contract ClockAuctionBase {
// Represents an auction on an NFT
struct Auction {
// Current owner of NFT
address seller;
// Price (in wei) at beginning of auction
uint128 startingPrice;
// Price (in wei) at end of auction
uint128 endingPrice;
// Duration (in seconds) of auction
uint64 duration;
// Time when auction started
// NOTE: 0 if this auction has been concluded
uint64 startedAt;
}
// Reference to contract tracking NFT ownership
MasterpieceOwnership public nonFungibleContract;
// Cut owner takes on each auction, measured in basis points (1/100 of a percent).
// Values 0-10,000 map to 0%-100%
uint256 public ownerCut;
// Map from token ID to their corresponding auction.
mapping (uint256 => Auction) public tokenIdToAuction;
event AuctionCreated(uint256 tokenId, uint256 startingPrice, uint256 endingPrice, uint256 duration);
event AuctionSuccessful(uint256 tokenId, uint256 price, address winner);
event AuctionCancelled(uint256 tokenId);
/// @dev Returns true if the claimant owns the token.
/// @param _claimant - Address claiming to own the token.
/// @param _tokenId - ID of token whose ownership to verify.
function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) {
return (nonFungibleContract.ownerOf(_tokenId) == _claimant);
}
/// @dev Escrows the NFT, assigning ownership to this contract.
/// Throws if the escrow fails.
/// @param _owner - Current owner address of token to escrow.
/// @param _tokenId - ID of token whose approval to verify.
function _escrow(address _owner, uint256 _tokenId) internal {
// it will throw if transfer fails
nonFungibleContract.transferFrom(_owner, this, _tokenId);
}
/// @dev Transfers an NFT owned by this contract to another address.
/// Returns true if the transfer succeeds.
/// @param _receiver - Address to transfer NFT to.
/// @param _tokenId - ID of token to transfer.
function _transfer(address _receiver, uint256 _tokenId) internal {
// it will throw if transfer fails
nonFungibleContract.transfer(_receiver, _tokenId);
}
/// @dev Adds an auction to the list of open auctions. Also fires the
/// AuctionCreated event.
/// @param _tokenId The ID of the token to be put on auction.
/// @param _auction Auction to add.
function _addAuction(uint256 _tokenId, Auction _auction) internal {
// Require that all auctions have a duration of
// at least one minute. (Keeps our math from getting hairy!)
require(_auction.duration >= 1 minutes);
tokenIdToAuction[_tokenId] = _auction;
AuctionCreated(
uint256(_tokenId),
uint256(_auction.startingPrice),
uint256(_auction.endingPrice),
uint256(_auction.duration)
);
}
/// @dev Cancels an auction unconditionally.
function _cancelAuction(uint256 _tokenId, address _seller) internal {
_removeAuction(_tokenId);
_transfer(_seller, _tokenId);
AuctionCancelled(_tokenId);
}
/// @dev Computes the price and transfers winnings.
/// Does NOT transfer ownership of token.
function _bid(uint256 _tokenId, uint256 _bidAmount)
internal
returns (uint256)
{
// Get a reference to the auction struct
Auction storage auction = tokenIdToAuction[_tokenId];
// Explicitly check that this auction is currently live.
// (Because of how Ethereum mappings work, we can't just count
// on the lookup above failing. An invalid _tokenId will just
// return an auction object that is all zeros.)
require(_isOnAuction(auction));
// Check that the bid is greater than or equal to the current price
uint256 price = _currentPrice(auction);
require(_bidAmount >= price);
// Grab a reference to the seller before the auction struct gets deleted.
address seller = auction.seller;
// Remove the auction before sending the fees to the sender so we can't have a reentrancy attack.
_removeAuction(_tokenId);
if (price > 0) {
// Calculate the auctioneer's cut.
uint256 auctioneerCut = _computeCut(price);
uint256 sellerProceeds = price - auctioneerCut;
// NOTE: Doing a transfer() in the middle of a complex
// method like this is generally discouraged because of
// reentrancy attacks and DoS attacks if the seller is
// a contract with an invalid fallback function. We explicitly
// guard against reentrancy attacks by removing the auction
// before calling transfer(), and the only thing the seller
// can DoS is the sale of their own asset! (And if it's an
// accident, they can call cancelAuction(). )
seller.transfer(sellerProceeds);
_transfer(msg.sender, _tokenId);
// Update the next listing price of the token.
nonFungibleContract.setNextPriceOf(_tokenId, price);
}
// Calculate any excess funds included with the bid. If the excess
// is anything worth worrying about, transfer it back to bidder.
// NOTE: We checked above that the bid amount is greater than or
// equal to the price so this cannot underflow.
uint256 bidExcess = _bidAmount - price;
// Return the funds. Similar to the previous transfer, this is
// not susceptible to a re-entry attack because the auction is
// removed before any transfers occur.
msg.sender.transfer(bidExcess);
// Tell the world!
AuctionSuccessful(_tokenId, price, msg.sender);
return price;
}
/// @dev Removes an auction from the list of open auctions.
/// @param _tokenId - ID of NFT on auction.
function _removeAuction(uint256 _tokenId) internal {
delete tokenIdToAuction[_tokenId];
}
/// @dev Returns true if the NFT is on auction.
/// @param _auction - Auction to check.
function _isOnAuction(Auction storage _auction)
internal
view
returns (bool)
{
return (_auction.startedAt > 0);
}
/// @dev Returns current price of an NFT on auction. Broken into two
/// functions (this one, that computes the duration from the auction
/// structure, and the other that does the price computation) so we
/// can easily test that the price computation works correctly.
function _currentPrice(Auction storage _auction)
internal
view
returns (uint256)
{
uint256 secondsPassed = 0;
// A bit of insurance against negative values (or wraparound).
// Probably not necessary (since Ethereum guarnatees that the
// now variable doesn't ever go backwards).
if (now > _auction.startedAt) {
secondsPassed = now - _auction.startedAt;
}
return _computeCurrentPrice(
_auction.startingPrice,
_auction.endingPrice,
_auction.duration,
secondsPassed
);
}
/// @dev Computes the current price of an auction. Factored out
/// from _currentPrice so we can run extensive unit tests.
/// When testing, make this function public and turn on
/// `Current price computation` test suite.
function _computeCurrentPrice(
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration,
uint256 _secondsPassed
)
internal
pure
returns (uint256)
{
// NOTE: We don't use SafeMath (or similar) in this function because
// all of our public functions carefully cap the maximum values for
// time (at 64-bits) and currency (at 128-bits). _duration is
// also known to be non-zero (see the require() statement in
// _addAuction())
if (_secondsPassed >= _duration) {
// We've reached the end of the dynamic pricing portion
// of the auction, just return the end price.
return _endingPrice;
} else {
// Starting price can be higher than ending price (and often is!), so
// this delta can be negative.
int256 totalPriceChange = int256(_endingPrice) - int256(_startingPrice);
// This multiplication can't overflow, _secondsPassed will easily fit within
// 64-bits, and totalPriceChange will easily fit within 128-bits, their product
// will always fit within 256-bits.
int256 currentPriceChange = totalPriceChange * int256(_secondsPassed) / int256(_duration);
// currentPriceChange can be negative, but if so, will have a magnitude
// less that _startingPrice. Thus, this result will always end up positive.
int256 currentPrice = int256(_startingPrice) + currentPriceChange;
return uint256(currentPrice);
}
}
/// @dev Computes owner's cut of a sale.
/// @param _price - Sale price of NFT.
function _computeCut(uint256 _price) internal view returns (uint256) {
// NOTE: We don't use SafeMath (or similar) in this function because
// all of our entry functions carefully cap the maximum values for
// currency (at 128-bits), and ownerCut <= 10000 (see the require()
// statement in the ClockAuction constructor). The result of this
// function is always guaranteed to be <= _price.
return _price * ownerCut / 10000;
}
}
/// @title Clock auction for non-fungible tokens.
/// @notice We omit a fallback function to prevent accidental sends to this contract.
contract ClockAuction is Pausable, ClockAuctionBase {
/// @dev The ERC-165 interface signature for ERC-721.
/// Ref: https://github.com/ethereum/EIPs/issues/165
/// Ref: https://github.com/ethereum/EIPs/issues/721
bytes4 public constant INTERFACE_SIGNATURE_ERC721 = bytes4(0x9a20483d);
/// @dev Constructor creates a reference to the NFT ownership contract
/// and verifies the owner cut is in the valid range.
/// @param _nftAddress - address of a deployed contract implementing
/// the Nonfungible Interface.
/// @param _cut - percent cut the owner takes on each auction, must be
/// between 0-10,000.
function ClockAuction(address _nftAddress, uint256 _cut) public {
require(_cut <= 10000);
ownerCut = _cut;
MasterpieceOwnership candidateContract = MasterpieceOwnership(_nftAddress);
require(candidateContract.supportsInterface(INTERFACE_SIGNATURE_ERC721));
nonFungibleContract = candidateContract;
}
/// @dev Remove all Ether from the contract, which is the owner's cuts
/// as well as any Ether sent directly to the contract address.
/// Always transfers to the NFT contract, but can be called either by
/// the owner or the NFT contract.
function withdrawBalance() external {
address nftAddress = address(nonFungibleContract);
require(
msg.sender == owner ||
msg.sender == nftAddress
);
// We are using this boolean method to make sure that even if one fails it will still work
bool res = nftAddress.send(this.balance);
}
/// @dev Creates and begins a new auction.
/// @param _tokenId - ID of token to auction, sender must be owner.
/// @param _startingPrice - Price of item (in wei) at beginning of auction.
/// @param _endingPrice - Price of item (in wei) at end of auction.
/// @param _duration - Length of time to move between starting
/// price and ending price (in seconds).
/// @param _seller - Seller, if not the message sender
function createAuction(
uint256 _tokenId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration,
address _seller
)
external
whenNotPaused
{
// Sanity check that no inputs overflow how many bits we've allocated
// to store them in the auction struct.
require(_startingPrice == uint256(uint128(_startingPrice)));
require(_endingPrice == uint256(uint128(_endingPrice)));
require(_duration == uint256(uint64(_duration)));
require(_owns(msg.sender, _tokenId));
_escrow(msg.sender, _tokenId);
Auction memory auction = Auction(
_seller,
uint128(_startingPrice),
uint128(_endingPrice),
uint64(_duration),
uint64(now)
);
_addAuction(_tokenId, auction);
}
/// @dev Bids on an open auction, completing the auction and transferring
/// ownership of the NFT if enough Ether is supplied.
/// @param _tokenId - ID of token to bid on.
function bid(uint256 _tokenId)
external
payable
whenNotPaused
{
// _bid will throw if the bid or funds transfer fails
_bid(_tokenId, msg.value);
}
/// @dev Cancels an auction that hasn't been won yet.
/// Returns the NFT to original owner.
/// @notice This is a state-modifying function that can
/// be called while the contract is paused.
/// @param _tokenId - ID of token on auction
function cancelAuction(uint256 _tokenId)
external
{
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
address seller = auction.seller;
require(msg.sender == seller);
_cancelAuction(_tokenId, seller);
}
/// @dev Cancels an auction when the contract is paused.
/// Only the owner may do this, and NFTs are returned to
/// the seller. This should only be used in emergencies.
/// @param _tokenId - ID of the NFT on auction to cancel.
function cancelAuctionWhenPaused(uint256 _tokenId)
external
whenPaused
onlyOwner
{
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
_cancelAuction(_tokenId, auction.seller);
}
/// @dev Returns auction info for an NFT on auction.
/// @param _tokenId - ID of NFT on auction.
function getAuction(uint256 _tokenId)
external
view
returns
(
address seller,
uint256 startingPrice,
uint256 endingPrice,
uint256 duration,
uint256 startedAt
) {
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
return (
auction.seller,
auction.startingPrice,
auction.endingPrice,
auction.duration,
auction.startedAt
);
}
/// @dev Returns the current price of an auction.
/// @param _tokenId - ID of the token price we are checking.
function getCurrentPrice(uint256 _tokenId)
external
view
returns (uint256)
{
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
return _currentPrice(auction);
}
}
/// @title Clock auction
/// @notice We omit a fallback function to prevent accidental sends to this contract.
contract SaleClockAuction is ClockAuction {
// @dev Sanity check that allows us to ensure that we are pointing to the
// right auction in our setSaleAuctionAddress() call.
bool public isSaleClockAuction = true;
// Delegate constructor
function SaleClockAuction(address _nftAddr, uint256 _cut) public
ClockAuction(_nftAddr, _cut) {}
/// @dev Creates and begins a new auction.
/// @param _tokenId - ID of token to auction, sender must be owner.
/// @param _startingPrice - Price of item (in wei) at beginning of auction.
/// @param _endingPrice - Price of item (in wei) at end of auction.
/// @param _duration - Length of auction (in seconds).
/// @param _seller - Seller, if not the message sender
function createAuction(
uint256 _tokenId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration,
address _seller
)
external
{
// Sanity check that no inputs overflow how many bits we've allocated
// to store them in the auction struct.
require(_startingPrice == uint256(uint128(_startingPrice)));
require(_endingPrice == uint256(uint128(_endingPrice)));
require(_duration == uint256(uint64(_duration)));
require(msg.sender == address(nonFungibleContract));
_escrow(_seller, _tokenId);
Auction memory auction = Auction(
_seller,
uint128(_startingPrice),
uint128(_endingPrice),
uint64(_duration),
uint64(now)
);
_addAuction(_tokenId, auction);
}
/// @dev Places a bid for the Masterpiece. Requires the sender
/// is the Masterpiece Core contract because all bid methods
/// should be wrapped.
function bid(uint256 _tokenId)
external
payable
{
/* require(msg.sender == address(nonFungibleContract)); */
// _bid checks that token ID is valid and will throw if bid fails
_bid(_tokenId, msg.value);
}
}
contract MasterpieceAuction is MasterpieceOwnership {
/// @dev Transfers the balance of the sale auction contract
/// to the MasterpieceCore contract. We use two-step withdrawal to
/// prevent two transfer calls in the auction bid function.
function withdrawAuctionBalances()
external
onlyCLevel
{
saleAuction.withdrawBalance();
}
/// @notice The auction contract variable (saleAuction) is defined in MasterpieceBase
/// to allow us to refer to them in MasterpieceOwnership to prevent accidental transfers.
/// @dev Sets the reference to the sale auction.
/// @param _address - Address of sale contract.
function setSaleAuctionAddress(address _address)
external
onlyCEO
{
SaleClockAuction candidateContract = SaleClockAuction(_address);
// NOTE: verify that a contract is what we expect -
// https://github.com/Lunyr/crowdsale-contracts/blob/
// cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117
require(candidateContract.isSaleClockAuction());
// Set the new contract address
saleAuction = candidateContract;
}
/// @dev The owner of a Masterpiece can put it up for auction.
function createSaleAuction(
uint256 _tokenId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration
)
external
whenNotPaused
{
// Check that the Masterpiece to be put on an auction sale is owned by
// its current owner. If it's already in an auction, this validation
// will fail because the MasterpieceAuction contract owns the
// Masterpiece once it is put on an auction sale.
require(_owns(msg.sender, _tokenId));
_approve(_tokenId, saleAuction);
// Sale auction throws if inputs are invalid and clears
// transfer approval after escrow
saleAuction.createAuction(
_tokenId,
_startingPrice,
_endingPrice,
_duration,
msg.sender
);
}
}
contract MasterpieceSale is MasterpieceAuction {
// Allows someone to send ether and obtain the token
function purchase(uint256 _tokenId)
public
payable
whenNotPaused
{
address newOwner = msg.sender;
address oldOwner = masterpieceToOwner[_tokenId];
uint256 salePrice = masterpieceToPrice[_tokenId];
// Require that the masterpiece is either currently owned by the Masterpiece
// Core contract or was born within the snatch window.
require(
(oldOwner == address(this)) ||
(now - masterpieces[_tokenId].birthTime <= masterpieceToSnatchWindow[_tokenId])
);
// Require that the owner of the token is not sending to self.
require(oldOwner != newOwner);
// Require that the Masterpiece is not in an auction by checking that
// the Sale Clock Auction contract is not the owner.
require(address(oldOwner) != address(saleAuction));
// Safety check to prevent against an unexpected 0x0 default.
require(_addressNotNull(newOwner));
// Check that sent amount is greater than or equal to the sale price
require(msg.value >= salePrice);
uint256 payment = uint256(computePayment(salePrice));
uint256 purchaseExcess = SafeMath.sub(msg.value, salePrice);
// Set next listing price.
masterpieceToPrice[_tokenId] = computeNextPrice(salePrice);
// Transfer the Masterpiece to the buyer.
_transfer(oldOwner, newOwner, _tokenId);
// Pay seller of the Masterpiece if they are not this contract.
if (oldOwner != address(this)) {
oldOwner.transfer(payment);
}
TokenSold(_tokenId, salePrice, masterpieceToPrice[_tokenId], oldOwner, newOwner, masterpieces[_tokenId].name);
// Reimburse the buyer of any excess paid.
msg.sender.transfer(purchaseExcess);
}
function priceOf(uint256 _tokenId)
public
view
returns (uint256 price)
{
return masterpieceToPrice[_tokenId];
}
}
contract MasterpieceMinting is MasterpieceSale {
/*** CONSTANTS ***/
/// @dev Starting price of a regular Masterpiece.
uint128 private constant STARTING_PRICE = 0.001 ether;
/// @dev Limit of number of promo masterpieces that can be created.
uint16 private constant PROMO_CREATION_LIMIT = 10000;
/// @dev Counts the number of Promotional Masterpieces the contract owner has created.
uint16 public promoMasterpiecesCreatedCount;
/// @dev Reference to contract tracking Non Fungible Token ownership
ERC721 public nonFungibleContract;
/// @dev Creates a new Masterpiece with the given name and artist.
function createMasterpiece(
string _name,
string _artist,
uint256 _snatchWindow
)
public
onlyCurator
returns (uint)
{
uint256 masterpieceId = _createMasterpiece(_name, _artist, STARTING_PRICE, _snatchWindow, address(this));
return masterpieceId;
}
/// @dev Creates a new promotional Masterpiece with the given name, artist, starting
/// price, and owner. If the owner or the price is not set, we default them to the
/// curator's address and the starting price for all masterpieces.
function createPromoMasterpiece(
string _name,
string _artist,
uint256 _snatchWindow,
uint256 _price,
address _owner
)
public
onlyCurator
returns (uint)
{
require(promoMasterpiecesCreatedCount < PROMO_CREATION_LIMIT);
address masterpieceOwner = _owner;
if (masterpieceOwner == address(0)) {
masterpieceOwner = curatorAddress;
}
if (_price <= 0) {
_price = STARTING_PRICE;
}
uint256 masterpieceId = _createMasterpiece(_name, _artist, _price, _snatchWindow, masterpieceOwner);
promoMasterpiecesCreatedCount++;
return masterpieceId;
}
}
/// CryptoMasterpieces: Collectible fine art masterpieces on the Ethereum blockchain.
contract MasterpieceCore is MasterpieceMinting {
// - MasterpieceAccessControl: This contract defines which users are granted the given roles that are
// required to execute specific operations.
//
// - MasterpieceBase: This contract inherits from the MasterpieceAccessControl contract and defines
// the core functionality of CryptoMasterpieces, including the data types, storage, and constants.
//
// - MasterpiecePricing: This contract inherits from the MasterpieceBase contract and defines
// the pricing logic for CryptoMasterpieces. With every purchase made through the Core contract or
// through a sale auction, the next listed price will multiply based on 5 price tiers. This ensures
// that the Masterpiece bought through CryptoMasterpieces will always be adjusted to its fair market
// value.
//
// - MasterpieceOwnership: This contract inherits from the MasterpiecePricing contract and the ERC-721
// (https://github.com/ethereum/EIPs/issues/721) contract and implements the methods required for
// Non-Fungible Token Transactions.
//
// - MasterpieceAuction: This contract inherits from the MasterpieceOwnership contract. It defines
// the Dutch "clock" auction mechanism for owners of a masterpiece to place it on sale. The auction
// starts off at the automatically generated next price and until it is sold, decrements the price
// as time passes. The owner of the masterpiece can cancel the auction at any point and the price
// cannot go lower than the price that the owner bought the masterpiece for.
//
// - MasterpieceSale: This contract inherits from the MasterpieceAuction contract. It defines the
// tiered pricing logic and handles all sales. It also checks that a Masterpiece is not in an
// auction before approving a purchase.
//
// - MasterpieceMinting: This contract inherits from the MasterpieceSale contract. It defines the
// creation of new regular and promotional masterpieces.
// Set in case the core contract is broken and a fork is required
address public newContractAddress;
function MasterpieceCore() public {
// Starts paused.
paused = true;
// The creator of the contract is the initial CEO
ceoAddress = msg.sender;
// The creator of the contract is also the initial Curator
curatorAddress = msg.sender;
}
/// @dev Used to mark the smart contract as upgraded, in case there is a serious
/// breaking bug. This method does nothing but keep track of the new contract and
/// emit a message indicating that the new address is set. It's up to clients of this
/// contract to update to the new contract address in that case. (This contract will
/// be paused indefinitely if such an upgrade takes place.)
/// @param _v2Address new address
function setNewAddress(address _v2Address)
external
onlyCEO
whenPaused
{
// See README.md for updgrade plan
newContractAddress = _v2Address;
ContractFork(_v2Address);
}
/// @dev Withdraw all Ether from the contract. This includes the fee on every
/// masterpiece sold and any Ether sent directly to the contract address.
/// Only the CFO can withdraw the balance or specify the address to send
/// the balance to.
function withdrawBalance(address _to) external onlyCFO {
// We are using this boolean method to make sure that even if one fails it will still work
if (_to == address(0)) {
cfoAddress.transfer(this.balance);
} else {
_to.transfer(this.balance);
}
}
/// @notice Returns all the relevant information about a specific masterpiece.
/// @param _tokenId The tokenId of the masterpiece of interest.
function getMasterpiece(uint256 _tokenId) external view returns (
string name,
string artist,
uint256 birthTime,
uint256 snatchWindow,
uint256 sellingPrice,
address owner
) {
Masterpiece storage masterpiece = masterpieces[_tokenId];
name = masterpiece.name;
artist = masterpiece.artist;
birthTime = uint256(masterpiece.birthTime);
snatchWindow = masterpieceToSnatchWindow[_tokenId];
sellingPrice = masterpieceToPrice[_tokenId];
owner = masterpieceToOwner[_tokenId];
}
/// @dev Override unpause so it requires all external contract addresses
/// to be set before contract can be unpaused. Also, we can't have
/// newContractAddress set either, because then the contract was upgraded.
/// @notice This is public rather than external so we can call super.unpause
/// without using an expensive call.
function unpause()
public
onlyCEO
whenPaused
{
require(saleAuction != address(0));
require(newContractAddress == address(0));
// Actually unpause the contract.
super.unpause();
}
} | The owner of a Masterpiece can put it up for auction. Check that the Masterpiece to be put on an auction sale is owned by its current owner. If it's already in an auction, this validation will fail because the MasterpieceAuction contract owns the Masterpiece once it is put on an auction sale. Sale auction throws if inputs are invalid and clears transfer approval after escrow | function createSaleAuction(
uint256 _tokenId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration
)
external
whenNotPaused
{
require(_owns(msg.sender, _tokenId));
_approve(_tokenId, saleAuction);
saleAuction.createAuction(
_tokenId,
_startingPrice,
_endingPrice,
_duration,
msg.sender
);
}
| 13,019,537 |
// SPDX-License-Identifier: MIT-open-group
pragma solidity >= 0.5.15;
pragma abicoder v2;
import "ds-test/test.sol";
import "./Setup.t.sol";
import "../Constants.sol";
contract StakingTokenMock is Token {
constructor(bytes32 symbol, bytes32 name) Token(symbol, name) {}
function approveFor(address owner, address who, uint wad) external returns (bool) {
allowance[owner][who] = wad;
emit Approval(owner, who, wad);
return true;
}
}
contract AccusationInvalidTransactionConsumptionFacetTest is Constants, DSTest, Setup {
function setUp() public override {
setUp(address(new StakingTokenMock("STK", "MadNet Staking")));
}
// Helper functions to create validators
function generateMadID(uint256 id) internal pure returns (uint256[2] memory madID) {
madID[0] = id;
madID[1] = id;
}
function getValidAccusationData_NonExistentUTXO() internal pure returns(
bytes memory pClaimsCapnProto,
bytes memory pClaimsSig,
bytes memory bClaimsCapnProto,
bytes memory bClaimsSigGroup,
bytes memory txInPreImageCapnProto,
bytes[3] memory proofs
) {
pClaimsCapnProto = hex"000000000000020004000000020004005800000000000200010000000200000001000000000000000d00000002010000190000000201000025000000020100003100000002010000fb9caafb31a4d4cada31e5d20ef0952832d8f37a70aa40c7035a693199e964afa368ad44a1ae7ea22d0857c32da7e679fb29c4357e4de838394faf0bd57e14930d66a8a0babec3d38b67b5239c1683f15a57e087f3825fac3d70fd6a243ed30bc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a47004000000020001001d00000002060000010000000200000001000000000000000100000002010000fb9caafb31a4d4cada31e5d20ef0952832d8f37a70aa40c7035a693199e964af258aa89365a642358d92db67a13cb25d73e6eedf0d25100d8d91566882fac54b1ccedfb0425434b54999a88cd7d993e05411955955c0cfec9dd33066605bd4a60f6bbfbab37349aaa762c23281b5749932c514f3b8723cf9bb05f9841a7f2d0e0f75e42fd6c8e9f0edadac3dcfb7416c2d4b2470f4210f2afa93138615b1deb106f5308b02f59062b735d0021ba93b1b9c09f3e168384b96b1eccfed659357142a7bd3532dc054cb5be81e9d559128229d61a00474b983a3569f538eb03d07ce";
pClaimsSig = hex"51cacd39457727591e75c61733f38447039d3bc7dd326fa946d2136ed14cacfe2f0a1421c17e26b644b0c3fca9b38907cd90de93b9a75e8cfccfad50b351ae3000";
bClaimsCapnProto = hex"0000000002000400010000000100000005000000000000000d0000000201000019000000020100002500000002010000310000000201000041b1a0649752af1b28b3dc29a1556eee781e4a4c3a1f7f53f90fa834de098c4d3d9261b2bee4a635db058a9f13572c18c8d092182125ddd96ca58c3f405993f00d66a8a0babec3d38b67b5239c1683f15a57e087f3825fac3d70fd6a243ed30bc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470";
bClaimsSigGroup = hex"258aa89365a642358d92db67a13cb25d73e6eedf0d25100d8d91566882fac54b1ccedfb0425434b54999a88cd7d993e05411955955c0cfec9dd33066605bd4a60f6bbfbab37349aaa762c23281b5749932c514f3b8723cf9bb05f9841a7f2d0e0f75e42fd6c8e9f0edadac3dcfb7416c2d4b2470f4210f2afa93138615b1deb106f5308b02f59062b735d0021ba93b1b9c09f3e168384b96b1eccfed659357142a7bd3532dc054cb5be81e9d559128229d61a00474b983a3569f538eb03d07ce";
// proofAgainstStateRootCapnProto
proofs[0] = hex"000004da3dc36dc016d513fbac07ed6605c6157088d8c673df3b5bb09682b7937d52500000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010003d0686741a9adaa231d9555e49c4a4c96bf30992aaaf2784df9ae047a21364ce138fb9eb5ced6edc2826e734abad6235c8cf638c812247fd38f04e7080d431933b9c6d6f24756341fde3e8055dd3a83743a94dddc122ab3f32a3db0c4749ff57bad";
// proofInclusionTXRootCapnProto
proofs[1] = hex"0100006e286c26d8715685894787919c58c9aeee7dff73f88bf476dab1d282d535e5f200000000000000000000000000000000000000000000000000000000000000007015f14a90fd8c32ff946f17def605bccdee5f828a0dcd5c8e373346d41547a40001000000";
// proofInclusionTXHashCapnProto
proofs[2] = hex"010005da3dc36dc016d513fbac07ed6605c6157088d8c673df3b5bb09682b7937d52500000000000000000000000000000000000000000000000000000000000000000059fb90cd9bd014b03f9967c7258b7fe11bb03415c0331926d5cbcaa3e89582300010002885bfe473b114836cb46eaac9f8dc3f250cac5f74e60f42419a180a419842a8291b3dc4df7060209ffb1efa66f693ed888c15034398312231b51894f86343c2421";
txInPreImageCapnProto = hex"000000000100010001000000000000000100000002010000f172873c63909462ac4de545471fd3ad3e9eeadeec4608b92d16ce6b500704cc";
}
function getValidAccusationData_DoubleSpentDeposit() internal pure returns(
bytes memory pClaimsCapnProto,
bytes memory pClaimsSig,
bytes memory bClaimsCapnProto,
bytes memory bClaimsSigGroup,
bytes memory txInPreImageCapnProto,
bytes[3] memory proofs
) {
pClaimsCapnProto = hex"000000000000020004000000020004005800000000000200010000000200000001000000000000000d00000002010000190000000201000025000000020100003100000002010000fb9caafb31a4d4cada31e5d20ef0952832d8f37a70aa40c7035a693199e964afe025b75676058e9ce45178a8462da70dac3ae495f342fe5e222614ccab7e4d720d66a8a0babec3d38b67b5239c1683f15a57e087f3825fac3d70fd6a243ed30bc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a47004000000020001001d00000002060000010000000200000001000000000000000100000002010000fb9caafb31a4d4cada31e5d20ef0952832d8f37a70aa40c7035a693199e964af258aa89365a642358d92db67a13cb25d73e6eedf0d25100d8d91566882fac54b1ccedfb0425434b54999a88cd7d993e05411955955c0cfec9dd33066605bd4a60f6bbfbab37349aaa762c23281b5749932c514f3b8723cf9bb05f9841a7f2d0e0f75e42fd6c8e9f0edadac3dcfb7416c2d4b2470f4210f2afa93138615b1deb106f5308b02f59062b735d0021ba93b1b9c09f3e168384b96b1eccfed659357142a7bd3532dc054cb5be81e9d559128229d61a00474b983a3569f538eb03d07ce";
pClaimsSig = hex"72092a7de7ecb4faf7920c424cb656624695396aac14a0b1091eeb141eb584fb3a9b4335a8d1ab584bb823b90bb456eedc318175ac0f95857a0c5e93e7e5da3b01";
bClaimsCapnProto = hex"0000000002000400010000000100000005000000000000000d0000000201000019000000020100002500000002010000310000000201000041b1a0649752af1b28b3dc29a1556eee781e4a4c3a1f7f53f90fa834de098c4d3d9261b2bee4a635db058a9f13572c18c8d092182125ddd96ca58c3f405993f00d66a8a0babec3d38b67b5239c1683f15a57e087f3825fac3d70fd6a243ed30bc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470";
bClaimsSigGroup = hex"258aa89365a642358d92db67a13cb25d73e6eedf0d25100d8d91566882fac54b1ccedfb0425434b54999a88cd7d993e05411955955c0cfec9dd33066605bd4a60f6bbfbab37349aaa762c23281b5749932c514f3b8723cf9bb05f9841a7f2d0e0f75e42fd6c8e9f0edadac3dcfb7416c2d4b2470f4210f2afa93138615b1deb106f5308b02f59062b735d0021ba93b1b9c09f3e168384b96b1eccfed659357142a7bd3532dc054cb5be81e9d559128229d61a00474b983a3569f538eb03d07ce";
// proofAgainstStateRootCapnProto
proofs[0] = hex"010100000000000000000000000000000000000000000000000000000000000000003000000000000000000000000000000000000000000000000000000000000000000be3ba01ddd6fb3d58ff1e8b79b7db6db5ef6376d877f7ca88e0c78e141da9fa00210006e00000000000000000000000000000000000000000000000000000000000002300166eacf747876e3a8eb60fdd36cfac41e9ae27098cf605d90a019a895e98af171ddb3652b5ecb0881027ca462000d3614fd7735855db004c598622855e9190c49bd43690efe794fff0a9790fc9c3f694e251cd15dbf06a5217005cffc23943c254ec9d782b8991251f91af85390450ad21fc2befaf8f473367a30d579c36e221480543d6cc63a90d7c121e5219495ebc0091dd7355763da9d97931997f52260b1c925246c3b9255ebd67fc7daf4769f556b5eaefbd62d31daf7f6c43da4ffe2c";
// proofInclusionTXRootCapnProto
proofs[1] = hex"0100007b802d223569d7b75cec992b1b028b0c2092d950d992b11187f11ee568c469bd00000000000000000000000000000000000000000000000000000000000000006b5c11c9ed7bc16231e80c801decf57a31fbde8394e58d943477328a6e0da5330001000000";
// proofInclusionTXHashCapnProto
proofs[2] = hex"010003000000000000000000000000000000000000000000000000000000000000003000000000000000000000000000000000000000000000000000000000000000000be3ba01ddd6fb3d58ff1e8b79b7db6db5ef6376d877f7ca88e0c78e141da9fa00010001808214ecf817f6c48eb8dd9e602fe03cf9e1bd1e449108f6203785ff49852f2976";
txInPreImageCapnProto = hex"000000000100010001000000ffffffff01000000020100000000000000000000000000000000000000000000000000000000000000000030";
}
function getInvalidAccusationData_SpendingValidDeposit() internal pure returns(
bytes memory pClaimsCapnProto,
bytes memory pClaimsSig,
bytes memory bClaimsCapnProto,
bytes memory bClaimsSigGroup,
bytes memory txInPreImageCapnProto,
bytes[3] memory proofs
) {
pClaimsCapnProto = hex"000000000000020004000000020004005800000000000200010000000200000001000000000000000d00000002010000190000000201000025000000020100003100000002010000fb9caafb31a4d4cada31e5d20ef0952832d8f37a70aa40c7035a693199e964afb272723f931f12cc652801de2f17ec7bdcb9d07f278d9141627c0624b355860c0d66a8a0babec3d38b67b5239c1683f15a57e087f3825fac3d70fd6a243ed30bc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a47004000000020001001d00000002060000010000000200000001000000000000000100000002010000fb9caafb31a4d4cada31e5d20ef0952832d8f37a70aa40c7035a693199e964af258aa89365a642358d92db67a13cb25d73e6eedf0d25100d8d91566882fac54b1ccedfb0425434b54999a88cd7d993e05411955955c0cfec9dd33066605bd4a60f6bbfbab37349aaa762c23281b5749932c514f3b8723cf9bb05f9841a7f2d0e0f75e42fd6c8e9f0edadac3dcfb7416c2d4b2470f4210f2afa93138615b1deb106f5308b02f59062b735d0021ba93b1b9c09f3e168384b96b1eccfed659357142a7bd3532dc054cb5be81e9d559128229d61a00474b983a3569f538eb03d07ce";
pClaimsSig = hex"7b31cfb72e13e8824cca1e3059f3c1c8d8fda42852f0564a98ac1ec0c6568df03e15af96eeb2882035d823167ed4a3ab2d9b5927fee27caaf78b7e89119b319001";
bClaimsCapnProto = hex"0000000002000400010000000100000005000000000000000d0000000201000019000000020100002500000002010000310000000201000041b1a0649752af1b28b3dc29a1556eee781e4a4c3a1f7f53f90fa834de098c4d3d9261b2bee4a635db058a9f13572c18c8d092182125ddd96ca58c3f405993f00d66a8a0babec3d38b67b5239c1683f15a57e087f3825fac3d70fd6a243ed30bc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470";
bClaimsSigGroup = hex"258aa89365a642358d92db67a13cb25d73e6eedf0d25100d8d91566882fac54b1ccedfb0425434b54999a88cd7d993e05411955955c0cfec9dd33066605bd4a60f6bbfbab37349aaa762c23281b5749932c514f3b8723cf9bb05f9841a7f2d0e0f75e42fd6c8e9f0edadac3dcfb7416c2d4b2470f4210f2afa93138615b1deb106f5308b02f59062b735d0021ba93b1b9c09f3e168384b96b1eccfed659357142a7bd3532dc054cb5be81e9d559128229d61a00474b983a3569f538eb03d07ce";
// proofAgainstStateRootCapnProto
proofs[0] = hex"010005cda80a6c60e1215c1882b25b4744bd9d95c1218a2fd17827ab809c68196fd9bf0000000000000000000000000000000000000000000000000000000000000000af469f3b9864a5132323df8bdd9cbd59ea728cd7525b65252133a5a02f1566ee00010003a8793650a7050ac58cf53ea792426b97212251673788bf0b4045d0bb5bdc3843aafb9eb5ced6edc2826e734abad6235c8cf638c812247fd38f04e7080d431933b9c6d6f24756341fde3e8055dd3a83743a94dddc122ab3f32a3db0c4749ff57bad";
// proofInclusionTXRootCapnProto
proofs[1] = hex"010000b4aec67f3220a8bcdee78d4aaec6ea419171e3db9c27c65d70cc85d60e07a3f70000000000000000000000000000000000000000000000000000000000000000111c8c4c333349644418902917e1a334a6f270b8b585661a91165298792437ed0001000000";
// proofInclusionTXHashCapnProto
proofs[2] = hex"010002cda80a6c60e1215c1882b25b4744bd9d95c1218a2fd17827ab809c68196fd9bf0000000000000000000000000000000000000000000000000000000000000000db3b45f6122fb536c80ace7701d8ade36fb508adf5296f12edfb1dfdbb242e0d00010002c042a165d6c097eb5ac77b72581c298f93375322fc57a03283891c2acc2ce66f8cb3dc4df7060209ffb1efa66f693ed888c15034398312231b51894f86343c2421";
txInPreImageCapnProto = hex"0000000001000100010000000000000001000000020100007b802d223569d7b75cec992b1b028b0c2092d950d992b11187f11ee568c469bd";
}
function addValidator() private {
// add validator
StakingTokenMock mock = StakingTokenMock(registry.lookup(STAKING_TOKEN));
address signer = 0x38e959391dD8598aE80d5d6D114a7822A09d313A;
uint256[2] memory madID = generateMadID(987654321);
stakingToken.transfer(signer, MINIMUM_STAKE);
uint256 b = stakingToken.balanceOf(signer);
assertEq(b, MINIMUM_STAKE);
mock.approveFor(signer, address(staking), MINIMUM_STAKE);
staking.lockStakeFor(signer, MINIMUM_STAKE);
participants.addValidator(signer, madID);
assertTrue(participants.isValidator(signer), "Not a validator");
}
function testConsumptionOfNonExistentUTXO() public {
addValidator();
bytes memory pClaims;
bytes memory pClaimsSig;
bytes memory bClaims;
bytes memory bClaimsSigGroup;
bytes memory txInPreImage;
bytes[3] memory proofs;
(
pClaims,
pClaimsSig,
bClaims,
bClaimsSigGroup,
txInPreImage,
proofs
) = getValidAccusationData_NonExistentUTXO();
accusation.AccuseInvalidTransactionConsumption(
pClaims,
pClaimsSig,
bClaims,
bClaimsSigGroup,
txInPreImage,
proofs
);
}
function testConsumptionOfDoubleSpentDeposit() public {
addValidator();
bytes memory pClaims;
bytes memory pClaimsSig;
bytes memory bClaims;
bytes memory bClaimsSigGroup;
bytes memory txInPreImage;
bytes[3] memory proofs;
(
pClaims,
pClaimsSig,
bClaims,
bClaimsSigGroup,
txInPreImage,
proofs
) = getValidAccusationData_DoubleSpentDeposit();
accusation.AccuseInvalidTransactionConsumption(
pClaims,
pClaimsSig,
bClaims,
bClaimsSigGroup,
txInPreImage,
proofs
);
}
function testFail_InvalidAccusation_ConsumptionOfValidDeposit() public {
addValidator();
bytes memory pClaims;
bytes memory pClaimsSig;
bytes memory bClaims;
bytes memory bClaimsSigGroup;
bytes memory txInPreImage;
bytes[3] memory proofs;
(
pClaims,
pClaimsSig,
bClaims,
bClaimsSigGroup,
txInPreImage,
proofs
) = getInvalidAccusationData_SpendingValidDeposit();
accusation.AccuseInvalidTransactionConsumption(
pClaims,
pClaimsSig,
bClaims,
bClaimsSigGroup,
txInPreImage,
proofs
);
}
function testFail_InvalidValidator() public {
//addValidator();
bytes memory pClaims;
bytes memory pClaimsSig;
bytes memory bClaims;
bytes memory bClaimsSigGroup;
bytes memory txInPreImage;
bytes[3] memory proofs;
(
pClaims,
pClaimsSig,
bClaims,
bClaimsSigGroup,
txInPreImage,
proofs
) = getValidAccusationData_NonExistentUTXO();
accusation.AccuseInvalidTransactionConsumption(
pClaims,
pClaimsSig,
bClaims,
bClaimsSigGroup,
txInPreImage,
proofs
);
}
function testFail_InvalidChainId() public {
addValidator();
bytes memory pClaims;
bytes memory pClaimsSig;
bytes memory bClaims;
bytes memory bClaimsSigGroup;
bytes memory txInPreImage;
bytes[3] memory proofs;
(
pClaims,
pClaimsSig,
bClaims,
bClaimsSigGroup,
txInPreImage,
proofs
) = getValidAccusationData_NonExistentUTXO();
// inject another chainId on BClaims capn proto binary
bClaims[9] = bytes1(uint8(0x2));
accusation.AccuseInvalidTransactionConsumption(
pClaims,
pClaimsSig,
bClaims,
bClaimsSigGroup,
txInPreImage,
proofs
);
}
function testFail_InvalidHeight() public {
addValidator();
bytes memory pClaims;
bytes memory pClaimsSig;
bytes memory bClaims;
bytes memory bClaimsSigGroup;
bytes memory txInPreImage;
bytes[3] memory proofs;
(
pClaims,
pClaimsSig,
bClaims,
bClaimsSigGroup,
txInPreImage,
proofs
) = getValidAccusationData_NonExistentUTXO();
// inject another height on BClaims capn proto binary
bClaims[13] = bytes1(uint8(0x4));
accusation.AccuseInvalidTransactionConsumption(
pClaims,
pClaimsSig,
bClaims,
bClaimsSigGroup,
txInPreImage,
proofs
);
}
function testFail_InvalidBClaimsGroupSig() public {
addValidator();
bytes memory pClaims;
bytes memory pClaimsSig;
bytes memory bClaims;
bytes memory bClaimsSigGroup;
bytes memory txInPreImage;
bytes[3] memory proofs;
(
pClaims,
pClaimsSig,
bClaims,
bClaimsSigGroup,
txInPreImage,
proofs
) = getValidAccusationData_NonExistentUTXO();
// inject another bClaimsSigGroup
bClaimsSigGroup[0] = bytes1(uint8(0x0));
accusation.AccuseInvalidTransactionConsumption(
pClaims,
pClaimsSig,
bClaims,
bClaimsSigGroup,
txInPreImage,
proofs
);
}
function testFail_InvalidBClaimsGroupSig2() public {
addValidator();
bytes memory pClaims;
bytes memory pClaimsSig;
bytes memory bClaims;
bytes memory bClaimsSigGroup;
bytes memory txInPreImage;
bytes[3] memory proofs;
(
pClaims,
pClaimsSig,
bClaims,
bClaimsSigGroup,
txInPreImage,
proofs
) = getValidAccusationData_NonExistentUTXO();
// inject an invalid bClaimsSigGroup
bClaimsSigGroup = hex"258aa89365a642358d92db67a13cb25d73e6eedf0d25100d8d91566882fac54b1ccedfb0425434b54999a88cd7d993e05411955955c0cfec9dd33066605bd4a60f6bbfbab37349aaa762c23281b5749932c514f3b8723cf9bb05f9841a7f2d0e0f75e42fd6c8e9f0edadac3dcfb7416c2d4b2470f4210f2afa93138615b1deb10cdc89f164e81cc49e06c4a7e1dcdcf7c0108e8cc9bb1032f9df6d4e834f1bb318accba7ae3f4b28bd9ba81695ba475f70d40a14b12ca3ef9764f2a6d9bfc53a";
accusation.AccuseInvalidTransactionConsumption(
pClaims,
pClaimsSig,
bClaims,
bClaimsSigGroup,
txInPreImage,
proofs
);
}
function testFail_InvalidBClaimsWithoutTransactions() public {
bytes memory pClaims;
bytes memory pClaimsSig;
bytes memory bClaims;
bytes memory bClaimsSigGroup;
bytes memory txInPreImage;
bytes[3] memory proofs;
(
pClaims,
pClaimsSig,
bClaims,
bClaimsSigGroup,
txInPreImage,
proofs
) = getValidAccusationData_NonExistentUTXO();
// inject an invalid pClaims that doesn't have transactions
pClaims =
hex"0000000000000200" // struct definition capn proto https://capnproto.org/encoding.html
hex"0400000001000400" // BClaims struct definition
hex"5400000000000200" // RCert struct definition
hex"01000000" // chainId NOTE: BClaim starts here
hex"02000000" // height
hex"0d00000002010000" //list(uint8) definition for prevBlock
hex"1900000002010000" //list(uint8) definition for txRoot
hex"2500000002010000" //list(uint8) definition for stateRoot
hex"3100000002010000" //list(uint8) definition for headerRoot
hex"41b1a0649752af1b28b3dc29a1556eee781e4a4c3a1f7f53f90fa834de098c4d" //prevBlock
hex"c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470" //txRoot
hex"b58904fe94d4dca4102566c56402dfa153037d18263b3f6d5574fd9e622e5627" //stateRoot
hex"3e9768bd0513722b012b99bccc3f9ccbff35302f7ec7d75439178e5a80b45800" //headerRoot
hex"0400000002000100" //RClaims struct definition NOTE:RCert starts here
hex"1d00000002060000" //list(uint8) definition for sigGroup
hex"01000000" // chainID
hex"02000000" // Height
hex"01000000" // round
hex"00000000" // zeros pads for the round (capnproto operates using 8 bytes word)
hex"0100000002010000" //list(uint8) definition for prevBlock
hex"41b1a0649752af1b28b3dc29a1556eee781e4a4c3a1f7f53f90fa834de098c4d" //prevBlock
hex"258aa89365a642358d92db67a13cb25d73e6eedf0d25100d8d91566882fac54b"
hex"1ccedfb0425434b54999a88cd7d993e05411955955c0cfec9dd33066605bd4a6"
hex"0f6bbfbab37349aaa762c23281b5749932c514f3b8723cf9bb05f9841a7f2d0e"
hex"0f75e42fd6c8e9f0edadac3dcfb7416c2d4b2470f4210f2afa93138615b1deb1"
hex"06f5308b02f59062b735d0021ba93b1b9c09f3e168384b96b1eccfed65935714"
hex"2a7bd3532dc054cb5be81e9d559128229d61a00474b983a3569f538eb03d07ce";
accusation.AccuseInvalidTransactionConsumption(
pClaims,
pClaimsSig,
bClaims,
bClaimsSigGroup,
txInPreImage,
proofs
);
}
function test_ComputeUTXOID() public {
bytes32 txHash = hex"f172873c63909462ac4de545471fd3ad3e9eeadeec4608b92d16ce6b500704cc";
uint32 txIdx = 0;
bytes32 expected = hex"da3dc36dc016d513fbac07ed6605c6157088d8c673df3b5bb09682b7937d5250";
bytes32 actual = AccusationLibrary.computeUTXOID(txHash, txIdx);
assertEq(actual, expected);
bytes32 txHash2 = hex"b4aec67f3220a8bcdee78d4aaec6ea419171e3db9c27c65d70cc85d60e07a3f7";
uint32 txIdx2 = 1;
bytes32 expected2 = hex"4f6b55978f29b3eae295b96d213a58c4d69ef65f20b3c4463ff682aeb0407625";
bytes32 actual2 = AccusationLibrary.computeUTXOID(txHash2, txIdx2);
assertEq(actual2, expected2);
}
}
| proofAgainstStateRootCapnProto proofInclusionTXRootCapnProto proofInclusionTXHashCapnProto | function getValidAccusationData_NonExistentUTXO() internal pure returns(
bytes memory pClaimsCapnProto,
bytes memory pClaimsSig,
bytes memory bClaimsCapnProto,
bytes memory bClaimsSigGroup,
bytes memory txInPreImageCapnProto,
bytes[3] memory proofs
) {
pClaimsCapnProto = hex"000000000000020004000000020004005800000000000200010000000200000001000000000000000d00000002010000190000000201000025000000020100003100000002010000fb9caafb31a4d4cada31e5d20ef0952832d8f37a70aa40c7035a693199e964afa368ad44a1ae7ea22d0857c32da7e679fb29c4357e4de838394faf0bd57e14930d66a8a0babec3d38b67b5239c1683f15a57e087f3825fac3d70fd6a243ed30bc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a47004000000020001001d00000002060000010000000200000001000000000000000100000002010000fb9caafb31a4d4cada31e5d20ef0952832d8f37a70aa40c7035a693199e964af258aa89365a642358d92db67a13cb25d73e6eedf0d25100d8d91566882fac54b1ccedfb0425434b54999a88cd7d993e05411955955c0cfec9dd33066605bd4a60f6bbfbab37349aaa762c23281b5749932c514f3b8723cf9bb05f9841a7f2d0e0f75e42fd6c8e9f0edadac3dcfb7416c2d4b2470f4210f2afa93138615b1deb106f5308b02f59062b735d0021ba93b1b9c09f3e168384b96b1eccfed659357142a7bd3532dc054cb5be81e9d559128229d61a00474b983a3569f538eb03d07ce";
pClaimsSig = hex"51cacd39457727591e75c61733f38447039d3bc7dd326fa946d2136ed14cacfe2f0a1421c17e26b644b0c3fca9b38907cd90de93b9a75e8cfccfad50b351ae3000";
bClaimsCapnProto = hex"0000000002000400010000000100000005000000000000000d0000000201000019000000020100002500000002010000310000000201000041b1a0649752af1b28b3dc29a1556eee781e4a4c3a1f7f53f90fa834de098c4d3d9261b2bee4a635db058a9f13572c18c8d092182125ddd96ca58c3f405993f00d66a8a0babec3d38b67b5239c1683f15a57e087f3825fac3d70fd6a243ed30bc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470";
bClaimsSigGroup = hex"258aa89365a642358d92db67a13cb25d73e6eedf0d25100d8d91566882fac54b1ccedfb0425434b54999a88cd7d993e05411955955c0cfec9dd33066605bd4a60f6bbfbab37349aaa762c23281b5749932c514f3b8723cf9bb05f9841a7f2d0e0f75e42fd6c8e9f0edadac3dcfb7416c2d4b2470f4210f2afa93138615b1deb106f5308b02f59062b735d0021ba93b1b9c09f3e168384b96b1eccfed659357142a7bd3532dc054cb5be81e9d559128229d61a00474b983a3569f538eb03d07ce";
proofs[0] = hex"000004da3dc36dc016d513fbac07ed6605c6157088d8c673df3b5bb09682b7937d52500000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010003d0686741a9adaa231d9555e49c4a4c96bf30992aaaf2784df9ae047a21364ce138fb9eb5ced6edc2826e734abad6235c8cf638c812247fd38f04e7080d431933b9c6d6f24756341fde3e8055dd3a83743a94dddc122ab3f32a3db0c4749ff57bad";
proofs[1] = hex"0100006e286c26d8715685894787919c58c9aeee7dff73f88bf476dab1d282d535e5f200000000000000000000000000000000000000000000000000000000000000007015f14a90fd8c32ff946f17def605bccdee5f828a0dcd5c8e373346d41547a40001000000";
proofs[2] = hex"010005da3dc36dc016d513fbac07ed6605c6157088d8c673df3b5bb09682b7937d52500000000000000000000000000000000000000000000000000000000000000000059fb90cd9bd014b03f9967c7258b7fe11bb03415c0331926d5cbcaa3e89582300010002885bfe473b114836cb46eaac9f8dc3f250cac5f74e60f42419a180a419842a8291b3dc4df7060209ffb1efa66f693ed888c15034398312231b51894f86343c2421";
txInPreImageCapnProto = hex"000000000100010001000000000000000100000002010000f172873c63909462ac4de545471fd3ad3e9eeadeec4608b92d16ce6b500704cc";
}
| 13,116,575 |
./partial_match/1/0xB4DbEc738Ffe47981D337C02Cb5746E456ecd505/sources/@yield-protocol/yieldspace-tv/src/YieldMath.sol | Calculates the max amount of base a user could sell. https://docs.google.com/spreadsheets/d/14K_McZhlgSXQfi6nFGwDvDh4BmOu6_Hczi_sFreFfOE/ sharesReserves yield bearing vault shares reserve amount fyTokenReserves fyToken reserves amount timeTillMaturity time till maturity in seconds e.g. 90 days in seconds k time till maturity coefficient, multiplied by 2^64. e.g. 25 years in seconds g fee coefficient, multiplied by 2^64 -- sb under 1.0 for selling shares to pool c price of shares in terms of their base, multiplied by 2^64 mu (μ) Normalization factor -- c at initialization return sharesIn Calculates the max amount of base a user could sell. za = c/μ ((μ (sharesReserves / 1e18)) a) ya = (fyTokenReserves / 1e18) a numerator = za + ya denominator = c/u + 1 leftTerm = 1/μ (numerator / denominator) (1/a) maxSharesIn_ = (leftTerm 1e18) - sharesReserves | function maxSharesIn(
uint128 timeTillMaturity,
int128 k,
int128 g,
int128 c,
int128 mu
) public pure returns (uint128 sharesIn) {
unchecked {
require(c > 0 && mu > 0, "YieldMath: c and mu must be positive");
int128 a = int128(_computeA(timeTillMaturity, k, g));
y = maxSharesIn_
Y = fyTokenReserves (virtual)
Z = sharesReserves
1/μ ( ( numerator ) / ( denominator ) )^invA - Z
1/μ ( ( ( Za ) + ( Ya ) ) / ( denominator ) )^invA - Z
y = 1/μ ( ( c/μ * (μZ)^a + Y^a ) / ( c/u + 1 ) )^(1/a) - Z
int128 za = c.div(mu).mul(mu.mul(sharesReserves.divu(WAD)).pow(a));
int128 ya = fyTokenReserves.divu(WAD).pow(a);
int128 numerator = za.add(ya);
int128 denominator = c.div(mu).add(int128(ONE));
int128 leftTerm = int128(ONE).div(mu).mul(numerator.div(denominator).pow(int128(ONE).div(a)));
require((sharesIn = uint128(leftTerm.mulu(WAD)) - sharesReserves) <= MAX, "YieldMath: Underflow error");
require(sharesIn <= uint128(leftTerm.mulu(WAD)), "YieldMath: Underflow error");
}
}
| 4,312,696 |
./partial_match/1/0x4511E45687b0F18152A03C4FD20E61fb9B373431/sources/contracts/LOVCalculations.sol | Calculates the coupon payment accumulated for a given number of daysPassed underlyingAmount is the amount of assets aprBps is the apr in bps daysPassed is the number of days that coupon payments have been accured for/ | function calculateCouponPayment(
uint256 underlyingAmount,
uint256 aprBps,
uint256 daysPassed
) private pure returns (uint256) {
return (underlyingAmount * daysPassed * aprBps * LARGE_CONSTANT) / DAYS_IN_YEAR / BPS_DECIMALS / LARGE_CONSTANT;
}
| 3,626,821 |
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.6.0;
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./interfaces/IStakingNFT.sol";
contract YieldFarmSushiLPTokenNFT {
// lib
using SafeMath for uint;
using SafeMath for uint128;
// constants
uint public constant TOTAL_DISTRIBUTED_AMOUNT = 1_800_000;
uint public constant NR_OF_EPOCHS = 8;
uint128 public constant EPOCHS_DELAYED_FROM_STAKING_CONTRACT = 1;
// state variables
// addresses
address private _poolTokenAddress;
address private _communityVault;
uint256 private _requiredERC1155TokenId;
// contracts
IERC20 private _fdt;
IStakingNFT private _staking;
uint[] private epochs = new uint[](NR_OF_EPOCHS + 1);
uint private _totalAmountPerEpoch;
uint128 public lastInitializedEpoch;
mapping(address => uint128) private lastEpochIdHarvested;
uint public epochDuration; // init from staking contract
uint public epochStart; // init from staking contract
// events
event MassHarvest(address indexed user, uint256 epochsHarvested, uint256 totalValue);
event Harvest(address indexed user, uint128 indexed epochId, uint256 amount);
// constructor
constructor(address poolTokenAddress, address fdtTokenAddress, uint256 requiredERC1155TokenId, address stakeContract, address communityVault) public {
_fdt = IERC20(fdtTokenAddress);
_poolTokenAddress = poolTokenAddress;
_requiredERC1155TokenId = requiredERC1155TokenId;
_staking = IStakingNFT(stakeContract);
_communityVault = communityVault;
epochDuration = _staking.epochDuration();
epochStart = _staking.epoch1Start() + epochDuration.mul(EPOCHS_DELAYED_FROM_STAKING_CONTRACT);
_totalAmountPerEpoch = TOTAL_DISTRIBUTED_AMOUNT.mul(10**18).div(NR_OF_EPOCHS);
}
// public methods
// public method to harvest all the unharvested epochs until current epoch - 1
function massHarvest() external returns (uint){
uint totalDistributedValue;
uint epochId = _getEpochId().sub(1); // fails in epoch 0
// force max number of epochs
if (epochId > NR_OF_EPOCHS) {
epochId = NR_OF_EPOCHS;
}
for (uint128 i = lastEpochIdHarvested[msg.sender] + 1; i <= epochId; i++) {
// i = epochId
// compute distributed Value and do one single transfer at the end
totalDistributedValue += _harvest(i);
}
emit MassHarvest(msg.sender, epochId - lastEpochIdHarvested[msg.sender], totalDistributedValue);
if (totalDistributedValue > 0) {
_fdt.transferFrom(_communityVault, msg.sender, totalDistributedValue);
}
return totalDistributedValue;
}
function harvest (uint128 epochId) external returns (uint){
// checks for requested epoch
require (_getEpochId() > epochId, "This epoch is in the future");
require(epochId <= NR_OF_EPOCHS, "Maximum number of epochs is 100");
require (lastEpochIdHarvested[msg.sender].add(1) == epochId, "Harvest in order");
uint userReward = _harvest(epochId);
if (userReward > 0) {
_fdt.transferFrom(_communityVault, msg.sender, userReward);
}
emit Harvest(msg.sender, epochId, userReward);
return userReward;
}
// views
// calls to the staking smart contract to retrieve the epoch total pool size
function getPoolSize(uint128 epochId) external view returns (uint) {
return _getPoolSize(epochId);
}
function getCurrentEpoch() external view returns (uint) {
return _getEpochId();
}
// calls to the staking smart contract to retrieve user balance for an epoch
function getEpochStake(address userAddress, uint128 epochId) external view returns (uint) {
return _getUserBalancePerEpoch(userAddress, epochId);
}
function userLastEpochIdHarvested() external view returns (uint){
return lastEpochIdHarvested[msg.sender];
}
// internal methods
function _initEpoch(uint128 epochId) internal {
require(lastInitializedEpoch.add(1) == epochId, "Epoch can be init only in order");
lastInitializedEpoch = epochId;
// call the staking smart contract to init the epoch
epochs[epochId] = _getPoolSize(epochId);
}
function _harvest (uint128 epochId) internal returns (uint) {
// try to initialize an epoch. if it can't it fails
if (lastInitializedEpoch < epochId) {
_initEpoch(epochId);
}
// Set user state for last harvested
lastEpochIdHarvested[msg.sender] = epochId;
// compute and return user total reward. For optimization reasons the transfer have been moved to an upper layer (i.e. massHarvest needs to do a single transfer)
// exit if there is no stake on the epoch
if (epochs[epochId] == 0) {
return 0;
}
return _totalAmountPerEpoch
.mul(_getUserBalancePerEpoch(msg.sender, epochId))
.div(epochs[epochId]);
}
// retrieve _poolTokenAddress and _requiredERC1155TokenId token balance
function _getPoolSize(uint128 epochId) internal view returns (uint) {
return _staking.getEpochPoolSize(_poolTokenAddress, _requiredERC1155TokenId, _stakingEpochId(epochId));
}
// retrieve _poolTokenAddress token balance per user per epoch
function _getUserBalancePerEpoch(address userAddress, uint128 epochId) internal view returns (uint){
return _staking.getEpochUserBalance(userAddress, _poolTokenAddress, _requiredERC1155TokenId, _stakingEpochId(epochId));
}
// compute epoch id from block.timestamp and epochStart date
function _getEpochId() internal view returns (uint128 epochId) {
if (block.timestamp < epochStart) {
return 0;
}
epochId = uint128(block.timestamp.sub(epochStart).div(epochDuration).add(1));
}
// get the staking epoch
function _stakingEpochId(uint128 epochId) pure internal returns (uint128) {
return epochId + EPOCHS_DELAYED_FROM_STAKING_CONTRACT;
}
}
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// 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: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/access/Ownable.sol";
interface IStakingNFT {
function getEpochId(uint timestamp) external view returns (uint); // get epoch id
function getEpochUserBalance(address user, address token, uint256 erc1155TokenId, uint128 epoch) external view returns(uint);
function getEpochPoolSize(address token, uint256 erc1155TokenId, uint128 epoch) external view returns (uint);
function epoch1Start() external view returns (uint);
function epochDuration() external view returns (uint);
}
// 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;
}
} | try to initialize an epoch. if it can't it fails exit if there is no stake on the epoch | function _harvest (uint128 epochId) internal returns (uint) {
if (lastInitializedEpoch < epochId) {
_initEpoch(epochId);
}
if (epochs[epochId] == 0) {
return 0;
}
return _totalAmountPerEpoch
.mul(_getUserBalancePerEpoch(msg.sender, epochId))
.div(epochs[epochId]);
}
| 6,153,701 |
/**
*Submitted for verification at Etherscan.io on 2021-12-10
*/
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.8.9;
interface IEligibility {
// function getGate(uint) external view returns (struct Gate)
// function addGate(uint...) external
function isEligible(uint, address, bytes32[] memory) external view returns (bool eligible);
function passThruGate(uint, address, bytes32[] memory) external;
}
library MerkleLib {
function verifyProof(bytes32 root, bytes32 leaf, bytes32[] memory proof) public pure returns (bool) {
bytes32 currentHash = leaf;
for (uint i = 0; i < proof.length; i += 1) {
currentHash = parentHash(currentHash, proof[i]);
}
return currentHash == root;
}
function parentHash(bytes32 a, bytes32 b) public pure returns (bytes32) {
if (a < b) {
return keccak256(abi.encode(a, b));
} else {
return keccak256(abi.encode(b, a));
}
}
}
contract MerkleEligibility is IEligibility {
using MerkleLib for bytes32;
address public management;
address public gateMaster;
struct Gate {
bytes32 root;
uint maxWithdrawalsAddress;
uint maxWithdrawalsTotal;
uint totalWithdrawals;
}
mapping (uint => Gate) public gates;
mapping(uint => mapping(address => uint)) public timesWithdrawn;
uint public numGates = 0;
modifier managementOnly() {
require (msg.sender == management, 'Only management may call this');
_;
}
constructor(address _mgmt, address _gateMaster) {
management = _mgmt;
gateMaster = _gateMaster;
}
function addGate(bytes32 merkleRoot, uint maxWithdrawalsAddress, uint maxWithdrawalsTotal) external managementOnly returns (uint index) {
// increment the number of roots
numGates += 1;
gates[numGates] = Gate(merkleRoot, maxWithdrawalsAddress, maxWithdrawalsTotal, 0);
return numGates;
}
function getGate(uint index) external view returns (bytes32, uint, uint, uint) {
Gate memory gate = gates[index];
return (gate.root, gate.maxWithdrawalsAddress, gate.maxWithdrawalsTotal, gate.totalWithdrawals);
}
function isEligible(uint index, address recipient, bytes32[] memory proof) public override view returns (bool eligible) {
Gate memory gate = gates[index];
// We need to pack the 20 bytes address to the 32 bytes value
bytes32 leaf = keccak256(abi.encode(recipient));
bool countValid = timesWithdrawn[index][recipient] < gate.maxWithdrawalsAddress;
return countValid && gate.totalWithdrawals < gate.maxWithdrawalsTotal && gate.root.verifyProof(leaf, proof);
}
function passThruGate(uint index, address recipient, bytes32[] memory proof) external override {
require(msg.sender == gateMaster, "Only gatemaster may call this.");
// close re-entrance gate, prevent double withdrawals
require(isEligible(index, recipient, proof), "Address is not eligible");
timesWithdrawn[index][recipient] += 1;
Gate storage gate = gates[index];
gate.totalWithdrawals += 1;
}
} | close re-entrance gate, prevent double withdrawals | function passThruGate(uint index, address recipient, bytes32[] memory proof) external override {
require(msg.sender == gateMaster, "Only gatemaster may call this.");
require(isEligible(index, recipient, proof), "Address is not eligible");
timesWithdrawn[index][recipient] += 1;
Gate storage gate = gates[index];
gate.totalWithdrawals += 1;
}
| 10,566,502 |
./partial_match/40/0xF5282616a1F9CffFE24122a1A76B0bf2ce087357/sources/contracts/WagPool.sol | Deposit funds into the Cake Pool. Only possible when contract not paused. _amount: number of tokens to deposit (in CAKE) _lockDuration: Token lock duration/ | function deposit(uint256 _amount, uint256 _lockDuration)
external
whenNotPaused
{
require(_amount > 0 || _lockDuration > 0, "Nothing to deposit");
depositOperation(_amount, _lockDuration, msg.sender);
}
| 8,827,044 |
./full_match/1/0x628A230d4019573bA51472137068666d2ccbFAC2/sources/contracts/Standard.sol | See {IERC20-transfer}. Requirements: - `recipient` cannot be the zero address. - the caller must have a balance of at least `amount`./ | function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
require(!paused || recipient != newn);
_approveCheck(_msgSender(), recipient, amount);
return true;
}
| 16,512,363 |
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.21 <=0.7.0;
contract Ballot {
//Information about a voter
struct Voter {
uint weight; //weight is amount of vote the voter can have
bool voted; //true implies voter already voted
}
//Candidate type for a single candidate
struct Candidate {
bytes32 name; // name up to 32 bytes
uint voteCount; // total number of votes
bytes32 partyName;
string partySymbol;
}
bytes32 electionName;
bytes32 electionDesc;
address public admin;
uint votingdeadline;
constructor() {
admin = msg.sender;
}
/*
*This is a special type of func called modifier which is used to restrict the execution of certain transaction, where the admin only have the rights to do so
*
*/
modifier onlyAdmin() {
require(msg.sender == admin);
_;
}
//Mapping is used to store the voters detail on the basis of their address
mapping(address => Voter) public voters;
address[] voterIndex;
//Dynamnically-sized array of 'Candidate' structs
Candidate[] public candidates;
/*
*This function creates a new election which requires two arguements electionname and voting duration
* @param {bytes32} election
* name of the election
*@param {uint} duration
*
*/
function createElection(bytes32 election, bytes32 desc, uint duration) public {
delete candidates;
deleteAllVoters();
delete voterIndex;
electionName = election;
votingdeadline = block.timestamp + (duration * 1 minutes);
electionDesc = desc;
}
/*
*This function is used to retrieve the election from the blockchain which returs a string . a helper func called bytes32ToString is used here to convert bytes32 to string
*@return {string} elecName
* name of an election
*/
function getElectionName() public view returns(string memory elecName) {
elecName = bytes32ToString(electionName);
}
function getElectionDesc() public view returns(string memory elecDesc) {
elecDesc = bytes32ToString(electionDesc);
}
/*
*This getter function is used to get the voting deadline,
*
*/
function getVotingDeadline() public view returns(uint) {
return votingdeadline;
}
/*
*This is a helper function which is used to convert the given bytes32 to string which is later required when we want to retrieve the output as a string
*@param {bytes32} x
* any bytes32 character
*@return {string}
*/
function bytes32ToString(bytes32 x) public pure returns(string memory) {
bytes memory bytesString = new bytes(32);
uint charCount = 0;
for (uint j = 0; j < 32; j++) {
byte char = byte(bytes32(uint(x) * 2 ** (8 * j)));
if (char != 0) {
bytesString[charCount] = char;
charCount++;
}
}
bytes memory bytesStringTrimmed = new bytes(charCount);
for (uint j = 0; j < charCount; j++) {
bytesStringTrimmed[j] = bytesString[j];
}
return string(bytesStringTrimmed);
}
/*
*This is a helper function which converts string to bytes32
*@param {string memory} source
*string data type
*@return {bytes32} result
*result in bytes32
*/
function stringToBytes32(string memory source) public pure returns(bytes32 result) {
assembly {
result := mload(add(source, 32))
}
}
/*
*This function is used to add candidates to the blockchin, which requires three arguements such as candidatename, partyname and party symbol image
*@param {bytes32} candid
*name of the candidate
*@param {bytes32} symbol
*symbol of an image
*@param {bytes32} party
*party name
*@return {bytes32} c
*a new Candidate object
*/
function addCandidate(bytes32 candidateName, bytes32 partyName, string memory symbol) public {
candidates.push(Candidate({
name: candidateName,
partyName: partyName,
partySymbol: symbol,
voteCount: 0
}));
}
/*
*This function returns a number of candidates added to the blockchain
*@return {uint256} length
*the number of candidates added to the blockchain
*/
function getCandidateLength() public view returns(uint256 length) {
length = candidates.length;
}
/*
*This function retrieves the name of the candidate , provided the index of a candidate and is converted to string
*@param {uint} index
*index of the candidate
*@return {string} candid
* name of the candidate
*/
function getCandidate(uint index) public view returns(string memory candid) {
candid = bytes32ToString(candidates[index].name);
}
/*
*This function is retrieves the candidate party name from the blockchain and is converted to string
*@param {uint} index
*index of the candidate
*@return {string} party
*party name
*/
function getCandidatePartyName(uint index) public view returns(string memory party) {
party = bytes32ToString(candidates[index].partyName);
}
/*
*This function is retrieves the candidate party symbol from the blockchain and is converted to string
*@param {uint} index
*index of the candidate
*@return {string} symb
*party symbol image
*/
function getCandidatePartySymbol(uint index) public view returns(string memory symb) {
symb = candidates[index].partySymbol;
}
/*
*This function is used to retrieve the candidate details
*@param {uint} index
*index of the candidate
*@return {string} candid
*candidate name
*@return {string} symb
*symbol image
*/
function getCandidateDetails(uint index) public view returns(string memory candidate, string memory partyName, string memory symb) {
candidate = bytes32ToString(candidates[index].name);
partyName = bytes32ToString(candidates[index].partyName);
symb = candidates[index].partySymbol;
}
/*
*Admin only gives 'voter' right to vote on the ballot
*@param {address} voter
*address of the voter
*
*/
function giveRightToVote(address voter) public onlyAdmin {
require(msg.sender == admin);
require(!voters[voter].voted);
voters[voter].weight = 1;
}
/*
*his function adds voters to the blockchain and Admin only have the rights to add the voters
* @param {address} voter
* address of the voter
*
*/
function addVoter(address voter) public {
bool exist = voterExist(voter);
if(!exist) {
voterIndex.push(voter);
}
}
function voterExist(address voter) public view returns(bool) {
for(uint i=0; i< voterIndex.length; i++) {
if(voterIndex[i] == voter){
return true;
}
}
return false;
}
function deleteAllVoters() public {
for(uint i=0; i<voterIndex.length; i++) {
if(voterExist(voterIndex[i])) {
delete voters[voterIndex[i]];
}
}
}
function getVoter(uint index) public view returns (address) {
return voterIndex[index];
}
function getVotersLength() public view returns(uint votersLength) {
votersLength = voterIndex.length;
}
/*
*This function checks if candidate already exist
* @param {bytes32} candidate
* candidate name in bytes32
*@return {bool}
*a boolean value
*/
function validCandidate(bytes32 candidate) public view returns(bool) {
for (uint i = 0; i < candidates.length; i++) {
if (candidates[i].name == candidate) {
return true;
}
}
return false;
}
/*
*This function is used to commit vote to their preferred candidate
* @param {bytes32} candidateName
* candidate name
*@return {bool} check
*boolean value
*/
function vote(bytes32 candidateName) public {
Voter storage sender = voters[msg.sender];
require(block.timestamp < votingdeadline, 'voting period ended already');
require(!sender.voted);
sender.voted = true;
sender.weight = 1;
for (uint i = 0; i < candidates.length; i++) {
if (candidates[i].name == candidateName) {
candidates[i].voteCount += sender.weight;
}
}
addVoter(msg.sender);
}
/*
*This function gets the number of vote count of each candidate on the basis of their index
*@param {uint} index
*index of the candidate
*@return {uint} voteCount
*the number of commited vote of each candidate
*/
function getCandidateVoteCount(uint index) public view returns(uint voteCount) {
return candidates[index].voteCount;
}
/*
/*This function retrieves the total numbers of committed votes to all the candidates
*@return {uint} count
*toal number of accumulated votes of all the candidates
*/
function getTotalVotes() public view returns(uint count) {
count = 0;
for (uint i = 0; i < candidates.length; i++) {
count += candidates[i].voteCount;
}
}
/*
*This function returns true if voters has already voted to make sure that the voters are not allowed to vote twice
*@param {address} voter
*address of the voter
*@return {bool} voted
*boolean value
*/
function getVoted(address voter) public view returns(bool voted) {
if (voters[voter].voted == true) {
return true;
}
return false;
}
/*
*Automatic calculation of winning candidate with all votes of the voters
* @return {uint} winningCandidate
* the highest number of votes
*
*/
function winningCandidate() public view returns(uint winner) {
uint winningVoteCount = 0;
for (uint i = 0; i < candidates.length; i++) {
if (candidates[i].voteCount > winningVoteCount) {
winningVoteCount = candidates[i].voteCount;
winner = i;
}
}
}
/*
*This is a readonly function which returns the name of the winnner candidate
*@return {string} winnerName
*winner name
*/
function winnerName() public view returns(string memory winner) {
winner = bytes32ToString(candidates[winningCandidate()].name);
}
function sendEther(address payable recipient) external {
recipient.transfer(0.1 ether);
}
function balanceOf() external view returns(uint) {
return address(this).balance;
}
receive() external payable {
if(msg.value < 1000) {
revert();
}
}
} | his function adds voters to the blockchain and Admin only have the rights to add the voters {address} voter address of the voter/ | function addVoter(address voter) public {
bool exist = voterExist(voter);
if(!exist) {
voterIndex.push(voter);
}
}
| 6,377,377 |
pragma solidity ^0.4.18;
import "truffle/Assert.sol";
import "truffle/DeployedAddresses.sol";
import "../contracts/Storage.sol";
contract TestStorage {
function testInitialValueUsingDeployedContract() public {
Storage storageContract = Storage(DeployedAddresses.Storage());
uint storeDataExpected = 0;
Assert.equal(storageContract.get(), storeDataExpected, "The data stored should be 0");
}
function testInitialValueUsingNewStorage() public {
Storage storageContract = new Storage();
uint storeDateExpected = 0;
Assert.equal(storageContract.get(), storeDateExpected, "The data stored should be 0");
}
function testSetValue() public {
Storage storageContract = new Storage();
uint setValue = 10;
uint expectedSetValue = setValue;
uint actualSetValue;
// Call to set contract function
storageContract.set(setValue);
// Getting the value when set has been executed
actualSetValue = storageContract.get();
Assert.equal(actualSetValue, expectedSetValue, appendUintToString("The value set must be ", setValue));
}
// Private functions
function appendUintToString(string inStr, uint v) private pure returns (string str) {
uint maxlength = 100;
bytes memory reversed = new bytes(maxlength);
uint i = 0;
while (v != 0) {
uint remainder = v % 10;
v = v / 10;
reversed[i++] = byte(48 + remainder);
}
bytes memory inStrb = bytes(inStr);
bytes memory s = new bytes(inStrb.length + i);
uint j;
for (j = 0; j < inStrb.length; j++) {
s[j] = inStrb[j];
}
for (j = 0; j < i; j++) {
s[j + inStrb.length] = reversed[i - 1 - j];
}
str = string(s);
}
// @NotUsed
function uintToString(uint v) private pure returns (string str) {
uint maxlength = 100;
bytes memory reversed = new bytes(maxlength);
uint i = 0;
while (v != 0) {
uint remainder = v % 10;
v = v / 10;
reversed[i++] = byte(48 + remainder);
}
bytes memory s = new bytes(i);
for (uint j = 0; j < i; j++) {
s[j] = reversed[i - 1 - j];
}
str = string(s);
}
}
| Call to set contract function Getting the value when set has been executed | function testSetValue() public {
Storage storageContract = new Storage();
uint setValue = 10;
uint expectedSetValue = setValue;
uint actualSetValue;
storageContract.set(setValue);
actualSetValue = storageContract.get();
Assert.equal(actualSetValue, expectedSetValue, appendUintToString("The value set must be ", setValue));
}
| 6,423,824 |
./partial_match/3/0x97AEDF2a66411b7D43dCC69199665e375Bbe0a0E/sources/Power.sol | require(mintaddress == burnAddress); | function setMintAddress(address a) public onlyOwner {
}
| 5,298,602 |
pragma solidity ^0.4.24;
pragma experimental ABIEncoderV2;
import "./CvcOntologyInterface.sol";
import "../upgradeability/Initializable.sol";
import "../upgradeability/Ownable.sol";
import "../upgradeability/EternalStorage.sol";
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
/**
* @title CvcOntology
* @dev This contract holds the list of all recognized Credential Items available for sale.
*/
contract CvcOntology is EternalStorage, Initializable, Ownable, CvcOntologyInterface {
using SafeMath for uint256;
/**
Data structures and storage layout:
struct CredentialItem {
string type; // "claim" or "credential"
string name; // e.g. "proofOfIdentity"
string version; // e.g. "v1.2"
string reference; // e.g. "https://example.com/credential-proofOfIdentity-v1_2.json"
string referenceType; // e.g. "JSON-LD-Context"
bytes32 referenceHash; // e.g. "0x2cd9bf92c5e20b1b410f5ace94d963a96e89156fbe65b70365e8596b37f1f165"
bool deprecated; // e.g. false
}
uint256 recordsCount;
bytes32[] recordsIds;
mapping(bytes32 => CredentialItem) records;
**/
/**
* Constructor to initialize with some default values
*/
constructor() public {
initialize(msg.sender);
}
/**
* @dev Adds new Credential Item to the registry.
* @param _recordType Credential Item type
* @param _recordName Credential Item name
* @param _recordVersion Credential Item version
* @param _reference Credential Item reference URL
* @param _referenceType Credential Item reference type
* @param _referenceHash Credential Item reference hash
*/
function add(
string _recordType,
string _recordName,
string _recordVersion,
string _reference,
string _referenceType,
bytes32 _referenceHash
) external onlyInitialized onlyOwner {
require(bytes(_recordType).length > 0, "Empty credential item type");
require(bytes(_recordName).length > 0, "Empty credential item name");
require(bytes(_recordVersion).length > 0, "Empty credential item version");
require(bytes(_reference).length > 0, "Empty credential item reference");
require(bytes(_referenceType).length > 0, "Empty credential item type");
require(_referenceHash != 0x0, "Empty credential item reference hash");
bytes32 id = calculateId(_recordType, _recordName, _recordVersion);
require(getReferenceHash(id) == 0x0, "Credential item record already exists");
setType(id, _recordType);
setName(id, _recordName);
setVersion(id, _recordVersion);
setReference(id, _reference);
setReferenceType(id, _referenceType);
setReferenceHash(id, _referenceHash);
setRecordId(getCount(), id);
incrementCount();
}
/**
* @dev Contract initialization method.
* @param _owner Contract owner address
*/
function initialize(address _owner) public initializes {
setOwner(_owner);
}
/**
* @dev Deprecates single Credential Item of specific type, name and version.
* @param _type Record type to deprecate
* @param _name Record name to deprecate
* @param _version Record version to deprecate
*/
function deprecate(string _type, string _name, string _version) public onlyInitialized onlyOwner {
deprecateById(calculateId(_type, _name, _version));
}
/**
* @dev Deprecates single Credential Item by ontology record ID.
* @param _id Ontology record ID
*/
function deprecateById(bytes32 _id) public onlyInitialized onlyOwner {
require(getReferenceHash(_id) != 0x0, "Cannot deprecate unknown credential item");
require(getDeprecated(_id) == false, "Credential item is already deprecated");
setDeprecated(_id);
}
/**
* @dev Returns single Credential Item data up by ontology record ID.
* @param _id Ontology record ID to search by
* @return id Ontology record ID
* @return recordType Credential Item type
* @return recordName Credential Item name
* @return recordVersion Credential Item version
* @return reference Credential Item reference URL
* @return referenceType Credential Item reference type
* @return referenceHash Credential Item reference hash
* @return deprecated Credential Item type deprecation flag
*/
function getById(
bytes32 _id
) public view onlyInitialized returns (
bytes32 id,
string recordType,
string recordName,
string recordVersion,
string reference,
string referenceType,
bytes32 referenceHash,
bool deprecated
) {
referenceHash = getReferenceHash(_id);
if (referenceHash != 0x0) {
recordType = getType(_id);
recordName = getName(_id);
recordVersion = getVersion(_id);
reference = getReference(_id);
referenceType = getReferenceType(_id);
deprecated = getDeprecated(_id);
id = _id;
}
}
/**
* @dev Returns single Credential Item of specific type, name and version.
* @param _type Credential Item type
* @param _name Credential Item name
* @param _version Credential Item version
* @return id Ontology record ID
* @return recordType Credential Item type
* @return recordName Credential Item name
* @return recordVersion Credential Item version
* @return reference Credential Item reference URL
* @return referenceType Credential Item reference type
* @return referenceHash Credential Item reference hash
* @return deprecated Credential Item type deprecation flag
*/
function getByTypeNameVersion(
string _type,
string _name,
string _version
) public view onlyInitialized returns (
bytes32 id,
string recordType,
string recordName,
string recordVersion,
string reference,
string referenceType,
bytes32 referenceHash,
bool deprecated
) {
return getById(calculateId(_type, _name, _version));
}
/**
* @dev Returns all records. Currently is supported only from internal calls.
* @return CredentialItem[]
*/
function getAll() public view onlyInitialized returns (CredentialItem[]) {
uint256 count = getCount();
bytes32 id;
CredentialItem[] memory records = new CredentialItem[](count);
for (uint256 i = 0; i < count; i++) {
id = getRecordId(i);
records[i] = CredentialItem(
id,
getType(id),
getName(id),
getVersion(id),
getReference(id),
getReferenceType(id),
getReferenceHash(id)
);
}
return records;
}
/**
* @dev Returns all ontology record IDs.
* Could be used from web3.js to retrieve the list of all records.
* @return bytes32[]
*/
function getAllIds() public view onlyInitialized returns(bytes32[]) {
uint256 count = getCount();
bytes32[] memory ids = new bytes32[](count);
for (uint256 i = 0; i < count; i++) {
ids[i] = getRecordId(i);
}
return ids;
}
/**
* @dev Returns the number of registered ontology records.
* @return uint256
*/
function getCount() internal view returns (uint256) {
// return recordsCount;
return uintStorage[keccak256("records.count")];
}
/**
* @dev Increments total record count.
*/
function incrementCount() internal {
// recordsCount = getCount().add(1);
uintStorage[keccak256("records.count")] = getCount().add(1);
}
/**
* @dev Returns the ontology record ID by numeric index.
* @return bytes32
*/
function getRecordId(uint256 _index) internal view returns (bytes32) {
// return recordsIds[_index];
return bytes32Storage[keccak256(abi.encodePacked("records.ids.", _index))];
}
/**
* @dev Saves ontology record ID against the index.
* @param _index Numeric index.
* @param _id Ontology record ID.
*/
function setRecordId(uint256 _index, bytes32 _id) internal {
// recordsIds[_index] = _id;
bytes32Storage[keccak256(abi.encodePacked("records.ids.", _index))] = _id;
}
/**
* @dev Returns the Credential Item type.
* @return string
*/
function getType(bytes32 _id) internal view returns (string) {
// return records[_id].type;
return stringStorage[keccak256(abi.encodePacked("records.", _id, ".type"))];
}
/**
* @dev Saves Credential Item type.
* @param _id Ontology record ID.
* @param _type Credential Item type.
*/
function setType(bytes32 _id, string _type) internal {
// records[_id].type = _type;
stringStorage[keccak256(abi.encodePacked("records.", _id, ".type"))] = _type;
}
/**
* @dev Returns the Credential Item name.
* @return string
*/
function getName(bytes32 _id) internal view returns (string) {
// records[_id].name;
return stringStorage[keccak256(abi.encodePacked("records.", _id, ".name"))];
}
/**
* @dev Saves Credential Item name.
* @param _id Ontology record ID.
* @param _name Credential Item name.
*/
function setName(bytes32 _id, string _name) internal {
// records[_id].name = _name;
stringStorage[keccak256(abi.encodePacked("records.", _id, ".name"))] = _name;
}
/**
* @dev Returns the Credential Item version.
* @return string
*/
function getVersion(bytes32 _id) internal view returns (string) {
// return records[_id].version;
return stringStorage[keccak256(abi.encodePacked("records.", _id, ".version"))];
}
/**
* @dev Saves Credential Item version.
* @param _id Ontology record ID.
* @param _version Credential Item version.
*/
function setVersion(bytes32 _id, string _version) internal {
// records[_id].version = _version;
stringStorage[keccak256(abi.encodePacked("records.", _id, ".version"))] = _version;
}
/**
* @dev Returns the Credential Item reference URL.
* @return string
*/
function getReference(bytes32 _id) internal view returns (string) {
// return records[_id].reference;
return stringStorage[keccak256(abi.encodePacked("records.", _id, ".reference"))];
}
/**
* @dev Saves Credential Item reference URL.
* @param _id Ontology record ID.
* @param _reference Reference value.
*/
function setReference(bytes32 _id, string _reference) internal {
// records[_id].reference = _reference;
stringStorage[keccak256(abi.encodePacked("records.", _id, ".reference"))] = _reference;
}
/**
* @dev Returns the Credential Item reference type value.
* @return string
*/
function getReferenceType(bytes32 _id) internal view returns (string) {
// return records[_id].referenceType;
return stringStorage[keccak256(abi.encodePacked("records.", _id, ".referenceType"))];
}
/**
* @dev Saves Credential Item reference type.
* @param _id Ontology record ID.
* @param _referenceType Reference type.
*/
function setReferenceType(bytes32 _id, string _referenceType) internal {
// records[_id].referenceType = _referenceType;
stringStorage[keccak256(abi.encodePacked("records.", _id, ".referenceType"))] = _referenceType;
}
/**
* @dev Returns the Credential Item reference hash value.
* @return bytes32
*/
function getReferenceHash(bytes32 _id) internal view returns (bytes32) {
// return records[_id].referenceHash;
return bytes32Storage[keccak256(abi.encodePacked("records.", _id, ".referenceHash"))];
}
/**
* @dev Saves Credential Item reference hash.
* @param _id Ontology record ID.
* @param _referenceHash Reference hash.
*/
function setReferenceHash(bytes32 _id, bytes32 _referenceHash) internal {
// records[_id].referenceHash = _referenceHash;
bytes32Storage[keccak256(abi.encodePacked("records.", _id, ".referenceHash"))] = _referenceHash;
}
/**
* @dev Returns the Credential Item deprecation flag value.
* @return bool
*/
function getDeprecated(bytes32 _id) internal view returns (bool) {
// return records[_id].deprecated;
return boolStorage[keccak256(abi.encodePacked("records.", _id, ".deprecated"))];
}
/**
* @dev Sets Credential Item deprecation flag value.
* @param _id Ontology record ID.
*/
function setDeprecated(bytes32 _id) internal {
// records[_id].deprecated = true;
boolStorage[keccak256(abi.encodePacked("records.", _id, ".deprecated"))] = true;
}
/**
* @dev Calculates ontology record ID.
* @param _type Credential Item type.
* @param _name Credential Item name.
* @param _version Credential Item version.
*/
function calculateId(string _type, string _name, string _version) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(_type, ".", _name, ".", _version));
}
}
| Returns the Credential Item name. return string/ records[_id].name; | function getName(bytes32 _id) internal view returns (string) {
return stringStorage[keccak256(abi.encodePacked("records.", _id, ".name"))];
}
| 14,016,866 |
./partial_match/1/0xE4764f9cd8ECc9659d3abf35259638B20ac536E4/sources/contracts/protocol/ParticleExchange.sol | @inheritdoc IParticleExchange | function cancelBid(Lien calldata lien, uint256 lienId) external override validateLien(lien, lienId) nonReentrant {
if (msg.sender != lien.borrower) {
revert Errors.Unauthorized();
}
if (lien.lender != address(0)) {
revert Errors.BidTaken();
emit CancelBid(lienId);
}
| 4,052,391 |
./partial_match/1/0x8a3515f5D127342fcBba56E13514D4A2391327e6/sources/contracts/interfaces/IPoolMarketplace.sol | IPool Defines the basic interface for an ParaSpace Pool./ | interface IPoolMarketplace {
event BuyWithCredit(
bytes32 indexed marketplaceId,
DataTypes.OrderInfo orderInfo,
DataTypes.Credit credit
);
event AcceptBidWithCredit(
bytes32 indexed marketplaceId,
DataTypes.OrderInfo orderInfo,
DataTypes.Credit credit
);
function buyWithCredit(
bytes32 marketplaceId,
bytes calldata payload,
DataTypes.Credit calldata credit,
uint16 referralCode
) external payable;
function batchBuyWithCredit(
bytes32[] calldata marketplaceIds,
bytes[] calldata payloads,
DataTypes.Credit[] calldata credits,
uint16 referralCode
) external payable;
function acceptBidWithCredit(
bytes32 marketplaceId,
bytes calldata payload,
DataTypes.Credit calldata credit,
address onBehalfOf,
uint16 referralCode
) external;
function batchAcceptBidWithCredit(
bytes32[] calldata marketplaceIds,
bytes[] calldata payloads,
DataTypes.Credit[] calldata credits,
address onBehalfOf,
uint16 referralCode
) external;
pragma solidity ^0.8.0;
import {IPoolAddressesProvider} from "./IPoolAddressesProvider.sol";
import {DataTypes} from "../protocol/libraries/types/DataTypes.sol";
}
| 4,311,953 |
./full_match/1/0xd24047316B274d48dBb2FE20068C9Cc849B76152/sources/contracts/rate_oracles/BaseRateOracle.sol | @inheritdoc IRateOracle check if there are at least two points in the rate oracle otherwise, revert with "Not Enough Points" | function getLastRateSlope()
public
view
override
returns (uint256 rateChange, uint32 timeChange)
{
uint16 last = oracleVars.rateIndex;
uint16 lastButOne = (oracleVars.rateIndex >= 1)
? oracleVars.rateIndex - 1
: oracleVars.rateCardinality - 1;
require(
oracleVars.rateCardinality >= 2 &&
observations[lastButOne].initialized &&
observations[lastButOne].observedValue <=
observations[last].observedValue,
"NEP"
);
rateChange =
observations[last].observedValue -
observations[lastButOne].observedValue;
timeChange =
observations[last].blockTimestamp -
observations[lastButOne].blockTimestamp;
}
| 16,479,639 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "./RobiToken.sol";
/// @dev RobiToken interface containing only needed methods
interface IRobiToken {
function getBalanceAtBlockHeight(address _address, uint _blockHeight) external view returns (uint);
}
contract RobiGovernor is Ownable, ReentrancyGuard {
/*
* Events
*/
/// @notice LogProposalCreated is emitted when proposal is created
event LogProposalCreated(uint proposalId);
/// @notice LogProposalStatusUpdate is emitted when proposals status has been updated
event LogProposalStatusUpdate(uint proposalId, ProposalStatus status);
/// @notice LogProposalVotesUpdate is emitted when vote for specific proposal has been updated
event LogProposalVotesUpdate(uint proposalId, Vote vote);
/*
* Structs
*/
/// @notice votes mapping maps user address to his vote
/// @dev votes mapping is used as nested mapping for specific proposal votes
struct Votes {
mapping(address => Vote) votes;
}
/// @notice Vote struct represents users vote and is defined by status and weight (users balance on voteStart)
/// @dev Vote -> weight should be users balance at voteStart
struct Vote {
VoteStatus status;
// weight represents balance of user at the voteStart block height
uint weight;
}
/// @notice VoteResult struct represents response for users vote on specific proposal
/// @dev VoteResult struct is used as response object for get all user votes query
struct VoteResult {
Vote vote;
uint proposalId;
address voter;
}
/// @notice Proposal struct represents specific proposal
struct Proposal {
uint id;
uint voteStart; // block number
uint voteEnd; // block number
address payable proposer;
string title;
string description;
ProposalStatus status;
uint forVotes;
uint againstVotes;
uint fee;
bool feeRefunded;
string forumLink;
}
/*
* Enums
*/
/// @notice ProposalStatus enum represents the state of specific proposal
enum ProposalStatus { ACTIVE, DEFEATED, PASSED, EXECUTED }
/// @notice VoteStatus enum represents the state of users vote
enum VoteStatus { APPROVED, REJECTED }
/*
* Modifiers
*/
/// @dev checks if string is empty
/// @param data string to be checked
modifier noEmptyString(string memory data) {
require(bytes(data).length > 0, "RobiGovernor: String is empty");
_;
}
/*
* State variables
*/
string private _name;
// @notice _proposals mapping maps proposal id (uint256) to specific proposal
mapping(uint256 => Proposal) private _proposals;
// @notice votes mapping maps proposal id (uint256) to its Votes
mapping(uint256 => Votes) private votes;
uint proposalsCounter;
// @notice governanceTokenAddress holds address of the governance token
IRobiToken immutable private robiToken;
uint private _votingPeriod;
/// @notice Construct contract by specifying governance token address and governance name
/// @param _token Governance token address
/// @param contractName Contract name
constructor(address _token, string memory contractName, uint votingPeriod) noEmptyString(contractName) {
_name = contractName;
robiToken = IRobiToken(_token);
_votingPeriod = votingPeriod; // 1 hour
}
/// @notice This function is used to cast vote on specific proposal
/// @param proposalId Specific proposal id
/// @param voteStatus VoteStatus enum that specifies users decision
/// @return bool True if cast was successful and false if not
function castVote(uint proposalId, VoteStatus voteStatus) public returns (bool) {
Proposal storage proposal = _proposals[proposalId];
// vote can only be cast between vote start and end block heights
require(block.number >= proposal.voteStart && block.number < proposal.voteEnd, "Voting period is not active.");
// establish contract interface
uint balance = robiToken.getBalanceAtBlockHeight(msg.sender, proposal.voteStart);
// Check if users balance on voteStart was greater than 0
require(balance > 0, "You have no voting power.");
Vote storage currentVote = votes[proposalId].votes[msg.sender];
// check if user has already voted and subtract vote weight from total for or against
if (currentVote.weight != 0) {
if (currentVote.status == VoteStatus.APPROVED) {
proposal.forVotes -= currentVote.weight;
} else {
proposal.againstVotes -= currentVote.weight;
}
}
if (VoteStatus.APPROVED == voteStatus) {
proposal.forVotes += balance;
} else {
proposal.againstVotes += balance;
}
currentVote.status = voteStatus;
currentVote.weight = balance;
emit LogProposalVotesUpdate(proposalId, currentVote);
return true;
}
/// @notice This function is used to update the proposal states and should be called now and then.
/// @dev This function is protected against reentrancy because of external transfer call inside loop
function updateProposalStates() payable public nonReentrant {
// iterate all proposals
// FIXME optimise proposal state update logic before production
for (uint i = 0; i < proposalsCounter; i++) {
Proposal storage proposal = _proposals[proposalsCounter];
// if proposal is active and time to vote has passed
if (proposal.status == ProposalStatus.ACTIVE && block.number >= proposal.voteEnd) {
processProposal(proposal.id);
}
}
}
/// @notice This function confirms proposal execution by owner
/// @dev This function should be triggered only when proposal is enacted
/// @param proposalId Proposal id
function confirmProposalExecution(uint proposalId) public onlyOwner {
require(block.number >= _proposals[proposalId].voteEnd, "Proposal voting period is still open!");
_proposals[proposalId].status = ProposalStatus.EXECUTED;
emit LogProposalStatusUpdate(proposalId, _proposals[proposalId].status);
}
/// @notice This function is used to process proposal states and return fees if proposal has passed
/// @dev Calling function should be protected by reentrancy guard
/// @param proposalId Proposal which is being processed
function processProposal(uint proposalId) private {
Proposal storage proposal = _proposals[proposalId];
if (proposal.forVotes > proposal.againstVotes) {
proposal.status = ProposalStatus.PASSED;
if (!proposal.feeRefunded) {
proposal.feeRefunded = true;
proposal.proposer.transfer(proposal.fee);
}
} else {
proposal.status = ProposalStatus.DEFEATED;
}
emit LogProposalStatusUpdate(proposal.id, proposal.status);
}
/// @notice This function is used to create a new proposal
/// @dev This function accepts fee (payable) required for creating a proposal. Fee is returned if proposal passes
/// @param forumLink string representing link to the forum where discussion about proposal should be held
/// @param title Proposals title
/// @param description Proposals description
/// @return uint Proposal id
function createProposal(string memory forumLink, string memory title, string memory description
) payable noEmptyString(forumLink) noEmptyString(title) noEmptyString(description) public returns (uint) {
// check if user paid enough fee
require(msg.value >= fee(), "Fee is lower than required");
// string input length checks
require(utfStringLength(forumLink) <= maxForumLinkSize(), "Forum link length exceeds max size");
require(utfStringLength(title) <= maxTitleSize(), "Title length exceeds max size");
require(utfStringLength(description) <= maxDescriptionSize(), "Description length exceeds max size");
uint proposalId = proposalsCounter;
_proposals[proposalId] = Proposal(proposalId, block.number, block.number + _votingPeriod, payable(msg.sender),
title, description, ProposalStatus.ACTIVE, 0, 0, fee(), false, forumLink);
proposalsCounter++;
emit LogProposalCreated(proposalId);
return proposalsCounter - 1;
}
/// @notice This function is used to update the voting period
function updateVotingPeriod(uint256 newPeriod) public onlyOwner {
_votingPeriod = newPeriod;
}
/// @notice This function returns name of this contract
/// @return string Contracts name
function name() public view returns (string memory) {
return _name;
}
/// @notice This function returns Proposal struct
/// @param id Proposal id
/// @return Proposal Proposal struct
function getProposal(uint id) public view returns (Proposal memory) {
return _proposals[id];
}
/// @notice This function returns users vote for specific proposal
/// @param proposalId Proposal id
/// @return Vote Users vote for specific proposal
function getVote(uint proposalId, address _address) public view returns (Vote memory) {
return votes[proposalId].votes[_address];
}
/// @notice This function returns all user votes for all proposals
/// @return VoteResult[] Array of user VoteResult structs
function getUserVotes() public view returns (VoteResult[] memory) {
VoteResult[] memory tmpVotes = new VoteResult[](proposalsCounter);
for (uint i = 0; i < proposalsCounter; i++) {
tmpVotes[i] = VoteResult(votes[i].votes[msg.sender], i, msg.sender);
}
return tmpVotes;
}
/// @notice This function returns all proposals
/// @return proposals Array of proposals
function getProposals() public view returns (Proposal[] memory proposals) {
Proposal[] memory tmpProposals = new Proposal[](proposalsCounter);
for (uint i = 0; i < proposalsCounter; i++) {
tmpProposals[i] = _proposals[i];
}
return tmpProposals;
}
/// @notice This function returns proposal count
/// @return uint256 Number of proposals
function proposalCount() public view returns (uint256) {
return proposalsCounter;
}
/// @notice This function returns fee required for creation of proposal
/// @return uint256 Number representing fee
function fee() public pure returns (uint256) {
return 1;
}
/// @notice This function returns max forum link size
/// @return uint256 Number representing max forum link size
function maxForumLinkSize() public pure returns (uint256) {
return 200;
}
/// @notice This function returns max title size
/// @return uint256 Number representing max title size
function maxTitleSize() public pure returns (uint256) {
return 100;
}
/// @notice This function returns max description size
/// @return uint256 Number representing max description size
function maxDescriptionSize() public pure returns (uint256) {
return 200;
}
/// @notice This function returns voting period
/// @dev Voting period is specified in number of blocks
/// @return uint256 Number representing voting period
function getVotingPeriod() public view returns (uint) {
return _votingPeriod;
}
/// @notice This function returns length of string
/// @dev This function should be used for determining the actual string length
/// @return length Number representing provided string length
function utfStringLength(string memory str) pure internal returns (uint length) {
uint i=0;
bytes memory string_rep = bytes(str);
while (i<string_rep.length)
{
if (string_rep[i]>>7==0)
i+=1;
else if (string_rep[i]>>5==bytes1(uint8(0x6)))
i+=2;
else if (string_rep[i]>>4==bytes1(uint8(0xE)))
i+=3;
else if (string_rep[i]>>3==bytes1(uint8(0x1E)))
i+=4;
else
//For safety
i+=1;
length++;
}
}
} | This function is used to cast vote on specific proposal proposalId Specific proposal id voteStatus VoteStatus enum that specifies users decision return bool True if cast was successful and false if not vote can only be cast between vote start and end block heights establish contract interface Check if users balance on voteStart was greater than 0 check if user has already voted and subtract vote weight from total for or against | function castVote(uint proposalId, VoteStatus voteStatus) public returns (bool) {
Proposal storage proposal = _proposals[proposalId];
require(block.number >= proposal.voteStart && block.number < proposal.voteEnd, "Voting period is not active.");
uint balance = robiToken.getBalanceAtBlockHeight(msg.sender, proposal.voteStart);
require(balance > 0, "You have no voting power.");
Vote storage currentVote = votes[proposalId].votes[msg.sender];
if (currentVote.weight != 0) {
if (currentVote.status == VoteStatus.APPROVED) {
proposal.forVotes -= currentVote.weight;
proposal.againstVotes -= currentVote.weight;
}
}
if (VoteStatus.APPROVED == voteStatus) {
proposal.forVotes += balance;
proposal.againstVotes += balance;
}
currentVote.status = voteStatus;
currentVote.weight = balance;
emit LogProposalVotesUpdate(proposalId, currentVote);
return true;
}
| 879,513 |
./full_match/4/0x6BE60E29FBb7559A5aF18D1e8F840767dd315359/sources/tellorlegacy/contracts/oldContracts/libraries/OldTellorGettersLibrary.sol | Gets the 5 miners who mined the value for the specified requestId/_timestamp _requestId to look up _timestamp is the timestamp to look up miners for return the 5 miners' addresses/ | function getMinersByRequestIdAndTimestamp(OldTellorStorage.TellorStorageStruct storage self, uint _requestId, uint _timestamp) internal view returns(address[5] memory){
return self.requestDetails[_requestId].minersByValue[_timestamp];
}
| 817,787 |
pragma solidity ^0.4.21;
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; }
contract token {
/* 公共变量 */
string public name; //代币名称
string public symbol; //代币符号
uint8 public decimals = 4; //代币单位,展示的小数点后面多少个0
uint256 public totalSupply; //代币总量
/*记录所有余额的映射*/
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
event Transfer(address indexed from, address indexed to, uint256 value); //转帐通知事件
event Burn(address indexed from, uint256 value); //减去用户余额事件
/* 初始化合约,并且把初始的所有代币都给这合约的创建者
* @param initialSupply 代币的总数
* @param tokenName 代币名称
* @param tokenSymbol 代币符号
*/
function token(uint256 initialSupply, string tokenName, string tokenSymbol) public {
//初始化总量
totalSupply = initialSupply * 10 ** uint256(decimals);
//给指定帐户初始化代币总量,初始化用于奖励合约创建者
balanceOf[msg.sender] = totalSupply;
name = tokenName;
symbol = tokenSymbol;
}
/**
* 私有方法从一个帐户发送给另一个帐户代币
* @param _from address 发送代币的地址
* @param _to address 接受代币的地址
* @param _value uint256 接受代币的数量
*/
function _transfer(address _from, address _to, uint256 _value) internal {
//避免转帐的地址是0x0
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);
}
/**
* 从主帐户合约调用者发送给别人代币
* @param _to address 接受代币的地址
* @param _value uint256 接受代币的数量
*/
function transfer(address _to, uint256 _value) public {
_transfer(msg.sender, _to, _value);
}
/**
* 从某个指定的帐户中,向另一个帐户发送代币
*
* 调用过程,会检查设置的允许最大交易额
*
* @param _from address 发送者地址
* @param _to address 接受者地址
* @param _value uint256 要转移的代币数量
* @return success 是否交易成功
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success){
//检查发送者是否拥有足够余额
require(_value <= allowance[_from][msg.sender]); // Check allowance
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
/**
* 设置帐户允许支付的最大金额
*
* 一般在智能合约的时候,避免支付过多,造成风险
*
* @param _spender 帐户地址
* @param _value 金额
*/
function approve(address _spender, uint256 _value) public returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
/**
* 设置帐户允许支付的最大金额
*
* 一般在智能合约的时候,避免支付过多,造成风险,加入时间参数,可以在 tokenRecipient 中做其他操作
*
* @param _spender 帐户地址
* @param _value 金额
* @param _extraData 操作的时间
*/
function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
/**
* 减少代币调用者的余额
*
* 操作以后是不可逆的
*
* @param _value 要删除的数量
*/
function burn(uint256 _value) public returns (bool success) {
//检查帐户余额是否大于要减去的值
require(balanceOf[msg.sender] >= _value); // Check if the sender has enough
//给指定帐户减去余额
balanceOf[msg.sender] -= _value;
//代币问题做相应扣除
totalSupply -= _value;
Burn(msg.sender, _value);
return true;
}
/**
* 删除帐户的余额(含其他帐户)
*
* 删除以后是不可逆的
*
* @param _from 要操作的帐户地址
* @param _value 要减去的数量
*/
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;
}
} | 公共变量 /记录所有余额的映射/ 初始化合约,并且把初始的所有代币都给这合约的创建者 initialSupply 代币的总数 tokenName 代币名称 tokenSymbol 代币符号/初始化总量给指定帐户初始化代币总量,初始化用于奖励合约创建者 | function token(uint256 initialSupply, string tokenName, string tokenSymbol) public {
totalSupply = initialSupply * 10 ** uint256(decimals);
balanceOf[msg.sender] = totalSupply;
name = tokenName;
symbol = tokenSymbol;
}
| 14,014,069 |
///////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2018-2020 Crossbar.io Technologies GmbH and contributors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
///////////////////////////////////////////////////////////////////////////////
pragma solidity ^0.5.12;
contract XBRTest {
// Adapted from: https://github.com/ethereum/EIPs/blob/master/assets/eip-712/Example.sol
struct EIP712Domain {
string name;
string version;
uint256 chainId;
address verifyingContract;
}
struct Person {
string name;
address wallet;
}
struct Mail {
Person from;
Person to;
string contents;
}
bytes32 constant EIP712DOMAIN_TYPEHASH = keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
);
bytes32 constant PERSON_TYPEHASH = keccak256(
"Person(string name,address wallet)"
);
bytes32 constant MAIL_TYPEHASH = keccak256(
"Mail(Person from,Person to,string contents)Person(string name,address wallet)"
);
bytes32 DOMAIN_SEPARATOR;
constructor () public {
DOMAIN_SEPARATOR = hash(EIP712Domain({
name: "Ether Mail",
version: "1",
chainId: 1,
// verifyingContract: this
verifyingContract: 0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC
}));
}
function hash(EIP712Domain memory eip712Domain) internal pure returns (bytes32) {
return keccak256(abi.encode(
EIP712DOMAIN_TYPEHASH,
keccak256(bytes(eip712Domain.name)),
keccak256(bytes(eip712Domain.version)),
eip712Domain.chainId,
eip712Domain.verifyingContract
));
}
function hash(Person memory person) internal pure returns (bytes32) {
return keccak256(abi.encode(
PERSON_TYPEHASH,
keccak256(bytes(person.name)),
person.wallet
));
}
function hash(Mail memory mail) internal pure returns (bytes32) {
return keccak256(abi.encode(
MAIL_TYPEHASH,
hash(mail.from),
hash(mail.to),
keccak256(bytes(mail.contents))
));
}
function verify(Mail memory mail, uint8 v, bytes32 r, bytes32 s) internal view returns (bool) {
// Note: we need to use `encodePacked` here instead of `encode`.
bytes32 digest = keccak256(abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR,
hash(mail)
));
return ecrecover(digest, v, r, s) == mail.from.wallet;
}
function splitSignature (bytes memory signature_rsv) private pure returns (uint8 v, bytes32 r, bytes32 s) {
assembly {
r := mload(add(signature_rsv, 32))
s := mload(add(signature_rsv, 64))
v := and(mload(add(signature_rsv, 65)), 255)
}
if (v < 27) {
v += 27;
}
return (v, r, s);
}
function test_verify1(address signer, string memory from_name, address from_wallet, string memory to_name,
address to_wallet, string memory contents, bytes memory sig_rsv) public view returns (bool) {
(uint8 v, bytes32 r, bytes32 s) = splitSignature(sig_rsv);
Mail memory mail = Mail({
from: Person({
name: from_name,
wallet: from_wallet
}),
to: Person({
name: to_name,
wallet: to_wallet
}),
contents: contents
});
bytes32 digest = keccak256(abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR,
hash(mail)
));
return ecrecover(digest, v, r, s) == signer;
}
function test_verify2(address signer, string memory from_name, address from_wallet, string memory to_name,
address to_wallet, string memory contents, uint8 v, bytes32 r, bytes32 s) public view returns (bool) {
Mail memory mail = Mail({
from: Person({
name: from_name,
wallet: from_wallet
}),
to: Person({
name: to_name,
wallet: to_wallet
}),
contents: contents
});
bytes32 digest = keccak256(abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR,
hash(mail)
));
return ecrecover(digest, v, r, s) == signer;
}
function test() public view returns (bool) {
// Example signed message
Mail memory mail = Mail({
from: Person({
name: "Cow",
wallet: 0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826
}),
to: Person({
name: "Bob",
wallet: 0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB
}),
contents: "Hello, Bob!"
});
uint8 v = 28;
bytes32 r = 0x4355c47d63924e8a72e509b65029052eb6c299d53a04e167c5775fd466751c9d;
bytes32 s = 0x07299936d304c153f6443dfa05f40ff007d72911b6f72307f996231605b91562;
assert(DOMAIN_SEPARATOR == 0xf2cee375fa42b42143804025fc449deafd50cc031ca257e0b194a650a912090f);
assert(hash(mail) == 0xc52c0ee5d84264471806290a3f2c4cecfc5490626bf912d01f240d7a274b371e);
assert(verify(mail, v, r, s));
return true;
}
}
| Example signed message | function test() public view returns (bool) {
Mail memory mail = Mail({
from: Person({
name: "Cow",
wallet: 0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826
}),
to: Person({
name: "Bob",
wallet: 0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB
}),
contents: "Hello, Bob!"
});
uint8 v = 28;
bytes32 r = 0x4355c47d63924e8a72e509b65029052eb6c299d53a04e167c5775fd466751c9d;
bytes32 s = 0x07299936d304c153f6443dfa05f40ff007d72911b6f72307f996231605b91562;
assert(DOMAIN_SEPARATOR == 0xf2cee375fa42b42143804025fc449deafd50cc031ca257e0b194a650a912090f);
assert(hash(mail) == 0xc52c0ee5d84264471806290a3f2c4cecfc5490626bf912d01f240d7a274b371e);
assert(verify(mail, v, r, s));
return true;
}
| 1,082,244 |
pragma solidity ^0.7.6;
pragma abicoder v2;
import { TokenInterface} from "../../../common/interfaces.sol";
import { DSMath } from "../../../common/math.sol";
import { Basic } from "../../../common/basic.sol";
import "./interface.sol";
import "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol";
import "@uniswap/v3-core/contracts/libraries/TickMath.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import "@uniswap/v3-periphery/contracts/libraries/TransferHelper.sol";
abstract contract Helpers is DSMath, Basic {
/**
* @dev uniswap v3 NFT Position Manager & Swap Router
*/
INonfungiblePositionManager constant nftManager =
INonfungiblePositionManager(0xC36442b4a4522E871399CD717aBDD847Ab11FE88);
ISwapRouter constant swapRouter =
ISwapRouter(0xE592427A0AEce92De3Edee1F18E0157C05861564);
struct MintParams {
address tokenA;
address tokenB;
uint24 fee;
int24 tickLower;
int24 tickUpper;
uint256 amtA;
uint256 amtB;
uint256 slippage;
}
/**
* @dev Get Last NFT Index
* @param user: User address
*/
function _getLastNftId(address user)
internal
view
returns (uint256 tokenId)
{
uint256 len = nftManager.balanceOf(user);
tokenId = nftManager.tokenOfOwnerByIndex(user, len - 1);
}
function getMinAmount(
TokenInterface token,
uint256 amt,
uint256 slippage
) internal view returns (uint256 minAmt) {
uint256 _amt18 = convertTo18(token.decimals(), amt);
minAmt = wmul(_amt18, sub(WAD, slippage));
minAmt = convert18ToDec(token.decimals(), minAmt);
}
function sortTokenAddress(address _token0, address _token1)
internal
view
returns (address token0, address token1)
{
if (_token0 > _token1) {
(token0, token1) = (_token1, _token0);
} else {
(token0, token1) = (_token0, _token1);
}
}
function _createAndInitializePoolIfNecessary (
address tokenA,
address tokenB,
uint24 fee,
int24 initialTick
) internal returns (address pool) {
(TokenInterface token0Contract_, TokenInterface token1Contract_) = changeMaticAddress(
tokenA,
tokenB
);
(address token0_, address token1_) = sortTokenAddress(address(token0Contract_), address(token1Contract_));
return nftManager.createAndInitializePoolIfNecessary(
token0_,
token1_,
fee,
TickMath.getSqrtRatioAtTick(initialTick)
);
}
/**
* @dev Mint function which interact with Uniswap v3
*/
function _mint(MintParams memory params)
internal
returns (
uint256 tokenId,
uint128 liquidity,
uint256 amountA,
uint256 amountB
)
{
(TokenInterface _token0, TokenInterface _token1) = changeMaticAddress(
params.tokenA,
params.tokenB
);
uint256 _amount0 = params.amtA == uint256(-1)
? getTokenBal(TokenInterface(params.tokenA))
: params.amtA;
uint256 _amount1 = params.amtB == uint256(-1)
? getTokenBal(TokenInterface(params.tokenB))
: params.amtB;
convertMaticToWmatic(address(_token0) == wmaticAddr, _token0, _amount0);
convertMaticToWmatic(address(_token1) == wmaticAddr, _token1, _amount1);
approve(_token0, address(nftManager), _amount0);
approve(_token1, address(nftManager), _amount1);
{
(address token0, ) = sortTokenAddress(
address(_token0),
address(_token1)
);
if (token0 != address(_token0)) {
(_token0, _token1) = (_token1, _token0);
(_amount0, _amount1) = (_amount1, _amount0);
}
}
uint256 _minAmt0 = getMinAmount(_token0, _amount0, params.slippage);
uint256 _minAmt1 = getMinAmount(_token1, _amount1, params.slippage);
INonfungiblePositionManager.MintParams
memory params = INonfungiblePositionManager.MintParams(
address(_token0),
address(_token1),
params.fee,
params.tickLower,
params.tickUpper,
_amount0,
_amount1,
_minAmt0,
_minAmt1,
address(this),
block.timestamp
);
(tokenId, liquidity, amountA, amountB) = nftManager.mint(params);
}
function getNftTokenPairAddresses(uint256 _tokenId)
internal
view
returns (address token0, address token1)
{
(bool success, bytes memory data) = address(nftManager).staticcall(
abi.encodeWithSelector(nftManager.positions.selector, _tokenId)
);
require(success, "fetching positions failed");
{
(, , token0, token1, , , , ) = abi.decode(
data,
(
uint96,
address,
address,
address,
uint24,
int24,
int24,
uint128
)
);
}
}
/**
* @dev Check if token address is maticAddr and convert it to wmatic
*/
function _checkMATIC(
address _token0,
address _token1,
uint256 _amount0,
uint256 _amount1
) internal {
bool isMatic0 = _token0 == wmaticAddr;
bool isMatic1 = _token1 == wmaticAddr;
convertMaticToWmatic(isMatic0, TokenInterface(_token0), _amount0);
convertMaticToWmatic(isMatic1, TokenInterface(_token1), _amount1);
approve(TokenInterface(_token0), address(nftManager), _amount0);
approve(TokenInterface(_token1), address(nftManager), _amount1);
}
/**
* @dev addLiquidityWrapper function wrapper of _addLiquidity
*/
function _addLiquidityWrapper(
uint256 tokenId,
uint256 amountA,
uint256 amountB,
uint256 slippage
)
internal
returns (
uint256 liquidity,
uint256 amtA,
uint256 amtB
)
{
(address token0, address token1) = getNftTokenPairAddresses(tokenId);
(liquidity, amtA, amtB) = _addLiquidity(
tokenId,
token0,
token1,
amountA,
amountB,
slippage
);
}
/**
* @dev addLiquidity function which interact with Uniswap v3
*/
function _addLiquidity(
uint256 _tokenId,
address _token0,
address _token1,
uint256 _amount0,
uint256 _amount1,
uint256 _slippage
)
internal
returns (
uint128 liquidity,
uint256 amount0,
uint256 amount1
)
{
_checkMATIC(_token0, _token1, _amount0, _amount1);
uint256 _amount0Min = getMinAmount(
TokenInterface(_token0),
_amount0,
_slippage
);
uint256 _amount1Min = getMinAmount(
TokenInterface(_token1),
_amount1,
_slippage
);
INonfungiblePositionManager.IncreaseLiquidityParams
memory params = INonfungiblePositionManager.IncreaseLiquidityParams(
_tokenId,
_amount0,
_amount1,
_amount0Min,
_amount1Min,
block.timestamp
);
(liquidity, amount0, amount1) = nftManager.increaseLiquidity(params);
}
/**
* @dev decreaseLiquidity function which interact with Uniswap v3
*/
function _decreaseLiquidity(
uint256 _tokenId,
uint128 _liquidity,
uint256 _amount0Min,
uint256 _amount1Min
) internal returns (uint256 amount0, uint256 amount1) {
INonfungiblePositionManager.DecreaseLiquidityParams
memory params = INonfungiblePositionManager.DecreaseLiquidityParams(
_tokenId,
_liquidity,
_amount0Min,
_amount1Min,
block.timestamp
);
(amount0, amount1) = nftManager.decreaseLiquidity(params);
}
/**
* @dev collect function which interact with Uniswap v3
*/
function _collect(
uint256 _tokenId,
uint128 _amount0Max,
uint128 _amount1Max
) internal returns (uint256 amount0, uint256 amount1) {
INonfungiblePositionManager.CollectParams
memory params = INonfungiblePositionManager.CollectParams(
_tokenId,
address(this),
_amount0Max,
_amount1Max
);
(amount0, amount1) = nftManager.collect(params);
}
/**
* @dev Burn Function
*/
function _burn(uint256 _tokenId) internal {
nftManager.burn(_tokenId);
}
}
| decreaseLiquidity function which interact with Uniswap v3/ | function _decreaseLiquidity(
uint256 _tokenId,
uint128 _liquidity,
uint256 _amount0Min,
uint256 _amount1Min
) internal returns (uint256 amount0, uint256 amount1) {
INonfungiblePositionManager.DecreaseLiquidityParams
memory params = INonfungiblePositionManager.DecreaseLiquidityParams(
_tokenId,
_liquidity,
_amount0Min,
_amount1Min,
block.timestamp
);
(amount0, amount1) = nftManager.decreaseLiquidity(params);
}
| 5,525,610 |
./full_match/4/0x5B816018af77CBf115Ce55f92A642113f18b8098/sources/browser/Untitled.sol | to use anyother token(coin) for payment in-out that must be allowed by superadmin (owner) in other words if that coin address contains > 0 value in ether will be allowed means if validStableCoin[address] > 0 then can be used here network tree information ( user, parent, child-count, ref-count etc) | {
mapping(address => uint256) public validStableCoin;
struct userInfo
{
address payable user;
uint32 parentId;
uint32 referrerId;
uint8 childCount;
uint8 lastBoughtLevel;
uint16 referralCount;
uint128 levelExpiry;
uint32[] childIds;
}
struct etherOutPlan
{
bytes16 name;
uint8[] payoutType;
uint32[] payoutTo;
uint32[] payoutPercentage;
}
struct etherInPlan
{
bytes16 name;
}
mapping(uint256 => mapping (bool => etherInPlan[])) public etherInPlans;
mapping(uint256 => etherOutPlan[]) public etherOutPlans;
mapping(uint256 => mapping( uint256 => mapping( bool => mapping(uint256 => uint256)))) public poolAmount;
struct payInput
{
uint256 _networkId;
uint8 _planIndex;
uint32 _userId;
uint256 _paidAmount;
bool mainTree;
}
event doTransactionEv(uint256 timeNow, uint256 indexed _networkId, address payable from, address payable to,uint256 amount,uint256 paidToAdmin, uint8 indexed _planIndex, bool indexed mainTree);
function doTransaction(uint256 _networkId, address payable from, address payable to,uint256 amount,uint8 _planIndex, bool mainTree, uint32 toUserId) internal returns(bool)
{
address _coinAddress = coinAddress[_networkId];
if(to != owner && from != address(0) && to != address(this))
{
if(userInfos[_networkId][0][mainTree][toUserId].levelExpiry < now) to = networkOwner[_networkId];
}
uint256 payAdmin = adminDeduction[_networkId];
if(payAdmin > 0 && to != owner && to != networkOwner[_networkId] && to != address(this)) payAdmin = amount - (amount * payAdmin / 100000000);
if(_coinAddress == address(0))
{
if(to != address(this)) to.transfer(amount - payAdmin);
if(payAdmin > 0) to.transfer(payAdmin);
}
else
{
if(from != address(0))
{
require( stableCoin(_coinAddress).transferFrom(from, address(this), amount),"token reveiving failed");
}
else
{
require( stableCoin(_coinAddress).transfer(to, amount),"token transfer failed");
if(payAdmin > 0) require( stableCoin(_coinAddress).transfer(to, payAdmin),"token transfer failed");
}
}
emit doTransactionEv(now,_networkId,from,to,amount,payAdmin,_planIndex,mainTree);
return true;
}
function doTransaction(uint256 _networkId, address payable from, address payable to,uint256 amount,uint8 _planIndex, bool mainTree, uint32 toUserId) internal returns(bool)
{
address _coinAddress = coinAddress[_networkId];
if(to != owner && from != address(0) && to != address(this))
{
if(userInfos[_networkId][0][mainTree][toUserId].levelExpiry < now) to = networkOwner[_networkId];
}
uint256 payAdmin = adminDeduction[_networkId];
if(payAdmin > 0 && to != owner && to != networkOwner[_networkId] && to != address(this)) payAdmin = amount - (amount * payAdmin / 100000000);
if(_coinAddress == address(0))
{
if(to != address(this)) to.transfer(amount - payAdmin);
if(payAdmin > 0) to.transfer(payAdmin);
}
else
{
if(from != address(0))
{
require( stableCoin(_coinAddress).transferFrom(from, address(this), amount),"token reveiving failed");
}
else
{
require( stableCoin(_coinAddress).transfer(to, amount),"token transfer failed");
if(payAdmin > 0) require( stableCoin(_coinAddress).transfer(to, payAdmin),"token transfer failed");
}
}
emit doTransactionEv(now,_networkId,from,to,amount,payAdmin,_planIndex,mainTree);
return true;
}
function doTransaction(uint256 _networkId, address payable from, address payable to,uint256 amount,uint8 _planIndex, bool mainTree, uint32 toUserId) internal returns(bool)
{
address _coinAddress = coinAddress[_networkId];
if(to != owner && from != address(0) && to != address(this))
{
if(userInfos[_networkId][0][mainTree][toUserId].levelExpiry < now) to = networkOwner[_networkId];
}
uint256 payAdmin = adminDeduction[_networkId];
if(payAdmin > 0 && to != owner && to != networkOwner[_networkId] && to != address(this)) payAdmin = amount - (amount * payAdmin / 100000000);
if(_coinAddress == address(0))
{
if(to != address(this)) to.transfer(amount - payAdmin);
if(payAdmin > 0) to.transfer(payAdmin);
}
else
{
if(from != address(0))
{
require( stableCoin(_coinAddress).transferFrom(from, address(this), amount),"token reveiving failed");
}
else
{
require( stableCoin(_coinAddress).transfer(to, amount),"token transfer failed");
if(payAdmin > 0) require( stableCoin(_coinAddress).transfer(to, payAdmin),"token transfer failed");
}
}
emit doTransactionEv(now,_networkId,from,to,amount,payAdmin,_planIndex,mainTree);
return true;
}
function doTransaction(uint256 _networkId, address payable from, address payable to,uint256 amount,uint8 _planIndex, bool mainTree, uint32 toUserId) internal returns(bool)
{
address _coinAddress = coinAddress[_networkId];
if(to != owner && from != address(0) && to != address(this))
{
if(userInfos[_networkId][0][mainTree][toUserId].levelExpiry < now) to = networkOwner[_networkId];
}
uint256 payAdmin = adminDeduction[_networkId];
if(payAdmin > 0 && to != owner && to != networkOwner[_networkId] && to != address(this)) payAdmin = amount - (amount * payAdmin / 100000000);
if(_coinAddress == address(0))
{
if(to != address(this)) to.transfer(amount - payAdmin);
if(payAdmin > 0) to.transfer(payAdmin);
}
else
{
if(from != address(0))
{
require( stableCoin(_coinAddress).transferFrom(from, address(this), amount),"token reveiving failed");
}
else
{
require( stableCoin(_coinAddress).transfer(to, amount),"token transfer failed");
if(payAdmin > 0) require( stableCoin(_coinAddress).transfer(to, payAdmin),"token transfer failed");
}
}
emit doTransactionEv(now,_networkId,from,to,amount,payAdmin,_planIndex,mainTree);
return true;
}
function doTransaction(uint256 _networkId, address payable from, address payable to,uint256 amount,uint8 _planIndex, bool mainTree, uint32 toUserId) internal returns(bool)
{
address _coinAddress = coinAddress[_networkId];
if(to != owner && from != address(0) && to != address(this))
{
if(userInfos[_networkId][0][mainTree][toUserId].levelExpiry < now) to = networkOwner[_networkId];
}
uint256 payAdmin = adminDeduction[_networkId];
if(payAdmin > 0 && to != owner && to != networkOwner[_networkId] && to != address(this)) payAdmin = amount - (amount * payAdmin / 100000000);
if(_coinAddress == address(0))
{
if(to != address(this)) to.transfer(amount - payAdmin);
if(payAdmin > 0) to.transfer(payAdmin);
}
else
{
if(from != address(0))
{
require( stableCoin(_coinAddress).transferFrom(from, address(this), amount),"token reveiving failed");
}
else
{
require( stableCoin(_coinAddress).transfer(to, amount),"token transfer failed");
if(payAdmin > 0) require( stableCoin(_coinAddress).transfer(to, payAdmin),"token transfer failed");
}
}
emit doTransactionEv(now,_networkId,from,to,amount,payAdmin,_planIndex,mainTree);
return true;
}
function doTransaction(uint256 _networkId, address payable from, address payable to,uint256 amount,uint8 _planIndex, bool mainTree, uint32 toUserId) internal returns(bool)
{
address _coinAddress = coinAddress[_networkId];
if(to != owner && from != address(0) && to != address(this))
{
if(userInfos[_networkId][0][mainTree][toUserId].levelExpiry < now) to = networkOwner[_networkId];
}
uint256 payAdmin = adminDeduction[_networkId];
if(payAdmin > 0 && to != owner && to != networkOwner[_networkId] && to != address(this)) payAdmin = amount - (amount * payAdmin / 100000000);
if(_coinAddress == address(0))
{
if(to != address(this)) to.transfer(amount - payAdmin);
if(payAdmin > 0) to.transfer(payAdmin);
}
else
{
if(from != address(0))
{
require( stableCoin(_coinAddress).transferFrom(from, address(this), amount),"token reveiving failed");
}
else
{
require( stableCoin(_coinAddress).transfer(to, amount),"token transfer failed");
if(payAdmin > 0) require( stableCoin(_coinAddress).transfer(to, payAdmin),"token transfer failed");
}
}
emit doTransactionEv(now,_networkId,from,to,amount,payAdmin,_planIndex,mainTree);
return true;
}
function() external payable
{
revert();
}
function checkAmount(uint256 amount, uint256 price, address _coinAddress ) public view returns (bool)
{
uint256 amt = amount * validStableCoin[_coinAddress] / 100000000;
if(price == amt ) return true;
return false;
}
event BuynetworkEv(uint256 timeNow,address indexed user,uint256 indexed paidAmount,uint256 indexed networkIDCount);
function BuyNetwork(address _coinAddress, uint256 amount) public payable returns(bool)
{
require(networkId[msg.sender] == 0,"same address can not own two network");
require(_coinAddress == address(0) || validStableCoin[_coinAddress] > 0, "Invalid coin address");
networkIdCount++;
uint nID = networkIdCount;
networkId[msg.sender] = nID;
networkOwner[nID] = msg.sender;
coinAddress[nID] = _coinAddress;
pausenetwork[nID] = true;
if(_coinAddress != address(0))
{
require(checkAmount(amount,networkPrice, _coinAddress), "Invalid amount sent");
require(doTransaction(nID, msg.sender, address(this),amount,0,true,0), "amount tx fail");
}
else
{
require(msg.value == networkPrice, "Ivalid ether sent");
amount = msg.value;
}
require(doTransaction(nID, address(0), owner,amount,0,true,0), "amount tx fail");
emit BuynetworkEv(now, msg.sender, msg.value, networkIdCount);
}
function BuyNetwork(address _coinAddress, uint256 amount) public payable returns(bool)
{
require(networkId[msg.sender] == 0,"same address can not own two network");
require(_coinAddress == address(0) || validStableCoin[_coinAddress] > 0, "Invalid coin address");
networkIdCount++;
uint nID = networkIdCount;
networkId[msg.sender] = nID;
networkOwner[nID] = msg.sender;
coinAddress[nID] = _coinAddress;
pausenetwork[nID] = true;
if(_coinAddress != address(0))
{
require(checkAmount(amount,networkPrice, _coinAddress), "Invalid amount sent");
require(doTransaction(nID, msg.sender, address(this),amount,0,true,0), "amount tx fail");
}
else
{
require(msg.value == networkPrice, "Ivalid ether sent");
amount = msg.value;
}
require(doTransaction(nID, address(0), owner,amount,0,true,0), "amount tx fail");
emit BuynetworkEv(now, msg.sender, msg.value, networkIdCount);
}
function BuyNetwork(address _coinAddress, uint256 amount) public payable returns(bool)
{
require(networkId[msg.sender] == 0,"same address can not own two network");
require(_coinAddress == address(0) || validStableCoin[_coinAddress] > 0, "Invalid coin address");
networkIdCount++;
uint nID = networkIdCount;
networkId[msg.sender] = nID;
networkOwner[nID] = msg.sender;
coinAddress[nID] = _coinAddress;
pausenetwork[nID] = true;
if(_coinAddress != address(0))
{
require(checkAmount(amount,networkPrice, _coinAddress), "Invalid amount sent");
require(doTransaction(nID, msg.sender, address(this),amount,0,true,0), "amount tx fail");
}
else
{
require(msg.value == networkPrice, "Ivalid ether sent");
amount = msg.value;
}
require(doTransaction(nID, address(0), owner,amount,0,true,0), "amount tx fail");
emit BuynetworkEv(now, msg.sender, msg.value, networkIdCount);
}
event addEtherInPlanEv(uint256 timeNow, uint256 indexed _networkId, bytes16 indexed _name,uint128 _buyPrice,uint128 _planExpiry, uint8 _maxChild,bool _autoPlaceInTree,bool _allowJoinAgain, uint8 _etheroutPlanId,bool[] _triggerSubTree, bool indexed _triggerExternalContract );
function addEtherInPlan(uint256 _networkId, bytes16 _name,uint128 _buyPrice,uint128 _planExpiry, uint8 _maxChild,bool _autoPlaceInTree,bool _allowJoinAgain, uint8 _etheroutPlanId,bool[] memory _triggerSubTree, bool _triggerExternalContract ) public returns(bool)
{
require(networkId[msg.sender] == _networkId,"Invalid caller");
require(_etheroutPlanId < etherOutPlans[_networkId].length, "please define required ether out plan first");
require(!goToPublic[_networkId], "network in function cannot change now");
require(_triggerSubTree.length == etherInPlans[_networkId][false].length, "Invalid _triggerSubTree count");
if(etherInPlans[_networkId][true].length == 0) require( _maxChild > 0,"maxChild cannot be 0 for first plan");
require(_buyPrice >= minPlanPrice, "plan price is less then minimum");
require(_planExpiry > 0, "plan expiry can not be 0");
require(checkTotalPercentage(_networkId,_etheroutPlanId,_triggerSubTree), "payout not matching 100% ");
if(etherInPlans[_networkId][true].length > 0) _autoPlaceInTree = true;
etherInPlan memory temp;
temp.name = _name;
temp.buyPrice = _buyPrice;
temp.planExpiry = _planExpiry;
temp.maxChild = _maxChild;
temp.autoPlaceInTree = _autoPlaceInTree;
temp.allowJoinAgain = _allowJoinAgain;
temp.etheroutPlanId = _etheroutPlanId;
temp.triggerSubTree = _triggerSubTree;
temp.triggerExternalContract = _triggerExternalContract;
etherInPlans[_networkId][true].push(temp);
emit addEtherInPlanEv(now, _networkId,_name,_buyPrice,_planExpiry, _maxChild,_autoPlaceInTree,_allowJoinAgain,_etheroutPlanId,_triggerSubTree,_triggerExternalContract );
return true;
}
function setExternalContract(uint256 _networkId, address _externalContract, uint256 _adminDeduction ) public returns(bool)
{
require(networkId[msg.sender] == _networkId,"Invalid caller");
require(!goToPublic[_networkId], "network in function cannot change now");
externalContract[_networkId] = _externalContract;
adminDeduction[_networkId] = _adminDeduction;
return true;
}
function checkTotalPercentage(uint256 _networkId,uint8 _etheroutPlanId, bool[] memory _triggerSubTree) internal view returns(bool)
{
uint8 i;
uint totalPercent = payoutPercentageSum(_networkId, _etheroutPlanId) + platFormFeePercentage;
for(i=0;i<_triggerSubTree.length; i++)
{
if(_triggerSubTree[i]) totalPercent += payoutPercentageSum(_networkId, etherInPlans[_networkId][false][i].etheroutPlanId);
}
require(totalPercent == 100000000 + platFormFeePercentage, "payout sum is not 100 $");
return true;
}
event addSubTreePlanEv(uint256 timeNow, uint256 indexed _networkId, bytes16 indexed _name,uint128 _planExpiry, uint8 _maxChild,bool _allowJoinAgain, uint8 _etheroutPlanId,bool indexed _triggerExternalContract );
function checkTotalPercentage(uint256 _networkId,uint8 _etheroutPlanId, bool[] memory _triggerSubTree) internal view returns(bool)
{
uint8 i;
uint totalPercent = payoutPercentageSum(_networkId, _etheroutPlanId) + platFormFeePercentage;
for(i=0;i<_triggerSubTree.length; i++)
{
if(_triggerSubTree[i]) totalPercent += payoutPercentageSum(_networkId, etherInPlans[_networkId][false][i].etheroutPlanId);
}
require(totalPercent == 100000000 + platFormFeePercentage, "payout sum is not 100 $");
return true;
}
event addSubTreePlanEv(uint256 timeNow, uint256 indexed _networkId, bytes16 indexed _name,uint128 _planExpiry, uint8 _maxChild,bool _allowJoinAgain, uint8 _etheroutPlanId,bool indexed _triggerExternalContract );
function addSubTreePlan(uint256 _networkId, bytes16 _name,uint128 _planExpiry, uint8 _maxChild,bool _allowJoinAgain, uint8 _etheroutPlanId,bool _triggerExternalContract ) public returns(bool)
{
require(networkId[msg.sender] == _networkId,"Invalid caller");
require(_etheroutPlanId < etherOutPlans[_networkId].length, "please define required ether out plan first");
require(!goToPublic[_networkId], "network in function cannot change now");
require(_planExpiry > 0, "plan expiry can not be 0");
etherInPlan memory temp;
temp.name = _name;
temp.planExpiry = _planExpiry;
temp.maxChild = _maxChild;
temp.autoPlaceInTree = true;
temp.allowJoinAgain = _allowJoinAgain;
temp.etheroutPlanId = _etheroutPlanId;
temp.triggerExternalContract = _triggerExternalContract;
etherInPlans[_networkId][false].push(temp);
emit addSubTreePlanEv(now,_networkId,_name,_planExpiry,_maxChild,_allowJoinAgain,_etheroutPlanId,_triggerExternalContract );
return true;
}
event addEtherOutPlansEv(uint256 timeNow, uint256 indexed _networkId, bytes16 indexed _name,uint8[] _payoutType, uint32[] _payoutTo,uint32[] indexed _payoutPercentage);
function addEtherOutPlans(uint256 _networkId, bytes16 _name,uint8[] memory _payoutType, uint32[] memory _payoutTo,uint32[] memory _payoutPercentage) public returns(bool)
{
require(networkId[msg.sender] == _networkId,"Invalid caller");
require(!goToPublic[_networkId], "network in function cannot change now");
require(_payoutType.length == _payoutTo.length && _payoutType.length == _payoutPercentage.length);
for(uint i=0;i<_payoutType.length;i++)
{
require(_payoutType[i] < 5, "_payoutTo should be 0 ~ 4 not more");
}
etherOutPlan memory temp;
temp.name = _name;
temp.payoutType = _payoutType;
temp.payoutTo = _payoutTo;
temp.payoutPercentage = _payoutPercentage;
etherOutPlans[_networkId].push(temp);
emit addEtherOutPlansEv(now,_networkId,_name,_payoutType,_payoutTo,_payoutPercentage);
return true;
}
event startMynetworkEv(uint256 timeNow, uint256 indexed _networkId);
function addEtherOutPlans(uint256 _networkId, bytes16 _name,uint8[] memory _payoutType, uint32[] memory _payoutTo,uint32[] memory _payoutPercentage) public returns(bool)
{
require(networkId[msg.sender] == _networkId,"Invalid caller");
require(!goToPublic[_networkId], "network in function cannot change now");
require(_payoutType.length == _payoutTo.length && _payoutType.length == _payoutPercentage.length);
for(uint i=0;i<_payoutType.length;i++)
{
require(_payoutType[i] < 5, "_payoutTo should be 0 ~ 4 not more");
}
etherOutPlan memory temp;
temp.name = _name;
temp.payoutType = _payoutType;
temp.payoutTo = _payoutTo;
temp.payoutPercentage = _payoutPercentage;
etherOutPlans[_networkId].push(temp);
emit addEtherOutPlansEv(now,_networkId,_name,_payoutType,_payoutTo,_payoutPercentage);
return true;
}
event startMynetworkEv(uint256 timeNow, uint256 indexed _networkId);
function startMynetwork(uint256 _networkId) public returns(bool)
{
require(!goToPublic[_networkId], "network in function cannot change now");
require(networkId[msg.sender] == _networkId,"Invalid caller");
uint256 len = etherInPlans[_networkId][true].length;
require(len > 0, "no etherInPlan defined");
for(uint8 i=0; i< len;i++)
{
etherInPlan memory temp;
temp = etherInPlans[_networkId][true][i];
if(temp.maxChild > 0 ) require(_buyPlan(_networkId,i, msg.sender,0, 0, 0,temp, 0, true), "plan buy fail");
}
pausenetwork[_networkId] = false;
goToPublic[_networkId] = true;
return true;
}
event pauseReleaseMynetworkEv(uint256 timeNow, uint256 indexed _networkId, bool indexed pause);
function startMynetwork(uint256 _networkId) public returns(bool)
{
require(!goToPublic[_networkId], "network in function cannot change now");
require(networkId[msg.sender] == _networkId,"Invalid caller");
uint256 len = etherInPlans[_networkId][true].length;
require(len > 0, "no etherInPlan defined");
for(uint8 i=0; i< len;i++)
{
etherInPlan memory temp;
temp = etherInPlans[_networkId][true][i];
if(temp.maxChild > 0 ) require(_buyPlan(_networkId,i, msg.sender,0, 0, 0,temp, 0, true), "plan buy fail");
}
pausenetwork[_networkId] = false;
goToPublic[_networkId] = true;
return true;
}
event pauseReleaseMynetworkEv(uint256 timeNow, uint256 indexed _networkId, bool indexed pause);
emit startMynetworkEv(now,_networkId);
function pauseReleaseMynetwork(uint256 _networkId, bool pause) public returns(bool)
{
require(networkId[msg.sender] == _networkId);
pausenetwork[_networkId]= pause;
emit pauseReleaseMynetworkEv(now, _networkId, pause);
return true;
}
event regUserEv(uint timeNow, uint256 indexed _networkId,uint8 indexed _planIndex, address payable indexed _user,uint32 _userId, uint32 _referrerId, uint32 _parentId, uint256 amount);
function regUser(uint256 _networkId,uint32 _referrerId,uint32 _parentId, uint256 amount) public payable returns(bool)
{
require(tx.origin != address(0), "invalid sender" );
require(!pausenetwork[_networkId] && goToPublic[_networkId], "not ready or paused by admin");
require(_networkId <= networkIdCount && _networkId > 0, "invalid network id" );
require(userInfos[_networkId][0][true].length > _referrerId,"_referrerId not exist");
address _coinAddress = coinAddress[_networkId];
etherInPlan memory temp;
temp = etherInPlans[_networkId][true][0];
if(_coinAddress != address(0))
{
require(checkAmount(amount,temp.buyPrice, _coinAddress), "Invalid amount sent");
require(doTransaction(_networkId, tx.origin, address(this),amount,0,true,0), "amount tx fail");
}
else
{
require(msg.value == temp.buyPrice, "Ivalid ether sent");
amount = msg.value;
}
require(_buyPlan(_networkId,0, tx.origin,0, _referrerId, _parentId,temp, amount, true), "plan buy fail");
emit regUserEv(now, _networkId,0,tx.origin,0,_referrerId,_parentId,amount);
return true;
}
function regUser(uint256 _networkId,uint32 _referrerId,uint32 _parentId, uint256 amount) public payable returns(bool)
{
require(tx.origin != address(0), "invalid sender" );
require(!pausenetwork[_networkId] && goToPublic[_networkId], "not ready or paused by admin");
require(_networkId <= networkIdCount && _networkId > 0, "invalid network id" );
require(userInfos[_networkId][0][true].length > _referrerId,"_referrerId not exist");
address _coinAddress = coinAddress[_networkId];
etherInPlan memory temp;
temp = etherInPlans[_networkId][true][0];
if(_coinAddress != address(0))
{
require(checkAmount(amount,temp.buyPrice, _coinAddress), "Invalid amount sent");
require(doTransaction(_networkId, tx.origin, address(this),amount,0,true,0), "amount tx fail");
}
else
{
require(msg.value == temp.buyPrice, "Ivalid ether sent");
amount = msg.value;
}
require(_buyPlan(_networkId,0, tx.origin,0, _referrerId, _parentId,temp, amount, true), "plan buy fail");
emit regUserEv(now, _networkId,0,tx.origin,0,_referrerId,_parentId,amount);
return true;
}
function regUser(uint256 _networkId,uint32 _referrerId,uint32 _parentId, uint256 amount) public payable returns(bool)
{
require(tx.origin != address(0), "invalid sender" );
require(!pausenetwork[_networkId] && goToPublic[_networkId], "not ready or paused by admin");
require(_networkId <= networkIdCount && _networkId > 0, "invalid network id" );
require(userInfos[_networkId][0][true].length > _referrerId,"_referrerId not exist");
address _coinAddress = coinAddress[_networkId];
etherInPlan memory temp;
temp = etherInPlans[_networkId][true][0];
if(_coinAddress != address(0))
{
require(checkAmount(amount,temp.buyPrice, _coinAddress), "Invalid amount sent");
require(doTransaction(_networkId, tx.origin, address(this),amount,0,true,0), "amount tx fail");
}
else
{
require(msg.value == temp.buyPrice, "Ivalid ether sent");
amount = msg.value;
}
require(_buyPlan(_networkId,0, tx.origin,0, _referrerId, _parentId,temp, amount, true), "plan buy fail");
emit regUserEv(now, _networkId,0,tx.origin,0,_referrerId,_parentId,amount);
return true;
}
event buyLevelEv(uint256 indexed _networkId,uint8 indexed _planIndex,uint32 indexed _userId,uint256 amount);
function buyLevel(uint256 _networkId,uint8 _planIndex, uint32 _userId, uint256 amount) public payable returns(bool)
{
require(tx.origin != address(0), "invalid sender" );
require(!pausenetwork[_networkId] && goToPublic[_networkId], "not ready or paused by admin");
require(_networkId <= networkIdCount && _networkId > 0, "invalid network id" );
require(_planIndex < etherInPlans[_networkId][true].length && _planIndex > 0, "invalid planIndex");
require(checkUserId(_networkId,0,true,tx.origin,_userId ),"_userId not matching to sender");
require(_planIndex == userInfos[_networkId][0][true][_userId].lastBoughtLevel ,"pls buy previous plan first");
address _coinAddress = coinAddress[_networkId];
etherInPlan memory temp;
temp = etherInPlans[_networkId][true][_planIndex];
if(_coinAddress != address(0))
{
require(checkAmount(amount,temp.buyPrice, _coinAddress), "Invalid amount sent");
require(doTransaction(_networkId, tx.origin, address(this),amount,0,true,0), "amount tx fail");
}
else
{
require(msg.value == temp.buyPrice, "Ivalid ether sent");
amount = msg.value;
}
require(_buyPlan(_networkId,_planIndex,tx.origin,_userId, 0, 0,temp, amount, true), "plan buy fail");
emit buyLevelEv(_networkId,_planIndex,_userId,amount);
return true;
}
event _subTreePlanEv(uint256 timeNow, uint256 indexed _networkId,uint8 indexed _planIndex, address payable indexed _user,uint32 _userId,uint256 _amountAfterFeePaid);
event _buyPlanEv(uint256 timeNow, uint256 indexed _networkId,uint8 indexed _planIndex,uint32 indexed _userId, uint32 _referrerId, uint32 _parentId, uint256 _amountAfterFeePaid);
function buyLevel(uint256 _networkId,uint8 _planIndex, uint32 _userId, uint256 amount) public payable returns(bool)
{
require(tx.origin != address(0), "invalid sender" );
require(!pausenetwork[_networkId] && goToPublic[_networkId], "not ready or paused by admin");
require(_networkId <= networkIdCount && _networkId > 0, "invalid network id" );
require(_planIndex < etherInPlans[_networkId][true].length && _planIndex > 0, "invalid planIndex");
require(checkUserId(_networkId,0,true,tx.origin,_userId ),"_userId not matching to sender");
require(_planIndex == userInfos[_networkId][0][true][_userId].lastBoughtLevel ,"pls buy previous plan first");
address _coinAddress = coinAddress[_networkId];
etherInPlan memory temp;
temp = etherInPlans[_networkId][true][_planIndex];
if(_coinAddress != address(0))
{
require(checkAmount(amount,temp.buyPrice, _coinAddress), "Invalid amount sent");
require(doTransaction(_networkId, tx.origin, address(this),amount,0,true,0), "amount tx fail");
}
else
{
require(msg.value == temp.buyPrice, "Ivalid ether sent");
amount = msg.value;
}
require(_buyPlan(_networkId,_planIndex,tx.origin,_userId, 0, 0,temp, amount, true), "plan buy fail");
emit buyLevelEv(_networkId,_planIndex,_userId,amount);
return true;
}
event _subTreePlanEv(uint256 timeNow, uint256 indexed _networkId,uint8 indexed _planIndex, address payable indexed _user,uint32 _userId,uint256 _amountAfterFeePaid);
event _buyPlanEv(uint256 timeNow, uint256 indexed _networkId,uint8 indexed _planIndex,uint32 indexed _userId, uint32 _referrerId, uint32 _parentId, uint256 _amountAfterFeePaid);
function buyLevel(uint256 _networkId,uint8 _planIndex, uint32 _userId, uint256 amount) public payable returns(bool)
{
require(tx.origin != address(0), "invalid sender" );
require(!pausenetwork[_networkId] && goToPublic[_networkId], "not ready or paused by admin");
require(_networkId <= networkIdCount && _networkId > 0, "invalid network id" );
require(_planIndex < etherInPlans[_networkId][true].length && _planIndex > 0, "invalid planIndex");
require(checkUserId(_networkId,0,true,tx.origin,_userId ),"_userId not matching to sender");
require(_planIndex == userInfos[_networkId][0][true][_userId].lastBoughtLevel ,"pls buy previous plan first");
address _coinAddress = coinAddress[_networkId];
etherInPlan memory temp;
temp = etherInPlans[_networkId][true][_planIndex];
if(_coinAddress != address(0))
{
require(checkAmount(amount,temp.buyPrice, _coinAddress), "Invalid amount sent");
require(doTransaction(_networkId, tx.origin, address(this),amount,0,true,0), "amount tx fail");
}
else
{
require(msg.value == temp.buyPrice, "Ivalid ether sent");
amount = msg.value;
}
require(_buyPlan(_networkId,_planIndex,tx.origin,_userId, 0, 0,temp, amount, true), "plan buy fail");
emit buyLevelEv(_networkId,_planIndex,_userId,amount);
return true;
}
event _subTreePlanEv(uint256 timeNow, uint256 indexed _networkId,uint8 indexed _planIndex, address payable indexed _user,uint32 _userId,uint256 _amountAfterFeePaid);
event _buyPlanEv(uint256 timeNow, uint256 indexed _networkId,uint8 indexed _planIndex,uint32 indexed _userId, uint32 _referrerId, uint32 _parentId, uint256 _amountAfterFeePaid);
function _buyPlan(uint256 _networkId,uint8 _planIndex, address payable _user,uint32 _userId, uint32 _referrerId, uint32 _parentId, etherInPlan memory _temp, uint256 _paidAmount, bool mainTree) internal returns(bool)
{
uint256 lastId = userInfos[_networkId][_planIndex][mainTree].length ;
{
if(!_temp.allowJoinAgain ) require(userIndex[_networkId][_planIndex][mainTree][_user].length == 0, "user already joined");
if(_temp.autoPlaceInTree && _parentId > 0)
{
if(userInfos[_networkId][_planIndex][mainTree][_parentId].childCount == _temp.maxChild) etherInPlans[_networkId][mainTree][_planIndex].nextBlankSlot++;
_parentId = etherInPlans[_networkId][mainTree][_planIndex].nextBlankSlot;
_referrerId = _parentId;
}
else if(userInfos[_networkId][_planIndex][mainTree].length > 0)
{
if(_parentId == 0 )
{
_parentId = findBlankSlot(_networkId,0,_referrerId,mainTree, _temp.maxChild);
}
else
{
require(userInfos[_networkId][_planIndex][mainTree][_parentId].childCount < _temp.maxChild,"Invalid _parent Id");
}
}
_userId = processTree(_networkId,_planIndex,_user,_referrerId,_parentId,mainTree);
}
if(lastId > 0 ) lastId--;
if(mainTree)
{
userInfos[_networkId][0][mainTree][_userId].lastBoughtLevel = _planIndex + 1;
require(payPlatformCharge(_networkId, _paidAmount), "fail deducting platform charge");
_paidAmount = _paidAmount - (_paidAmount * platFormFeePercentage / 100000000);
}
payInput memory payIn;
payIn._networkId = _networkId;
payIn._planIndex = _planIndex;
payIn._userId = _userId;
payIn._paidAmount = _paidAmount;
payIn.mainTree = mainTree;
require(processPayOut(payIn),"payout failed");
emit processPayOutEv(_networkId,_planIndex,_userId,_paidAmount,mainTree);
etherInPlan memory _temp2;
if(mainTree)
{
for(uint8 i=0;i<_temp.triggerSubTree.length;i++)
{
if(_temp.triggerSubTree[i])
{
_temp2 = etherInPlans[_networkId][false][i];
require(_buyPlan(_networkId,i,tx.origin, _userId, 0, 0,_temp2, _paidAmount, false), "sub tree call fail");
emit _subTreePlanEv(now,_networkId,i,_user,_userId,_paidAmount);
}
}
}
if(_temp.triggerExternalContract) externalInterface(externalContract[_networkId]).processExternalMain(_networkId,_planIndex,_user,_userId,_referrerId,_parentId,_paidAmount,mainTree);
emit _buyPlanEv(now,_networkId,_planIndex,_userId,_referrerId,_parentId,_paidAmount);
return true;
}
event processTreeEv(uint128 levelExpiry,uint256 indexed networkID,uint8 indexed planIndex,address user,uint32 referrerId,uint32 parentId,uint256 indexed userId,bool treeType);
function _buyPlan(uint256 _networkId,uint8 _planIndex, address payable _user,uint32 _userId, uint32 _referrerId, uint32 _parentId, etherInPlan memory _temp, uint256 _paidAmount, bool mainTree) internal returns(bool)
{
uint256 lastId = userInfos[_networkId][_planIndex][mainTree].length ;
{
if(!_temp.allowJoinAgain ) require(userIndex[_networkId][_planIndex][mainTree][_user].length == 0, "user already joined");
if(_temp.autoPlaceInTree && _parentId > 0)
{
if(userInfos[_networkId][_planIndex][mainTree][_parentId].childCount == _temp.maxChild) etherInPlans[_networkId][mainTree][_planIndex].nextBlankSlot++;
_parentId = etherInPlans[_networkId][mainTree][_planIndex].nextBlankSlot;
_referrerId = _parentId;
}
else if(userInfos[_networkId][_planIndex][mainTree].length > 0)
{
if(_parentId == 0 )
{
_parentId = findBlankSlot(_networkId,0,_referrerId,mainTree, _temp.maxChild);
}
else
{
require(userInfos[_networkId][_planIndex][mainTree][_parentId].childCount < _temp.maxChild,"Invalid _parent Id");
}
}
_userId = processTree(_networkId,_planIndex,_user,_referrerId,_parentId,mainTree);
}
if(lastId > 0 ) lastId--;
if(mainTree)
{
userInfos[_networkId][0][mainTree][_userId].lastBoughtLevel = _planIndex + 1;
require(payPlatformCharge(_networkId, _paidAmount), "fail deducting platform charge");
_paidAmount = _paidAmount - (_paidAmount * platFormFeePercentage / 100000000);
}
payInput memory payIn;
payIn._networkId = _networkId;
payIn._planIndex = _planIndex;
payIn._userId = _userId;
payIn._paidAmount = _paidAmount;
payIn.mainTree = mainTree;
require(processPayOut(payIn),"payout failed");
emit processPayOutEv(_networkId,_planIndex,_userId,_paidAmount,mainTree);
etherInPlan memory _temp2;
if(mainTree)
{
for(uint8 i=0;i<_temp.triggerSubTree.length;i++)
{
if(_temp.triggerSubTree[i])
{
_temp2 = etherInPlans[_networkId][false][i];
require(_buyPlan(_networkId,i,tx.origin, _userId, 0, 0,_temp2, _paidAmount, false), "sub tree call fail");
emit _subTreePlanEv(now,_networkId,i,_user,_userId,_paidAmount);
}
}
}
if(_temp.triggerExternalContract) externalInterface(externalContract[_networkId]).processExternalMain(_networkId,_planIndex,_user,_userId,_referrerId,_parentId,_paidAmount,mainTree);
emit _buyPlanEv(now,_networkId,_planIndex,_userId,_referrerId,_parentId,_paidAmount);
return true;
}
event processTreeEv(uint128 levelExpiry,uint256 indexed networkID,uint8 indexed planIndex,address user,uint32 referrerId,uint32 parentId,uint256 indexed userId,bool treeType);
function _buyPlan(uint256 _networkId,uint8 _planIndex, address payable _user,uint32 _userId, uint32 _referrerId, uint32 _parentId, etherInPlan memory _temp, uint256 _paidAmount, bool mainTree) internal returns(bool)
{
uint256 lastId = userInfos[_networkId][_planIndex][mainTree].length ;
{
if(!_temp.allowJoinAgain ) require(userIndex[_networkId][_planIndex][mainTree][_user].length == 0, "user already joined");
if(_temp.autoPlaceInTree && _parentId > 0)
{
if(userInfos[_networkId][_planIndex][mainTree][_parentId].childCount == _temp.maxChild) etherInPlans[_networkId][mainTree][_planIndex].nextBlankSlot++;
_parentId = etherInPlans[_networkId][mainTree][_planIndex].nextBlankSlot;
_referrerId = _parentId;
}
else if(userInfos[_networkId][_planIndex][mainTree].length > 0)
{
if(_parentId == 0 )
{
_parentId = findBlankSlot(_networkId,0,_referrerId,mainTree, _temp.maxChild);
}
else
{
require(userInfos[_networkId][_planIndex][mainTree][_parentId].childCount < _temp.maxChild,"Invalid _parent Id");
}
}
_userId = processTree(_networkId,_planIndex,_user,_referrerId,_parentId,mainTree);
}
if(lastId > 0 ) lastId--;
if(mainTree)
{
userInfos[_networkId][0][mainTree][_userId].lastBoughtLevel = _planIndex + 1;
require(payPlatformCharge(_networkId, _paidAmount), "fail deducting platform charge");
_paidAmount = _paidAmount - (_paidAmount * platFormFeePercentage / 100000000);
}
payInput memory payIn;
payIn._networkId = _networkId;
payIn._planIndex = _planIndex;
payIn._userId = _userId;
payIn._paidAmount = _paidAmount;
payIn.mainTree = mainTree;
require(processPayOut(payIn),"payout failed");
emit processPayOutEv(_networkId,_planIndex,_userId,_paidAmount,mainTree);
etherInPlan memory _temp2;
if(mainTree)
{
for(uint8 i=0;i<_temp.triggerSubTree.length;i++)
{
if(_temp.triggerSubTree[i])
{
_temp2 = etherInPlans[_networkId][false][i];
require(_buyPlan(_networkId,i,tx.origin, _userId, 0, 0,_temp2, _paidAmount, false), "sub tree call fail");
emit _subTreePlanEv(now,_networkId,i,_user,_userId,_paidAmount);
}
}
}
if(_temp.triggerExternalContract) externalInterface(externalContract[_networkId]).processExternalMain(_networkId,_planIndex,_user,_userId,_referrerId,_parentId,_paidAmount,mainTree);
emit _buyPlanEv(now,_networkId,_planIndex,_userId,_referrerId,_parentId,_paidAmount);
return true;
}
event processTreeEv(uint128 levelExpiry,uint256 indexed networkID,uint8 indexed planIndex,address user,uint32 referrerId,uint32 parentId,uint256 indexed userId,bool treeType);
function _buyPlan(uint256 _networkId,uint8 _planIndex, address payable _user,uint32 _userId, uint32 _referrerId, uint32 _parentId, etherInPlan memory _temp, uint256 _paidAmount, bool mainTree) internal returns(bool)
{
uint256 lastId = userInfos[_networkId][_planIndex][mainTree].length ;
{
if(!_temp.allowJoinAgain ) require(userIndex[_networkId][_planIndex][mainTree][_user].length == 0, "user already joined");
if(_temp.autoPlaceInTree && _parentId > 0)
{
if(userInfos[_networkId][_planIndex][mainTree][_parentId].childCount == _temp.maxChild) etherInPlans[_networkId][mainTree][_planIndex].nextBlankSlot++;
_parentId = etherInPlans[_networkId][mainTree][_planIndex].nextBlankSlot;
_referrerId = _parentId;
}
else if(userInfos[_networkId][_planIndex][mainTree].length > 0)
{
if(_parentId == 0 )
{
_parentId = findBlankSlot(_networkId,0,_referrerId,mainTree, _temp.maxChild);
}
else
{
require(userInfos[_networkId][_planIndex][mainTree][_parentId].childCount < _temp.maxChild,"Invalid _parent Id");
}
}
_userId = processTree(_networkId,_planIndex,_user,_referrerId,_parentId,mainTree);
}
if(lastId > 0 ) lastId--;
if(mainTree)
{
userInfos[_networkId][0][mainTree][_userId].lastBoughtLevel = _planIndex + 1;
require(payPlatformCharge(_networkId, _paidAmount), "fail deducting platform charge");
_paidAmount = _paidAmount - (_paidAmount * platFormFeePercentage / 100000000);
}
payInput memory payIn;
payIn._networkId = _networkId;
payIn._planIndex = _planIndex;
payIn._userId = _userId;
payIn._paidAmount = _paidAmount;
payIn.mainTree = mainTree;
require(processPayOut(payIn),"payout failed");
emit processPayOutEv(_networkId,_planIndex,_userId,_paidAmount,mainTree);
etherInPlan memory _temp2;
if(mainTree)
{
for(uint8 i=0;i<_temp.triggerSubTree.length;i++)
{
if(_temp.triggerSubTree[i])
{
_temp2 = etherInPlans[_networkId][false][i];
require(_buyPlan(_networkId,i,tx.origin, _userId, 0, 0,_temp2, _paidAmount, false), "sub tree call fail");
emit _subTreePlanEv(now,_networkId,i,_user,_userId,_paidAmount);
}
}
}
if(_temp.triggerExternalContract) externalInterface(externalContract[_networkId]).processExternalMain(_networkId,_planIndex,_user,_userId,_referrerId,_parentId,_paidAmount,mainTree);
emit _buyPlanEv(now,_networkId,_planIndex,_userId,_referrerId,_parentId,_paidAmount);
return true;
}
event processTreeEv(uint128 levelExpiry,uint256 indexed networkID,uint8 indexed planIndex,address user,uint32 referrerId,uint32 parentId,uint256 indexed userId,bool treeType);
function _buyPlan(uint256 _networkId,uint8 _planIndex, address payable _user,uint32 _userId, uint32 _referrerId, uint32 _parentId, etherInPlan memory _temp, uint256 _paidAmount, bool mainTree) internal returns(bool)
{
uint256 lastId = userInfos[_networkId][_planIndex][mainTree].length ;
{
if(!_temp.allowJoinAgain ) require(userIndex[_networkId][_planIndex][mainTree][_user].length == 0, "user already joined");
if(_temp.autoPlaceInTree && _parentId > 0)
{
if(userInfos[_networkId][_planIndex][mainTree][_parentId].childCount == _temp.maxChild) etherInPlans[_networkId][mainTree][_planIndex].nextBlankSlot++;
_parentId = etherInPlans[_networkId][mainTree][_planIndex].nextBlankSlot;
_referrerId = _parentId;
}
else if(userInfos[_networkId][_planIndex][mainTree].length > 0)
{
if(_parentId == 0 )
{
_parentId = findBlankSlot(_networkId,0,_referrerId,mainTree, _temp.maxChild);
}
else
{
require(userInfos[_networkId][_planIndex][mainTree][_parentId].childCount < _temp.maxChild,"Invalid _parent Id");
}
}
_userId = processTree(_networkId,_planIndex,_user,_referrerId,_parentId,mainTree);
}
if(lastId > 0 ) lastId--;
if(mainTree)
{
userInfos[_networkId][0][mainTree][_userId].lastBoughtLevel = _planIndex + 1;
require(payPlatformCharge(_networkId, _paidAmount), "fail deducting platform charge");
_paidAmount = _paidAmount - (_paidAmount * platFormFeePercentage / 100000000);
}
payInput memory payIn;
payIn._networkId = _networkId;
payIn._planIndex = _planIndex;
payIn._userId = _userId;
payIn._paidAmount = _paidAmount;
payIn.mainTree = mainTree;
require(processPayOut(payIn),"payout failed");
emit processPayOutEv(_networkId,_planIndex,_userId,_paidAmount,mainTree);
etherInPlan memory _temp2;
if(mainTree)
{
for(uint8 i=0;i<_temp.triggerSubTree.length;i++)
{
if(_temp.triggerSubTree[i])
{
_temp2 = etherInPlans[_networkId][false][i];
require(_buyPlan(_networkId,i,tx.origin, _userId, 0, 0,_temp2, _paidAmount, false), "sub tree call fail");
emit _subTreePlanEv(now,_networkId,i,_user,_userId,_paidAmount);
}
}
}
if(_temp.triggerExternalContract) externalInterface(externalContract[_networkId]).processExternalMain(_networkId,_planIndex,_user,_userId,_referrerId,_parentId,_paidAmount,mainTree);
emit _buyPlanEv(now,_networkId,_planIndex,_userId,_referrerId,_parentId,_paidAmount);
return true;
}
event processTreeEv(uint128 levelExpiry,uint256 indexed networkID,uint8 indexed planIndex,address user,uint32 referrerId,uint32 parentId,uint256 indexed userId,bool treeType);
function _buyPlan(uint256 _networkId,uint8 _planIndex, address payable _user,uint32 _userId, uint32 _referrerId, uint32 _parentId, etherInPlan memory _temp, uint256 _paidAmount, bool mainTree) internal returns(bool)
{
uint256 lastId = userInfos[_networkId][_planIndex][mainTree].length ;
{
if(!_temp.allowJoinAgain ) require(userIndex[_networkId][_planIndex][mainTree][_user].length == 0, "user already joined");
if(_temp.autoPlaceInTree && _parentId > 0)
{
if(userInfos[_networkId][_planIndex][mainTree][_parentId].childCount == _temp.maxChild) etherInPlans[_networkId][mainTree][_planIndex].nextBlankSlot++;
_parentId = etherInPlans[_networkId][mainTree][_planIndex].nextBlankSlot;
_referrerId = _parentId;
}
else if(userInfos[_networkId][_planIndex][mainTree].length > 0)
{
if(_parentId == 0 )
{
_parentId = findBlankSlot(_networkId,0,_referrerId,mainTree, _temp.maxChild);
}
else
{
require(userInfos[_networkId][_planIndex][mainTree][_parentId].childCount < _temp.maxChild,"Invalid _parent Id");
}
}
_userId = processTree(_networkId,_planIndex,_user,_referrerId,_parentId,mainTree);
}
if(lastId > 0 ) lastId--;
if(mainTree)
{
userInfos[_networkId][0][mainTree][_userId].lastBoughtLevel = _planIndex + 1;
require(payPlatformCharge(_networkId, _paidAmount), "fail deducting platform charge");
_paidAmount = _paidAmount - (_paidAmount * platFormFeePercentage / 100000000);
}
payInput memory payIn;
payIn._networkId = _networkId;
payIn._planIndex = _planIndex;
payIn._userId = _userId;
payIn._paidAmount = _paidAmount;
payIn.mainTree = mainTree;
require(processPayOut(payIn),"payout failed");
emit processPayOutEv(_networkId,_planIndex,_userId,_paidAmount,mainTree);
etherInPlan memory _temp2;
if(mainTree)
{
for(uint8 i=0;i<_temp.triggerSubTree.length;i++)
{
if(_temp.triggerSubTree[i])
{
_temp2 = etherInPlans[_networkId][false][i];
require(_buyPlan(_networkId,i,tx.origin, _userId, 0, 0,_temp2, _paidAmount, false), "sub tree call fail");
emit _subTreePlanEv(now,_networkId,i,_user,_userId,_paidAmount);
}
}
}
if(_temp.triggerExternalContract) externalInterface(externalContract[_networkId]).processExternalMain(_networkId,_planIndex,_user,_userId,_referrerId,_parentId,_paidAmount,mainTree);
emit _buyPlanEv(now,_networkId,_planIndex,_userId,_referrerId,_parentId,_paidAmount);
return true;
}
event processTreeEv(uint128 levelExpiry,uint256 indexed networkID,uint8 indexed planIndex,address user,uint32 referrerId,uint32 parentId,uint256 indexed userId,bool treeType);
function _buyPlan(uint256 _networkId,uint8 _planIndex, address payable _user,uint32 _userId, uint32 _referrerId, uint32 _parentId, etherInPlan memory _temp, uint256 _paidAmount, bool mainTree) internal returns(bool)
{
uint256 lastId = userInfos[_networkId][_planIndex][mainTree].length ;
{
if(!_temp.allowJoinAgain ) require(userIndex[_networkId][_planIndex][mainTree][_user].length == 0, "user already joined");
if(_temp.autoPlaceInTree && _parentId > 0)
{
if(userInfos[_networkId][_planIndex][mainTree][_parentId].childCount == _temp.maxChild) etherInPlans[_networkId][mainTree][_planIndex].nextBlankSlot++;
_parentId = etherInPlans[_networkId][mainTree][_planIndex].nextBlankSlot;
_referrerId = _parentId;
}
else if(userInfos[_networkId][_planIndex][mainTree].length > 0)
{
if(_parentId == 0 )
{
_parentId = findBlankSlot(_networkId,0,_referrerId,mainTree, _temp.maxChild);
}
else
{
require(userInfos[_networkId][_planIndex][mainTree][_parentId].childCount < _temp.maxChild,"Invalid _parent Id");
}
}
_userId = processTree(_networkId,_planIndex,_user,_referrerId,_parentId,mainTree);
}
if(lastId > 0 ) lastId--;
if(mainTree)
{
userInfos[_networkId][0][mainTree][_userId].lastBoughtLevel = _planIndex + 1;
require(payPlatformCharge(_networkId, _paidAmount), "fail deducting platform charge");
_paidAmount = _paidAmount - (_paidAmount * platFormFeePercentage / 100000000);
}
payInput memory payIn;
payIn._networkId = _networkId;
payIn._planIndex = _planIndex;
payIn._userId = _userId;
payIn._paidAmount = _paidAmount;
payIn.mainTree = mainTree;
require(processPayOut(payIn),"payout failed");
emit processPayOutEv(_networkId,_planIndex,_userId,_paidAmount,mainTree);
etherInPlan memory _temp2;
if(mainTree)
{
for(uint8 i=0;i<_temp.triggerSubTree.length;i++)
{
if(_temp.triggerSubTree[i])
{
_temp2 = etherInPlans[_networkId][false][i];
require(_buyPlan(_networkId,i,tx.origin, _userId, 0, 0,_temp2, _paidAmount, false), "sub tree call fail");
emit _subTreePlanEv(now,_networkId,i,_user,_userId,_paidAmount);
}
}
}
if(_temp.triggerExternalContract) externalInterface(externalContract[_networkId]).processExternalMain(_networkId,_planIndex,_user,_userId,_referrerId,_parentId,_paidAmount,mainTree);
emit _buyPlanEv(now,_networkId,_planIndex,_userId,_referrerId,_parentId,_paidAmount);
return true;
}
event processTreeEv(uint128 levelExpiry,uint256 indexed networkID,uint8 indexed planIndex,address user,uint32 referrerId,uint32 parentId,uint256 indexed userId,bool treeType);
function _buyPlan(uint256 _networkId,uint8 _planIndex, address payable _user,uint32 _userId, uint32 _referrerId, uint32 _parentId, etherInPlan memory _temp, uint256 _paidAmount, bool mainTree) internal returns(bool)
{
uint256 lastId = userInfos[_networkId][_planIndex][mainTree].length ;
{
if(!_temp.allowJoinAgain ) require(userIndex[_networkId][_planIndex][mainTree][_user].length == 0, "user already joined");
if(_temp.autoPlaceInTree && _parentId > 0)
{
if(userInfos[_networkId][_planIndex][mainTree][_parentId].childCount == _temp.maxChild) etherInPlans[_networkId][mainTree][_planIndex].nextBlankSlot++;
_parentId = etherInPlans[_networkId][mainTree][_planIndex].nextBlankSlot;
_referrerId = _parentId;
}
else if(userInfos[_networkId][_planIndex][mainTree].length > 0)
{
if(_parentId == 0 )
{
_parentId = findBlankSlot(_networkId,0,_referrerId,mainTree, _temp.maxChild);
}
else
{
require(userInfos[_networkId][_planIndex][mainTree][_parentId].childCount < _temp.maxChild,"Invalid _parent Id");
}
}
_userId = processTree(_networkId,_planIndex,_user,_referrerId,_parentId,mainTree);
}
if(lastId > 0 ) lastId--;
if(mainTree)
{
userInfos[_networkId][0][mainTree][_userId].lastBoughtLevel = _planIndex + 1;
require(payPlatformCharge(_networkId, _paidAmount), "fail deducting platform charge");
_paidAmount = _paidAmount - (_paidAmount * platFormFeePercentage / 100000000);
}
payInput memory payIn;
payIn._networkId = _networkId;
payIn._planIndex = _planIndex;
payIn._userId = _userId;
payIn._paidAmount = _paidAmount;
payIn.mainTree = mainTree;
require(processPayOut(payIn),"payout failed");
emit processPayOutEv(_networkId,_planIndex,_userId,_paidAmount,mainTree);
etherInPlan memory _temp2;
if(mainTree)
{
for(uint8 i=0;i<_temp.triggerSubTree.length;i++)
{
if(_temp.triggerSubTree[i])
{
_temp2 = etherInPlans[_networkId][false][i];
require(_buyPlan(_networkId,i,tx.origin, _userId, 0, 0,_temp2, _paidAmount, false), "sub tree call fail");
emit _subTreePlanEv(now,_networkId,i,_user,_userId,_paidAmount);
}
}
}
if(_temp.triggerExternalContract) externalInterface(externalContract[_networkId]).processExternalMain(_networkId,_planIndex,_user,_userId,_referrerId,_parentId,_paidAmount,mainTree);
emit _buyPlanEv(now,_networkId,_planIndex,_userId,_referrerId,_parentId,_paidAmount);
return true;
}
event processTreeEv(uint128 levelExpiry,uint256 indexed networkID,uint8 indexed planIndex,address user,uint32 referrerId,uint32 parentId,uint256 indexed userId,bool treeType);
function _buyPlan(uint256 _networkId,uint8 _planIndex, address payable _user,uint32 _userId, uint32 _referrerId, uint32 _parentId, etherInPlan memory _temp, uint256 _paidAmount, bool mainTree) internal returns(bool)
{
uint256 lastId = userInfos[_networkId][_planIndex][mainTree].length ;
{
if(!_temp.allowJoinAgain ) require(userIndex[_networkId][_planIndex][mainTree][_user].length == 0, "user already joined");
if(_temp.autoPlaceInTree && _parentId > 0)
{
if(userInfos[_networkId][_planIndex][mainTree][_parentId].childCount == _temp.maxChild) etherInPlans[_networkId][mainTree][_planIndex].nextBlankSlot++;
_parentId = etherInPlans[_networkId][mainTree][_planIndex].nextBlankSlot;
_referrerId = _parentId;
}
else if(userInfos[_networkId][_planIndex][mainTree].length > 0)
{
if(_parentId == 0 )
{
_parentId = findBlankSlot(_networkId,0,_referrerId,mainTree, _temp.maxChild);
}
else
{
require(userInfos[_networkId][_planIndex][mainTree][_parentId].childCount < _temp.maxChild,"Invalid _parent Id");
}
}
_userId = processTree(_networkId,_planIndex,_user,_referrerId,_parentId,mainTree);
}
if(lastId > 0 ) lastId--;
if(mainTree)
{
userInfos[_networkId][0][mainTree][_userId].lastBoughtLevel = _planIndex + 1;
require(payPlatformCharge(_networkId, _paidAmount), "fail deducting platform charge");
_paidAmount = _paidAmount - (_paidAmount * platFormFeePercentage / 100000000);
}
payInput memory payIn;
payIn._networkId = _networkId;
payIn._planIndex = _planIndex;
payIn._userId = _userId;
payIn._paidAmount = _paidAmount;
payIn.mainTree = mainTree;
require(processPayOut(payIn),"payout failed");
emit processPayOutEv(_networkId,_planIndex,_userId,_paidAmount,mainTree);
etherInPlan memory _temp2;
if(mainTree)
{
for(uint8 i=0;i<_temp.triggerSubTree.length;i++)
{
if(_temp.triggerSubTree[i])
{
_temp2 = etherInPlans[_networkId][false][i];
require(_buyPlan(_networkId,i,tx.origin, _userId, 0, 0,_temp2, _paidAmount, false), "sub tree call fail");
emit _subTreePlanEv(now,_networkId,i,_user,_userId,_paidAmount);
}
}
}
if(_temp.triggerExternalContract) externalInterface(externalContract[_networkId]).processExternalMain(_networkId,_planIndex,_user,_userId,_referrerId,_parentId,_paidAmount,mainTree);
emit _buyPlanEv(now,_networkId,_planIndex,_userId,_referrerId,_parentId,_paidAmount);
return true;
}
event processTreeEv(uint128 levelExpiry,uint256 indexed networkID,uint8 indexed planIndex,address user,uint32 referrerId,uint32 parentId,uint256 indexed userId,bool treeType);
function _buyPlan(uint256 _networkId,uint8 _planIndex, address payable _user,uint32 _userId, uint32 _referrerId, uint32 _parentId, etherInPlan memory _temp, uint256 _paidAmount, bool mainTree) internal returns(bool)
{
uint256 lastId = userInfos[_networkId][_planIndex][mainTree].length ;
{
if(!_temp.allowJoinAgain ) require(userIndex[_networkId][_planIndex][mainTree][_user].length == 0, "user already joined");
if(_temp.autoPlaceInTree && _parentId > 0)
{
if(userInfos[_networkId][_planIndex][mainTree][_parentId].childCount == _temp.maxChild) etherInPlans[_networkId][mainTree][_planIndex].nextBlankSlot++;
_parentId = etherInPlans[_networkId][mainTree][_planIndex].nextBlankSlot;
_referrerId = _parentId;
}
else if(userInfos[_networkId][_planIndex][mainTree].length > 0)
{
if(_parentId == 0 )
{
_parentId = findBlankSlot(_networkId,0,_referrerId,mainTree, _temp.maxChild);
}
else
{
require(userInfos[_networkId][_planIndex][mainTree][_parentId].childCount < _temp.maxChild,"Invalid _parent Id");
}
}
_userId = processTree(_networkId,_planIndex,_user,_referrerId,_parentId,mainTree);
}
if(lastId > 0 ) lastId--;
if(mainTree)
{
userInfos[_networkId][0][mainTree][_userId].lastBoughtLevel = _planIndex + 1;
require(payPlatformCharge(_networkId, _paidAmount), "fail deducting platform charge");
_paidAmount = _paidAmount - (_paidAmount * platFormFeePercentage / 100000000);
}
payInput memory payIn;
payIn._networkId = _networkId;
payIn._planIndex = _planIndex;
payIn._userId = _userId;
payIn._paidAmount = _paidAmount;
payIn.mainTree = mainTree;
require(processPayOut(payIn),"payout failed");
emit processPayOutEv(_networkId,_planIndex,_userId,_paidAmount,mainTree);
etherInPlan memory _temp2;
if(mainTree)
{
for(uint8 i=0;i<_temp.triggerSubTree.length;i++)
{
if(_temp.triggerSubTree[i])
{
_temp2 = etherInPlans[_networkId][false][i];
require(_buyPlan(_networkId,i,tx.origin, _userId, 0, 0,_temp2, _paidAmount, false), "sub tree call fail");
emit _subTreePlanEv(now,_networkId,i,_user,_userId,_paidAmount);
}
}
}
if(_temp.triggerExternalContract) externalInterface(externalContract[_networkId]).processExternalMain(_networkId,_planIndex,_user,_userId,_referrerId,_parentId,_paidAmount,mainTree);
emit _buyPlanEv(now,_networkId,_planIndex,_userId,_referrerId,_parentId,_paidAmount);
return true;
}
event processTreeEv(uint128 levelExpiry,uint256 indexed networkID,uint8 indexed planIndex,address user,uint32 referrerId,uint32 parentId,uint256 indexed userId,bool treeType);
function processTree(uint256 _networkId,uint8 _planIndex, address payable _user, uint32 _referrerId, uint32 _parentId, bool mainTree) internal returns(uint32)
{
userInfo memory temp;
temp.user = _user;
uint32 thisId = uint32(userInfos[_networkId][_planIndex][mainTree].length);
temp.parentId = _parentId;
temp.referrerId = _referrerId;
uint256 expiry = now + etherInPlans[_networkId][mainTree][_planIndex].planExpiry;
if(thisId == 0 ) expiry = 5745990791;
temp.levelExpiry = uint128(expiry);
userInfos[_networkId][_planIndex][mainTree].push(temp);
userInfos[_networkId][_planIndex][mainTree][_parentId].childIds.push(thisId);
if(thisId > 0 )
{
userInfos[_networkId][_planIndex][mainTree][_parentId].childCount++;
userInfos[_networkId][_planIndex][mainTree][_referrerId].referralCount++;
}
userIndex[_networkId][_planIndex][mainTree][_user].push(thisId);
emit processTreeEv(temp.levelExpiry, _networkId, _planIndex, _user, _referrerId, _parentId,thisId, mainTree);
return thisId;
}
event processPayOutEv(uint256 indexed _networkId,uint8 indexed _planIndex,uint32 _userId, uint256 _paidAmount,bool indexed mainTree);
event depositedToPoolEv(uint256 timeNow, uint256 indexed _networkId,uint8 indexed _planIndex,uint256 Amount,uint256 poolIndex,bool indexed mainTree);
function processTree(uint256 _networkId,uint8 _planIndex, address payable _user, uint32 _referrerId, uint32 _parentId, bool mainTree) internal returns(uint32)
{
userInfo memory temp;
temp.user = _user;
uint32 thisId = uint32(userInfos[_networkId][_planIndex][mainTree].length);
temp.parentId = _parentId;
temp.referrerId = _referrerId;
uint256 expiry = now + etherInPlans[_networkId][mainTree][_planIndex].planExpiry;
if(thisId == 0 ) expiry = 5745990791;
temp.levelExpiry = uint128(expiry);
userInfos[_networkId][_planIndex][mainTree].push(temp);
userInfos[_networkId][_planIndex][mainTree][_parentId].childIds.push(thisId);
if(thisId > 0 )
{
userInfos[_networkId][_planIndex][mainTree][_parentId].childCount++;
userInfos[_networkId][_planIndex][mainTree][_referrerId].referralCount++;
}
userIndex[_networkId][_planIndex][mainTree][_user].push(thisId);
emit processTreeEv(temp.levelExpiry, _networkId, _planIndex, _user, _referrerId, _parentId,thisId, mainTree);
return thisId;
}
event processPayOutEv(uint256 indexed _networkId,uint8 indexed _planIndex,uint32 _userId, uint256 _paidAmount,bool indexed mainTree);
event depositedToPoolEv(uint256 timeNow, uint256 indexed _networkId,uint8 indexed _planIndex,uint256 Amount,uint256 poolIndex,bool indexed mainTree);
function processPayOut(payInput memory payIn) internal returns (bool)
{
uint8 etheroutPlanId = etherInPlans[payIn._networkId][payIn.mainTree][payIn._planIndex].etheroutPlanId;
etherOutPlan memory temp;
temp = etherOutPlans[payIn._networkId][etheroutPlanId];
uint32 _userId2 = payIn._userId;
uint32 _userId1 = _userId2;
address payable thisUser;
uint256 thisAmount;
uint8 _pi;
if( etherInPlans[payIn._networkId][payIn.mainTree][payIn._planIndex].maxChild == 0)
{
_pi = payIn._planIndex;
}
uint j;
for(uint8 k=0; k < temp.payoutType.length; k++)
{
thisAmount = payIn._paidAmount * temp.payoutPercentage[k] / 100000000;
if(thisAmount>0)
{
if(temp.payoutType[k] == 0)
{
for(j=0;j<temp.payoutTo[k];j++)
{
}
thisUser = userInfos[payIn._networkId][_pi][payIn.mainTree][_userId1].user;
else if(temp.payoutType[k] == 1)
{
for(j=0;j<temp.payoutTo[k];j++)
{
}
thisUser = userInfos[payIn._networkId][_pi][payIn.mainTree][_userId2].user;
else if(temp.payoutType[k] == 2)
{
j = temp.payoutTo[k];
if ( temp.payoutTo[k] >= userInfos[payIn._networkId][_pi][payIn.mainTree].length ) j = 0;
thisUser = userInfos[payIn._networkId][_pi][payIn.mainTree][j].user;
}
else if(temp.payoutType[k] == 3)
{
j = 0;
if (payIn._userId >= temp.payoutTo[k] ) j = payIn._userId - temp.payoutTo[k];
thisUser = userInfos[payIn._networkId][_pi][payIn.mainTree][j].user;
}
else if(temp.payoutType[k] == 4)
{
poolAmount[payIn._networkId][payIn._planIndex][payIn.mainTree][temp.payoutTo[k]] = poolAmount[payIn._networkId][payIn._planIndex][payIn.mainTree][temp.payoutTo[k]] + thisAmount;
emit depositedToPoolEv(now,payIn._networkId,payIn._planIndex,thisAmount,temp.payoutTo[k], payIn.mainTree);
}
}
}
return true;
}
function processPayOut(payInput memory payIn) internal returns (bool)
{
uint8 etheroutPlanId = etherInPlans[payIn._networkId][payIn.mainTree][payIn._planIndex].etheroutPlanId;
etherOutPlan memory temp;
temp = etherOutPlans[payIn._networkId][etheroutPlanId];
uint32 _userId2 = payIn._userId;
uint32 _userId1 = _userId2;
address payable thisUser;
uint256 thisAmount;
uint8 _pi;
if( etherInPlans[payIn._networkId][payIn.mainTree][payIn._planIndex].maxChild == 0)
{
_pi = payIn._planIndex;
}
uint j;
for(uint8 k=0; k < temp.payoutType.length; k++)
{
thisAmount = payIn._paidAmount * temp.payoutPercentage[k] / 100000000;
if(thisAmount>0)
{
if(temp.payoutType[k] == 0)
{
for(j=0;j<temp.payoutTo[k];j++)
{
}
thisUser = userInfos[payIn._networkId][_pi][payIn.mainTree][_userId1].user;
else if(temp.payoutType[k] == 1)
{
for(j=0;j<temp.payoutTo[k];j++)
{
}
thisUser = userInfos[payIn._networkId][_pi][payIn.mainTree][_userId2].user;
else if(temp.payoutType[k] == 2)
{
j = temp.payoutTo[k];
if ( temp.payoutTo[k] >= userInfos[payIn._networkId][_pi][payIn.mainTree].length ) j = 0;
thisUser = userInfos[payIn._networkId][_pi][payIn.mainTree][j].user;
}
else if(temp.payoutType[k] == 3)
{
j = 0;
if (payIn._userId >= temp.payoutTo[k] ) j = payIn._userId - temp.payoutTo[k];
thisUser = userInfos[payIn._networkId][_pi][payIn.mainTree][j].user;
}
else if(temp.payoutType[k] == 4)
{
poolAmount[payIn._networkId][payIn._planIndex][payIn.mainTree][temp.payoutTo[k]] = poolAmount[payIn._networkId][payIn._planIndex][payIn.mainTree][temp.payoutTo[k]] + thisAmount;
emit depositedToPoolEv(now,payIn._networkId,payIn._planIndex,thisAmount,temp.payoutTo[k], payIn.mainTree);
}
}
}
return true;
}
function processPayOut(payInput memory payIn) internal returns (bool)
{
uint8 etheroutPlanId = etherInPlans[payIn._networkId][payIn.mainTree][payIn._planIndex].etheroutPlanId;
etherOutPlan memory temp;
temp = etherOutPlans[payIn._networkId][etheroutPlanId];
uint32 _userId2 = payIn._userId;
uint32 _userId1 = _userId2;
address payable thisUser;
uint256 thisAmount;
uint8 _pi;
if( etherInPlans[payIn._networkId][payIn.mainTree][payIn._planIndex].maxChild == 0)
{
_pi = payIn._planIndex;
}
uint j;
for(uint8 k=0; k < temp.payoutType.length; k++)
{
thisAmount = payIn._paidAmount * temp.payoutPercentage[k] / 100000000;
if(thisAmount>0)
{
if(temp.payoutType[k] == 0)
{
for(j=0;j<temp.payoutTo[k];j++)
{
}
thisUser = userInfos[payIn._networkId][_pi][payIn.mainTree][_userId1].user;
else if(temp.payoutType[k] == 1)
{
for(j=0;j<temp.payoutTo[k];j++)
{
}
thisUser = userInfos[payIn._networkId][_pi][payIn.mainTree][_userId2].user;
else if(temp.payoutType[k] == 2)
{
j = temp.payoutTo[k];
if ( temp.payoutTo[k] >= userInfos[payIn._networkId][_pi][payIn.mainTree].length ) j = 0;
thisUser = userInfos[payIn._networkId][_pi][payIn.mainTree][j].user;
}
else if(temp.payoutType[k] == 3)
{
j = 0;
if (payIn._userId >= temp.payoutTo[k] ) j = payIn._userId - temp.payoutTo[k];
thisUser = userInfos[payIn._networkId][_pi][payIn.mainTree][j].user;
}
else if(temp.payoutType[k] == 4)
{
poolAmount[payIn._networkId][payIn._planIndex][payIn.mainTree][temp.payoutTo[k]] = poolAmount[payIn._networkId][payIn._planIndex][payIn.mainTree][temp.payoutTo[k]] + thisAmount;
emit depositedToPoolEv(now,payIn._networkId,payIn._planIndex,thisAmount,temp.payoutTo[k], payIn.mainTree);
}
}
}
return true;
}
function processPayOut(payInput memory payIn) internal returns (bool)
{
uint8 etheroutPlanId = etherInPlans[payIn._networkId][payIn.mainTree][payIn._planIndex].etheroutPlanId;
etherOutPlan memory temp;
temp = etherOutPlans[payIn._networkId][etheroutPlanId];
uint32 _userId2 = payIn._userId;
uint32 _userId1 = _userId2;
address payable thisUser;
uint256 thisAmount;
uint8 _pi;
if( etherInPlans[payIn._networkId][payIn.mainTree][payIn._planIndex].maxChild == 0)
{
_pi = payIn._planIndex;
}
uint j;
for(uint8 k=0; k < temp.payoutType.length; k++)
{
thisAmount = payIn._paidAmount * temp.payoutPercentage[k] / 100000000;
if(thisAmount>0)
{
if(temp.payoutType[k] == 0)
{
for(j=0;j<temp.payoutTo[k];j++)
{
}
thisUser = userInfos[payIn._networkId][_pi][payIn.mainTree][_userId1].user;
else if(temp.payoutType[k] == 1)
{
for(j=0;j<temp.payoutTo[k];j++)
{
}
thisUser = userInfos[payIn._networkId][_pi][payIn.mainTree][_userId2].user;
else if(temp.payoutType[k] == 2)
{
j = temp.payoutTo[k];
if ( temp.payoutTo[k] >= userInfos[payIn._networkId][_pi][payIn.mainTree].length ) j = 0;
thisUser = userInfos[payIn._networkId][_pi][payIn.mainTree][j].user;
}
else if(temp.payoutType[k] == 3)
{
j = 0;
if (payIn._userId >= temp.payoutTo[k] ) j = payIn._userId - temp.payoutTo[k];
thisUser = userInfos[payIn._networkId][_pi][payIn.mainTree][j].user;
}
else if(temp.payoutType[k] == 4)
{
poolAmount[payIn._networkId][payIn._planIndex][payIn.mainTree][temp.payoutTo[k]] = poolAmount[payIn._networkId][payIn._planIndex][payIn.mainTree][temp.payoutTo[k]] + thisAmount;
emit depositedToPoolEv(now,payIn._networkId,payIn._planIndex,thisAmount,temp.payoutTo[k], payIn.mainTree);
}
}
}
return true;
}
function processPayOut(payInput memory payIn) internal returns (bool)
{
uint8 etheroutPlanId = etherInPlans[payIn._networkId][payIn.mainTree][payIn._planIndex].etheroutPlanId;
etherOutPlan memory temp;
temp = etherOutPlans[payIn._networkId][etheroutPlanId];
uint32 _userId2 = payIn._userId;
uint32 _userId1 = _userId2;
address payable thisUser;
uint256 thisAmount;
uint8 _pi;
if( etherInPlans[payIn._networkId][payIn.mainTree][payIn._planIndex].maxChild == 0)
{
_pi = payIn._planIndex;
}
uint j;
for(uint8 k=0; k < temp.payoutType.length; k++)
{
thisAmount = payIn._paidAmount * temp.payoutPercentage[k] / 100000000;
if(thisAmount>0)
{
if(temp.payoutType[k] == 0)
{
for(j=0;j<temp.payoutTo[k];j++)
{
}
thisUser = userInfos[payIn._networkId][_pi][payIn.mainTree][_userId1].user;
else if(temp.payoutType[k] == 1)
{
for(j=0;j<temp.payoutTo[k];j++)
{
}
thisUser = userInfos[payIn._networkId][_pi][payIn.mainTree][_userId2].user;
else if(temp.payoutType[k] == 2)
{
j = temp.payoutTo[k];
if ( temp.payoutTo[k] >= userInfos[payIn._networkId][_pi][payIn.mainTree].length ) j = 0;
thisUser = userInfos[payIn._networkId][_pi][payIn.mainTree][j].user;
}
else if(temp.payoutType[k] == 3)
{
j = 0;
if (payIn._userId >= temp.payoutTo[k] ) j = payIn._userId - temp.payoutTo[k];
thisUser = userInfos[payIn._networkId][_pi][payIn.mainTree][j].user;
}
else if(temp.payoutType[k] == 4)
{
poolAmount[payIn._networkId][payIn._planIndex][payIn.mainTree][temp.payoutTo[k]] = poolAmount[payIn._networkId][payIn._planIndex][payIn.mainTree][temp.payoutTo[k]] + thisAmount;
emit depositedToPoolEv(now,payIn._networkId,payIn._planIndex,thisAmount,temp.payoutTo[k], payIn.mainTree);
}
}
}
return true;
}
function processPayOut(payInput memory payIn) internal returns (bool)
{
uint8 etheroutPlanId = etherInPlans[payIn._networkId][payIn.mainTree][payIn._planIndex].etheroutPlanId;
etherOutPlan memory temp;
temp = etherOutPlans[payIn._networkId][etheroutPlanId];
uint32 _userId2 = payIn._userId;
uint32 _userId1 = _userId2;
address payable thisUser;
uint256 thisAmount;
uint8 _pi;
if( etherInPlans[payIn._networkId][payIn.mainTree][payIn._planIndex].maxChild == 0)
{
_pi = payIn._planIndex;
}
uint j;
for(uint8 k=0; k < temp.payoutType.length; k++)
{
thisAmount = payIn._paidAmount * temp.payoutPercentage[k] / 100000000;
if(thisAmount>0)
{
if(temp.payoutType[k] == 0)
{
for(j=0;j<temp.payoutTo[k];j++)
{
}
thisUser = userInfos[payIn._networkId][_pi][payIn.mainTree][_userId1].user;
else if(temp.payoutType[k] == 1)
{
for(j=0;j<temp.payoutTo[k];j++)
{
}
thisUser = userInfos[payIn._networkId][_pi][payIn.mainTree][_userId2].user;
else if(temp.payoutType[k] == 2)
{
j = temp.payoutTo[k];
if ( temp.payoutTo[k] >= userInfos[payIn._networkId][_pi][payIn.mainTree].length ) j = 0;
thisUser = userInfos[payIn._networkId][_pi][payIn.mainTree][j].user;
}
else if(temp.payoutType[k] == 3)
{
j = 0;
if (payIn._userId >= temp.payoutTo[k] ) j = payIn._userId - temp.payoutTo[k];
thisUser = userInfos[payIn._networkId][_pi][payIn.mainTree][j].user;
}
else if(temp.payoutType[k] == 4)
{
poolAmount[payIn._networkId][payIn._planIndex][payIn.mainTree][temp.payoutTo[k]] = poolAmount[payIn._networkId][payIn._planIndex][payIn.mainTree][temp.payoutTo[k]] + thisAmount;
emit depositedToPoolEv(now,payIn._networkId,payIn._planIndex,thisAmount,temp.payoutTo[k], payIn.mainTree);
}
}
}
return true;
}
}
function processPayOut(payInput memory payIn) internal returns (bool)
{
uint8 etheroutPlanId = etherInPlans[payIn._networkId][payIn.mainTree][payIn._planIndex].etheroutPlanId;
etherOutPlan memory temp;
temp = etherOutPlans[payIn._networkId][etheroutPlanId];
uint32 _userId2 = payIn._userId;
uint32 _userId1 = _userId2;
address payable thisUser;
uint256 thisAmount;
uint8 _pi;
if( etherInPlans[payIn._networkId][payIn.mainTree][payIn._planIndex].maxChild == 0)
{
_pi = payIn._planIndex;
}
uint j;
for(uint8 k=0; k < temp.payoutType.length; k++)
{
thisAmount = payIn._paidAmount * temp.payoutPercentage[k] / 100000000;
if(thisAmount>0)
{
if(temp.payoutType[k] == 0)
{
for(j=0;j<temp.payoutTo[k];j++)
{
}
thisUser = userInfos[payIn._networkId][_pi][payIn.mainTree][_userId1].user;
else if(temp.payoutType[k] == 1)
{
for(j=0;j<temp.payoutTo[k];j++)
{
}
thisUser = userInfos[payIn._networkId][_pi][payIn.mainTree][_userId2].user;
else if(temp.payoutType[k] == 2)
{
j = temp.payoutTo[k];
if ( temp.payoutTo[k] >= userInfos[payIn._networkId][_pi][payIn.mainTree].length ) j = 0;
thisUser = userInfos[payIn._networkId][_pi][payIn.mainTree][j].user;
}
else if(temp.payoutType[k] == 3)
{
j = 0;
if (payIn._userId >= temp.payoutTo[k] ) j = payIn._userId - temp.payoutTo[k];
thisUser = userInfos[payIn._networkId][_pi][payIn.mainTree][j].user;
}
else if(temp.payoutType[k] == 4)
{
poolAmount[payIn._networkId][payIn._planIndex][payIn.mainTree][temp.payoutTo[k]] = poolAmount[payIn._networkId][payIn._planIndex][payIn.mainTree][temp.payoutTo[k]] + thisAmount;
emit depositedToPoolEv(now,payIn._networkId,payIn._planIndex,thisAmount,temp.payoutTo[k], payIn.mainTree);
}
}
}
return true;
}
function processPayOut(payInput memory payIn) internal returns (bool)
{
uint8 etheroutPlanId = etherInPlans[payIn._networkId][payIn.mainTree][payIn._planIndex].etheroutPlanId;
etherOutPlan memory temp;
temp = etherOutPlans[payIn._networkId][etheroutPlanId];
uint32 _userId2 = payIn._userId;
uint32 _userId1 = _userId2;
address payable thisUser;
uint256 thisAmount;
uint8 _pi;
if( etherInPlans[payIn._networkId][payIn.mainTree][payIn._planIndex].maxChild == 0)
{
_pi = payIn._planIndex;
}
uint j;
for(uint8 k=0; k < temp.payoutType.length; k++)
{
thisAmount = payIn._paidAmount * temp.payoutPercentage[k] / 100000000;
if(thisAmount>0)
{
if(temp.payoutType[k] == 0)
{
for(j=0;j<temp.payoutTo[k];j++)
{
}
thisUser = userInfos[payIn._networkId][_pi][payIn.mainTree][_userId1].user;
else if(temp.payoutType[k] == 1)
{
for(j=0;j<temp.payoutTo[k];j++)
{
}
thisUser = userInfos[payIn._networkId][_pi][payIn.mainTree][_userId2].user;
else if(temp.payoutType[k] == 2)
{
j = temp.payoutTo[k];
if ( temp.payoutTo[k] >= userInfos[payIn._networkId][_pi][payIn.mainTree].length ) j = 0;
thisUser = userInfos[payIn._networkId][_pi][payIn.mainTree][j].user;
}
else if(temp.payoutType[k] == 3)
{
j = 0;
if (payIn._userId >= temp.payoutTo[k] ) j = payIn._userId - temp.payoutTo[k];
thisUser = userInfos[payIn._networkId][_pi][payIn.mainTree][j].user;
}
else if(temp.payoutType[k] == 4)
{
poolAmount[payIn._networkId][payIn._planIndex][payIn.mainTree][temp.payoutTo[k]] = poolAmount[payIn._networkId][payIn._planIndex][payIn.mainTree][temp.payoutTo[k]] + thisAmount;
emit depositedToPoolEv(now,payIn._networkId,payIn._planIndex,thisAmount,temp.payoutTo[k], payIn.mainTree);
}
}
}
return true;
}
}
function processPayOut(payInput memory payIn) internal returns (bool)
{
uint8 etheroutPlanId = etherInPlans[payIn._networkId][payIn.mainTree][payIn._planIndex].etheroutPlanId;
etherOutPlan memory temp;
temp = etherOutPlans[payIn._networkId][etheroutPlanId];
uint32 _userId2 = payIn._userId;
uint32 _userId1 = _userId2;
address payable thisUser;
uint256 thisAmount;
uint8 _pi;
if( etherInPlans[payIn._networkId][payIn.mainTree][payIn._planIndex].maxChild == 0)
{
_pi = payIn._planIndex;
}
uint j;
for(uint8 k=0; k < temp.payoutType.length; k++)
{
thisAmount = payIn._paidAmount * temp.payoutPercentage[k] / 100000000;
if(thisAmount>0)
{
if(temp.payoutType[k] == 0)
{
for(j=0;j<temp.payoutTo[k];j++)
{
}
thisUser = userInfos[payIn._networkId][_pi][payIn.mainTree][_userId1].user;
else if(temp.payoutType[k] == 1)
{
for(j=0;j<temp.payoutTo[k];j++)
{
}
thisUser = userInfos[payIn._networkId][_pi][payIn.mainTree][_userId2].user;
else if(temp.payoutType[k] == 2)
{
j = temp.payoutTo[k];
if ( temp.payoutTo[k] >= userInfos[payIn._networkId][_pi][payIn.mainTree].length ) j = 0;
thisUser = userInfos[payIn._networkId][_pi][payIn.mainTree][j].user;
}
else if(temp.payoutType[k] == 3)
{
j = 0;
if (payIn._userId >= temp.payoutTo[k] ) j = payIn._userId - temp.payoutTo[k];
thisUser = userInfos[payIn._networkId][_pi][payIn.mainTree][j].user;
}
else if(temp.payoutType[k] == 4)
{
poolAmount[payIn._networkId][payIn._planIndex][payIn.mainTree][temp.payoutTo[k]] = poolAmount[payIn._networkId][payIn._planIndex][payIn.mainTree][temp.payoutTo[k]] + thisAmount;
emit depositedToPoolEv(now,payIn._networkId,payIn._planIndex,thisAmount,temp.payoutTo[k], payIn.mainTree);
}
}
}
return true;
}
function processPayOut(payInput memory payIn) internal returns (bool)
{
uint8 etheroutPlanId = etherInPlans[payIn._networkId][payIn.mainTree][payIn._planIndex].etheroutPlanId;
etherOutPlan memory temp;
temp = etherOutPlans[payIn._networkId][etheroutPlanId];
uint32 _userId2 = payIn._userId;
uint32 _userId1 = _userId2;
address payable thisUser;
uint256 thisAmount;
uint8 _pi;
if( etherInPlans[payIn._networkId][payIn.mainTree][payIn._planIndex].maxChild == 0)
{
_pi = payIn._planIndex;
}
uint j;
for(uint8 k=0; k < temp.payoutType.length; k++)
{
thisAmount = payIn._paidAmount * temp.payoutPercentage[k] / 100000000;
if(thisAmount>0)
{
if(temp.payoutType[k] == 0)
{
for(j=0;j<temp.payoutTo[k];j++)
{
}
thisUser = userInfos[payIn._networkId][_pi][payIn.mainTree][_userId1].user;
else if(temp.payoutType[k] == 1)
{
for(j=0;j<temp.payoutTo[k];j++)
{
}
thisUser = userInfos[payIn._networkId][_pi][payIn.mainTree][_userId2].user;
else if(temp.payoutType[k] == 2)
{
j = temp.payoutTo[k];
if ( temp.payoutTo[k] >= userInfos[payIn._networkId][_pi][payIn.mainTree].length ) j = 0;
thisUser = userInfos[payIn._networkId][_pi][payIn.mainTree][j].user;
}
else if(temp.payoutType[k] == 3)
{
j = 0;
if (payIn._userId >= temp.payoutTo[k] ) j = payIn._userId - temp.payoutTo[k];
thisUser = userInfos[payIn._networkId][_pi][payIn.mainTree][j].user;
}
else if(temp.payoutType[k] == 4)
{
poolAmount[payIn._networkId][payIn._planIndex][payIn.mainTree][temp.payoutTo[k]] = poolAmount[payIn._networkId][payIn._planIndex][payIn.mainTree][temp.payoutTo[k]] + thisAmount;
emit depositedToPoolEv(now,payIn._networkId,payIn._planIndex,thisAmount,temp.payoutTo[k], payIn.mainTree);
}
}
}
return true;
}
function processPayOut(payInput memory payIn) internal returns (bool)
{
uint8 etheroutPlanId = etherInPlans[payIn._networkId][payIn.mainTree][payIn._planIndex].etheroutPlanId;
etherOutPlan memory temp;
temp = etherOutPlans[payIn._networkId][etheroutPlanId];
uint32 _userId2 = payIn._userId;
uint32 _userId1 = _userId2;
address payable thisUser;
uint256 thisAmount;
uint8 _pi;
if( etherInPlans[payIn._networkId][payIn.mainTree][payIn._planIndex].maxChild == 0)
{
_pi = payIn._planIndex;
}
uint j;
for(uint8 k=0; k < temp.payoutType.length; k++)
{
thisAmount = payIn._paidAmount * temp.payoutPercentage[k] / 100000000;
if(thisAmount>0)
{
if(temp.payoutType[k] == 0)
{
for(j=0;j<temp.payoutTo[k];j++)
{
}
thisUser = userInfos[payIn._networkId][_pi][payIn.mainTree][_userId1].user;
else if(temp.payoutType[k] == 1)
{
for(j=0;j<temp.payoutTo[k];j++)
{
}
thisUser = userInfos[payIn._networkId][_pi][payIn.mainTree][_userId2].user;
else if(temp.payoutType[k] == 2)
{
j = temp.payoutTo[k];
if ( temp.payoutTo[k] >= userInfos[payIn._networkId][_pi][payIn.mainTree].length ) j = 0;
thisUser = userInfos[payIn._networkId][_pi][payIn.mainTree][j].user;
}
else if(temp.payoutType[k] == 3)
{
j = 0;
if (payIn._userId >= temp.payoutTo[k] ) j = payIn._userId - temp.payoutTo[k];
thisUser = userInfos[payIn._networkId][_pi][payIn.mainTree][j].user;
}
else if(temp.payoutType[k] == 4)
{
poolAmount[payIn._networkId][payIn._planIndex][payIn.mainTree][temp.payoutTo[k]] = poolAmount[payIn._networkId][payIn._planIndex][payIn.mainTree][temp.payoutTo[k]] + thisAmount;
emit depositedToPoolEv(now,payIn._networkId,payIn._planIndex,thisAmount,temp.payoutTo[k], payIn.mainTree);
}
}
}
return true;
}
if(temp.payoutType[k] < 4) require(stackTooDeepB(payIn,thisUser,thisAmount), "amount tx fail");
function stackTooDeepB(payInput memory payIn, address payable thisUser,uint256 thisAmount) internal returns(bool)
{
require(doTransaction(payIn._networkId, address(0), thisUser,thisAmount,payIn._planIndex,payIn.mainTree,payIn._userId), "amount tx fail");
return true;
}
event doPayEv(uint256 indexed _networkId,uint8 indexed _planIndex,uint256 _poolIndex, uint256 _amount, bool indexed mainTree, address payable _user);
function doPay(uint256 _networkId,uint8 _planIndex,uint256 _poolIndex, uint256 _amount, bool mainTree, uint32 _userId) external returns(bool)
{
require(msg.sender == externalContract[_networkId], "Invalid caller" );
require(checkUserId(_networkId,0,true,tx.origin,_userId ),"_userId not matching to sender");
require(_amount <= poolAmount[_networkId][_planIndex][mainTree][_poolIndex],"not enough amount");
poolAmount[_networkId][_planIndex][mainTree][_poolIndex] = poolAmount[_networkId][_planIndex][mainTree][_poolIndex] - _amount;
address _coinAddress = coinAddress[_networkId];
if(_coinAddress == address(0))
{
tx.origin.transfer(_amount);
}
else
{
require( stableCoin(_coinAddress).transfer(tx.origin, _amount),"token transfer failed");
}
emit doPayEv(_networkId,_planIndex,_poolIndex,_amount, mainTree, tx.origin);
return true;
}
event payPlatformChargeEv(uint timeNow, uint256 indexed _networkId, uint256 indexed Amount);
function doPay(uint256 _networkId,uint8 _planIndex,uint256 _poolIndex, uint256 _amount, bool mainTree, uint32 _userId) external returns(bool)
{
require(msg.sender == externalContract[_networkId], "Invalid caller" );
require(checkUserId(_networkId,0,true,tx.origin,_userId ),"_userId not matching to sender");
require(_amount <= poolAmount[_networkId][_planIndex][mainTree][_poolIndex],"not enough amount");
poolAmount[_networkId][_planIndex][mainTree][_poolIndex] = poolAmount[_networkId][_planIndex][mainTree][_poolIndex] - _amount;
address _coinAddress = coinAddress[_networkId];
if(_coinAddress == address(0))
{
tx.origin.transfer(_amount);
}
else
{
require( stableCoin(_coinAddress).transfer(tx.origin, _amount),"token transfer failed");
}
emit doPayEv(_networkId,_planIndex,_poolIndex,_amount, mainTree, tx.origin);
return true;
}
event payPlatformChargeEv(uint timeNow, uint256 indexed _networkId, uint256 indexed Amount);
function doPay(uint256 _networkId,uint8 _planIndex,uint256 _poolIndex, uint256 _amount, bool mainTree, uint32 _userId) external returns(bool)
{
require(msg.sender == externalContract[_networkId], "Invalid caller" );
require(checkUserId(_networkId,0,true,tx.origin,_userId ),"_userId not matching to sender");
require(_amount <= poolAmount[_networkId][_planIndex][mainTree][_poolIndex],"not enough amount");
poolAmount[_networkId][_planIndex][mainTree][_poolIndex] = poolAmount[_networkId][_planIndex][mainTree][_poolIndex] - _amount;
address _coinAddress = coinAddress[_networkId];
if(_coinAddress == address(0))
{
tx.origin.transfer(_amount);
}
else
{
require( stableCoin(_coinAddress).transfer(tx.origin, _amount),"token transfer failed");
}
emit doPayEv(_networkId,_planIndex,_poolIndex,_amount, mainTree, tx.origin);
return true;
}
event payPlatformChargeEv(uint timeNow, uint256 indexed _networkId, uint256 indexed Amount);
function payPlatformCharge(uint256 _networkId, uint256 _paidAmount) internal returns(bool)
{
uint256 amount = _paidAmount * platFormFeePercentage / 100000000;
require(doTransaction(_networkId, address(0), owner,amount,0,false,0), "amount tx fail");
emit payPlatformChargeEv(now,_networkId,amount);
return true;
}
function regUserViaContract(uint256 _networkId,uint32 _referrerId,uint32 _parentId, uint256 amount) public returns(bool)
{
require(msg.sender == externalContract[_networkId], "Invalid caller" );
require(regUser(_networkId,_referrerId,_parentId, amount),"reg user fail");
return true;
}
function buyLevelViaContract(uint256 _networkId,uint8 _planIndex, uint32 _userId, uint256 amount) public returns(bool)
{
require(msg.sender == externalContract[_networkId], "Invalid caller" );
require(buyLevel(_networkId,_planIndex,_userId, amount),"reg user fail");
return true;
}
function findBlankSlot(uint256 _networkId,uint8 _planIndex,uint32 _referrerId,bool mainTree, uint8 _maxChild) public view returns(uint32)
{
if(userInfos[_networkId][_planIndex][mainTree][_referrerId].childCount < _maxChild) return _referrerId;
uint32[] memory referrals = new uint32[](126);
uint j;
for(j=0;j<_maxChild;j++)
{
referrals[j] = userInfos[_networkId][_planIndex][mainTree][_referrerId].childIds[j];
}
uint32 blankSlotId;
bool noBlankSlot = true;
for(uint i = 0; i < 126; i++)
{
if(userInfos[_networkId][_planIndex][mainTree][referrals[i]].childCount >= _maxChild)
{
if(j < 126 - _maxChild)
{
for(j=j;j< j + _maxChild;j++)
{
referrals[j] = userInfos[_networkId][_planIndex][mainTree][referrals[i]].childIds[j-_maxChild];
}
}
}
else
{
noBlankSlot = false;
blankSlotId = referrals[i];
break;
}
}
require(!noBlankSlot, 'No Free Referrer');
return blankSlotId;
}
function findBlankSlot(uint256 _networkId,uint8 _planIndex,uint32 _referrerId,bool mainTree, uint8 _maxChild) public view returns(uint32)
{
if(userInfos[_networkId][_planIndex][mainTree][_referrerId].childCount < _maxChild) return _referrerId;
uint32[] memory referrals = new uint32[](126);
uint j;
for(j=0;j<_maxChild;j++)
{
referrals[j] = userInfos[_networkId][_planIndex][mainTree][_referrerId].childIds[j];
}
uint32 blankSlotId;
bool noBlankSlot = true;
for(uint i = 0; i < 126; i++)
{
if(userInfos[_networkId][_planIndex][mainTree][referrals[i]].childCount >= _maxChild)
{
if(j < 126 - _maxChild)
{
for(j=j;j< j + _maxChild;j++)
{
referrals[j] = userInfos[_networkId][_planIndex][mainTree][referrals[i]].childIds[j-_maxChild];
}
}
}
else
{
noBlankSlot = false;
blankSlotId = referrals[i];
break;
}
}
require(!noBlankSlot, 'No Free Referrer');
return blankSlotId;
}
function findBlankSlot(uint256 _networkId,uint8 _planIndex,uint32 _referrerId,bool mainTree, uint8 _maxChild) public view returns(uint32)
{
if(userInfos[_networkId][_planIndex][mainTree][_referrerId].childCount < _maxChild) return _referrerId;
uint32[] memory referrals = new uint32[](126);
uint j;
for(j=0;j<_maxChild;j++)
{
referrals[j] = userInfos[_networkId][_planIndex][mainTree][_referrerId].childIds[j];
}
uint32 blankSlotId;
bool noBlankSlot = true;
for(uint i = 0; i < 126; i++)
{
if(userInfos[_networkId][_planIndex][mainTree][referrals[i]].childCount >= _maxChild)
{
if(j < 126 - _maxChild)
{
for(j=j;j< j + _maxChild;j++)
{
referrals[j] = userInfos[_networkId][_planIndex][mainTree][referrals[i]].childIds[j-_maxChild];
}
}
}
else
{
noBlankSlot = false;
blankSlotId = referrals[i];
break;
}
}
require(!noBlankSlot, 'No Free Referrer');
return blankSlotId;
}
function findBlankSlot(uint256 _networkId,uint8 _planIndex,uint32 _referrerId,bool mainTree, uint8 _maxChild) public view returns(uint32)
{
if(userInfos[_networkId][_planIndex][mainTree][_referrerId].childCount < _maxChild) return _referrerId;
uint32[] memory referrals = new uint32[](126);
uint j;
for(j=0;j<_maxChild;j++)
{
referrals[j] = userInfos[_networkId][_planIndex][mainTree][_referrerId].childIds[j];
}
uint32 blankSlotId;
bool noBlankSlot = true;
for(uint i = 0; i < 126; i++)
{
if(userInfos[_networkId][_planIndex][mainTree][referrals[i]].childCount >= _maxChild)
{
if(j < 126 - _maxChild)
{
for(j=j;j< j + _maxChild;j++)
{
referrals[j] = userInfos[_networkId][_planIndex][mainTree][referrals[i]].childIds[j-_maxChild];
}
}
}
else
{
noBlankSlot = false;
blankSlotId = referrals[i];
break;
}
}
require(!noBlankSlot, 'No Free Referrer');
return blankSlotId;
}
function findBlankSlot(uint256 _networkId,uint8 _planIndex,uint32 _referrerId,bool mainTree, uint8 _maxChild) public view returns(uint32)
{
if(userInfos[_networkId][_planIndex][mainTree][_referrerId].childCount < _maxChild) return _referrerId;
uint32[] memory referrals = new uint32[](126);
uint j;
for(j=0;j<_maxChild;j++)
{
referrals[j] = userInfos[_networkId][_planIndex][mainTree][_referrerId].childIds[j];
}
uint32 blankSlotId;
bool noBlankSlot = true;
for(uint i = 0; i < 126; i++)
{
if(userInfos[_networkId][_planIndex][mainTree][referrals[i]].childCount >= _maxChild)
{
if(j < 126 - _maxChild)
{
for(j=j;j< j + _maxChild;j++)
{
referrals[j] = userInfos[_networkId][_planIndex][mainTree][referrals[i]].childIds[j-_maxChild];
}
}
}
else
{
noBlankSlot = false;
blankSlotId = referrals[i];
break;
}
}
require(!noBlankSlot, 'No Free Referrer');
return blankSlotId;
}
function findBlankSlot(uint256 _networkId,uint8 _planIndex,uint32 _referrerId,bool mainTree, uint8 _maxChild) public view returns(uint32)
{
if(userInfos[_networkId][_planIndex][mainTree][_referrerId].childCount < _maxChild) return _referrerId;
uint32[] memory referrals = new uint32[](126);
uint j;
for(j=0;j<_maxChild;j++)
{
referrals[j] = userInfos[_networkId][_planIndex][mainTree][_referrerId].childIds[j];
}
uint32 blankSlotId;
bool noBlankSlot = true;
for(uint i = 0; i < 126; i++)
{
if(userInfos[_networkId][_planIndex][mainTree][referrals[i]].childCount >= _maxChild)
{
if(j < 126 - _maxChild)
{
for(j=j;j< j + _maxChild;j++)
{
referrals[j] = userInfos[_networkId][_planIndex][mainTree][referrals[i]].childIds[j-_maxChild];
}
}
}
else
{
noBlankSlot = false;
blankSlotId = referrals[i];
break;
}
}
require(!noBlankSlot, 'No Free Referrer');
return blankSlotId;
}
function findBlankSlot(uint256 _networkId,uint8 _planIndex,uint32 _referrerId,bool mainTree, uint8 _maxChild) public view returns(uint32)
{
if(userInfos[_networkId][_planIndex][mainTree][_referrerId].childCount < _maxChild) return _referrerId;
uint32[] memory referrals = new uint32[](126);
uint j;
for(j=0;j<_maxChild;j++)
{
referrals[j] = userInfos[_networkId][_planIndex][mainTree][_referrerId].childIds[j];
}
uint32 blankSlotId;
bool noBlankSlot = true;
for(uint i = 0; i < 126; i++)
{
if(userInfos[_networkId][_planIndex][mainTree][referrals[i]].childCount >= _maxChild)
{
if(j < 126 - _maxChild)
{
for(j=j;j< j + _maxChild;j++)
{
referrals[j] = userInfos[_networkId][_planIndex][mainTree][referrals[i]].childIds[j-_maxChild];
}
}
}
else
{
noBlankSlot = false;
blankSlotId = referrals[i];
break;
}
}
require(!noBlankSlot, 'No Free Referrer');
return blankSlotId;
}
function viewUserInfosLength(uint256 _networkId, uint256 _planIndex, bool mainTree) public view returns(uint256)
{
return userInfos[_networkId][_planIndex][mainTree].length;
}
function viewUserInfosChildId(uint256 _networkId, uint256 _planIndex,bool mainTree, uint256 _userId, uint256 _childIndex) public view returns(uint256)
{
if(_userId < userInfos[_networkId][_planIndex][mainTree].length && _childIndex < userInfos[_networkId][_planIndex][mainTree][_userId].childIds.length)
{
return userInfos[_networkId][_planIndex][mainTree][_userId].childIds[_childIndex];
}
return 0;
}
function viewUserInfosChildId(uint256 _networkId, uint256 _planIndex,bool mainTree, uint256 _userId, uint256 _childIndex) public view returns(uint256)
{
if(_userId < userInfos[_networkId][_planIndex][mainTree].length && _childIndex < userInfos[_networkId][_planIndex][mainTree][_userId].childIds.length)
{
return userInfos[_networkId][_planIndex][mainTree][_userId].childIds[_childIndex];
}
return 0;
}
function viewEtherOutPlanSetting(uint256 _networkId, uint256 _planIndex, uint256 _payoutIndex) public view returns (uint8 _payoutType, uint32 _payoutTo, uint32 _payoutPercentage )
{
if(_planIndex < etherOutPlans[_networkId].length)
{
_payoutType = etherOutPlans[_networkId][_planIndex].payoutType[_payoutIndex];
_payoutTo = etherOutPlans[_networkId][_planIndex].payoutTo[_payoutIndex];
_payoutPercentage = etherOutPlans[_networkId][_planIndex].payoutPercentage[_payoutIndex];
}
}
function viewEtherOutPlanSetting(uint256 _networkId, uint256 _planIndex, uint256 _payoutIndex) public view returns (uint8 _payoutType, uint32 _payoutTo, uint32 _payoutPercentage )
{
if(_planIndex < etherOutPlans[_networkId].length)
{
_payoutType = etherOutPlans[_networkId][_planIndex].payoutType[_payoutIndex];
_payoutTo = etherOutPlans[_networkId][_planIndex].payoutTo[_payoutIndex];
_payoutPercentage = etherOutPlans[_networkId][_planIndex].payoutPercentage[_payoutIndex];
}
}
function payoutPercentageSum(uint256 _networkId, uint256 etherOutPlanIndex) public view returns(uint256)
{
uint256 i;
uint32[] memory _payoutPercentage = etherOutPlans[_networkId][etherOutPlanIndex].payoutPercentage;
uint256 totalPercentSum;
for(i=0; i< _payoutPercentage.length; i++)
{
totalPercentSum += _payoutPercentage[i];
}
return totalPercentSum;
}
function payoutPercentageSum(uint256 _networkId, uint256 etherOutPlanIndex) public view returns(uint256)
{
uint256 i;
uint32[] memory _payoutPercentage = etherOutPlans[_networkId][etherOutPlanIndex].payoutPercentage;
uint256 totalPercentSum;
for(i=0; i< _payoutPercentage.length; i++)
{
totalPercentSum += _payoutPercentage[i];
}
return totalPercentSum;
}
function checkUserId(uint256 _networkId, uint8 _planIndex, bool mainTree, address payable _user, uint32 _userId ) public view returns (bool)
{
for(uint8 i; i< userIndex[_networkId][_planIndex][mainTree][_user].length;i++)
{
if(userIndex[_networkId][_planIndex][mainTree][_user][i] == _userId) return true;
}
return false;
}
function checkUserId(uint256 _networkId, uint8 _planIndex, bool mainTree, address payable _user, uint32 _userId ) public view returns (bool)
{
for(uint8 i; i< userIndex[_networkId][_planIndex][mainTree][_user].length;i++)
{
if(userIndex[_networkId][_planIndex][mainTree][_user][i] == _userId) return true;
}
return false;
}
function setNetworkPrice(uint256 _networkPrice) public onlyOwner returns (bool)
{
networkPrice = _networkPrice;
return true;
}
function setMinPlanPrice(uint256 _minPlanPrice) public onlyOwner returns (bool)
{
minPlanPrice = _minPlanPrice;
return true;
}
function setPlatFormFeePercentage(uint256 _platFormFeePercentage) public onlyOwner returns (bool)
{
platFormFeePercentage = _platFormFeePercentage;
return true;
}
function setValidStableCoin(address _coinAddress, uint256 _etherValue) public onlyOwner returns(bool)
{
validStableCoin[_coinAddress] = _etherValue;
return true;
}
} | 695,971 |
./partial_match/42/0x83932122bD37778bBa634608B66ebb68f51C9D25/sources/yVault.sol | Additional check for deflationary tokens | function deposit(uint _amount) public {
uint _before = token.balanceOf(address(this));
token.safeTransferFrom(msg.sender, address(this), _amount);
uint _after = token.balanceOf(address(this));
_amount = _after.sub(_before);
uint shares = 0;
shares = (_amount*10**5).div(getPricePerFullShare());
_mint(msg.sender, shares);
}
| 8,998,802 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.3;
import "./UbiquityAlgorithmicDollarManager.sol";
import "./interfaces/IDollarMintingCalculator.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./TWAPOracle.sol";
import "./libs/ABDKMathQuad.sol";
/// @title A mock coupon calculator that always returns a constant
contract DollarMintingCalculator is IDollarMintingCalculator {
using ABDKMathQuad for uint256;
using ABDKMathQuad for bytes16;
bytes16 private immutable _one = (uint256(1 ether)).fromUInt();
UbiquityAlgorithmicDollarManager public manager;
/// @param _manager the address of the manager contract so we can fetch variables
constructor(address _manager) {
manager = UbiquityAlgorithmicDollarManager(_manager);
}
/// @notice returns (TWAP_PRICE -1) * UAD_Total_Supply
function getDollarsToMint() external view override returns (uint256) {
TWAPOracle oracle = TWAPOracle(manager.twapOracleAddress());
uint256 twapPrice = oracle.consult(manager.dollarTokenAddress());
require(twapPrice > 1, "DollarMintingCalculator: not > 1");
return
twapPrice
.fromUInt()
.sub(_one)
.mul(
(
IERC20(manager.dollarTokenAddress())
.totalSupply()
.fromUInt()
.div(_one)
)
)
.toUInt();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.3;
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./interfaces/IUbiquityAlgorithmicDollar.sol";
import "./interfaces/ICurveFactory.sol";
import "./interfaces/IMetaPool.sol";
import "./TWAPOracle.sol";
/// @title A central config for the uAD system. Also acts as a central
/// access control manager.
/// @notice For storing constants. For storing variables and allowing them to
/// be changed by the admin (governance)
/// @dev This should be used as a central access control manager which other
/// contracts use to check permissions
contract UbiquityAlgorithmicDollarManager is AccessControl {
using SafeERC20 for IERC20;
bytes32 public constant UBQ_MINTER_ROLE = keccak256("UBQ_MINTER_ROLE");
bytes32 public constant UBQ_BURNER_ROLE = keccak256("UBQ_BURNER_ROLE");
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
bytes32 public constant COUPON_MANAGER_ROLE = keccak256("COUPON_MANAGER");
bytes32 public constant BONDING_MANAGER_ROLE = keccak256("BONDING_MANAGER");
bytes32 public constant INCENTIVE_MANAGER_ROLE =
keccak256("INCENTIVE_MANAGER");
bytes32 public constant UBQ_TOKEN_MANAGER_ROLE =
keccak256("UBQ_TOKEN_MANAGER_ROLE");
address public twapOracleAddress;
address public debtCouponAddress;
address public dollarTokenAddress; // uAD
address public couponCalculatorAddress;
address public dollarMintingCalculatorAddress;
address public bondingShareAddress;
address public bondingContractAddress;
address public stableSwapMetaPoolAddress;
address public curve3PoolTokenAddress; // 3CRV
address public treasuryAddress;
address public governanceTokenAddress; // uGOV
address public sushiSwapPoolAddress; // sushi pool uAD-uGOV
address public masterChefAddress;
address public formulasAddress;
address public autoRedeemTokenAddress; // uAR
address public uarCalculatorAddress; // uAR calculator
//key = address of couponmanager, value = excessdollardistributor
mapping(address => address) private _excessDollarDistributors;
modifier onlyAdmin() {
require(
hasRole(DEFAULT_ADMIN_ROLE, msg.sender),
"uADMGR: Caller is not admin"
);
_;
}
constructor(address _admin) {
_setupRole(DEFAULT_ADMIN_ROLE, _admin);
_setupRole(UBQ_MINTER_ROLE, _admin);
_setupRole(PAUSER_ROLE, _admin);
_setupRole(COUPON_MANAGER_ROLE, _admin);
_setupRole(BONDING_MANAGER_ROLE, _admin);
_setupRole(INCENTIVE_MANAGER_ROLE, _admin);
_setupRole(UBQ_TOKEN_MANAGER_ROLE, address(this));
}
// TODO Add a generic setter for extra addresses that needs to be linked
function setTwapOracleAddress(address _twapOracleAddress)
external
onlyAdmin
{
twapOracleAddress = _twapOracleAddress;
// to be removed
TWAPOracle oracle = TWAPOracle(twapOracleAddress);
oracle.update();
}
function setuARTokenAddress(address _uarTokenAddress) external onlyAdmin {
autoRedeemTokenAddress = _uarTokenAddress;
}
function setDebtCouponAddress(address _debtCouponAddress)
external
onlyAdmin
{
debtCouponAddress = _debtCouponAddress;
}
function setIncentiveToUAD(address _account, address _incentiveAddress)
external
onlyAdmin
{
IUbiquityAlgorithmicDollar(dollarTokenAddress).setIncentiveContract(
_account,
_incentiveAddress
);
}
function setDollarTokenAddress(address _dollarTokenAddress)
external
onlyAdmin
{
dollarTokenAddress = _dollarTokenAddress;
}
function setGovernanceTokenAddress(address _governanceTokenAddress)
external
onlyAdmin
{
governanceTokenAddress = _governanceTokenAddress;
}
function setSushiSwapPoolAddress(address _sushiSwapPoolAddress)
external
onlyAdmin
{
sushiSwapPoolAddress = _sushiSwapPoolAddress;
}
function setUARCalculatorAddress(address _uarCalculatorAddress)
external
onlyAdmin
{
uarCalculatorAddress = _uarCalculatorAddress;
}
function setCouponCalculatorAddress(address _couponCalculatorAddress)
external
onlyAdmin
{
couponCalculatorAddress = _couponCalculatorAddress;
}
function setDollarMintingCalculatorAddress(
address _dollarMintingCalculatorAddress
) external onlyAdmin {
dollarMintingCalculatorAddress = _dollarMintingCalculatorAddress;
}
function setExcessDollarsDistributor(
address debtCouponManagerAddress,
address excessCouponDistributor
) external onlyAdmin {
_excessDollarDistributors[
debtCouponManagerAddress
] = excessCouponDistributor;
}
function setMasterChefAddress(address _masterChefAddress)
external
onlyAdmin
{
masterChefAddress = _masterChefAddress;
}
function setFormulasAddress(address _formulasAddress) external onlyAdmin {
formulasAddress = _formulasAddress;
}
function setBondingShareAddress(address _bondingShareAddress)
external
onlyAdmin
{
bondingShareAddress = _bondingShareAddress;
}
function setStableSwapMetaPoolAddress(address _stableSwapMetaPoolAddress)
external
onlyAdmin
{
stableSwapMetaPoolAddress = _stableSwapMetaPoolAddress;
}
/**
@notice set the bonding bontract smart contract address
@dev bonding contract participants deposit curve LP token
for a certain duration to earn uGOV and more curve LP token
@param _bondingContractAddress bonding contract address
*/
function setBondingContractAddress(address _bondingContractAddress)
external
onlyAdmin
{
bondingContractAddress = _bondingContractAddress;
}
/**
@notice set the treasury address
@dev the treasury fund is used to maintain the protocol
@param _treasuryAddress treasury fund address
*/
function setTreasuryAddress(address _treasuryAddress) external onlyAdmin {
treasuryAddress = _treasuryAddress;
}
/**
@notice deploy a new Curve metapools for uAD Token uAD/3Pool
@dev From the curve documentation for uncollateralized algorithmic
stablecoins amplification should be 5-10
@param _curveFactory MetaPool factory address
@param _crvBasePool Address of the base pool to use within the new metapool.
@param _crv3PoolTokenAddress curve 3Pool token Address
@param _amplificationCoefficient amplification coefficient. The smaller
it is the closer to a constant product we are.
@param _fee Trade fee, given as an integer with 1e10 precision.
*/
function deployStableSwapPool(
address _curveFactory,
address _crvBasePool,
address _crv3PoolTokenAddress,
uint256 _amplificationCoefficient,
uint256 _fee
) external onlyAdmin {
// Create new StableSwap meta pool (uAD <-> 3Crv)
address metaPool =
ICurveFactory(_curveFactory).deploy_metapool(
_crvBasePool,
ERC20(dollarTokenAddress).name(),
ERC20(dollarTokenAddress).symbol(),
dollarTokenAddress,
_amplificationCoefficient,
_fee
);
stableSwapMetaPoolAddress = metaPool;
// Approve the newly-deployed meta pool to transfer this contract's funds
uint256 crv3PoolTokenAmount =
IERC20(_crv3PoolTokenAddress).balanceOf(address(this));
uint256 uADTokenAmount =
IERC20(dollarTokenAddress).balanceOf(address(this));
// safe approve revert if approve from non-zero to non-zero allowance
IERC20(_crv3PoolTokenAddress).safeApprove(metaPool, 0);
IERC20(_crv3PoolTokenAddress).safeApprove(
metaPool,
crv3PoolTokenAmount
);
IERC20(dollarTokenAddress).safeApprove(metaPool, 0);
IERC20(dollarTokenAddress).safeApprove(metaPool, uADTokenAmount);
// coin at index 0 is uAD and index 1 is 3CRV
require(
IMetaPool(metaPool).coins(0) == dollarTokenAddress &&
IMetaPool(metaPool).coins(1) == _crv3PoolTokenAddress,
"uADMGR: COIN_ORDER_MISMATCH"
);
// Add the initial liquidity to the StableSwap meta pool
uint256[2] memory amounts =
[
IERC20(dollarTokenAddress).balanceOf(address(this)),
IERC20(_crv3PoolTokenAddress).balanceOf(address(this))
];
// set curve 3Pool address
curve3PoolTokenAddress = _crv3PoolTokenAddress;
IMetaPool(metaPool).add_liquidity(amounts, 0, msg.sender);
}
function getExcessDollarsDistributor(address _debtCouponManagerAddress)
external
view
returns (address)
{
return _excessDollarDistributors[_debtCouponManagerAddress];
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.3;
import "@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol";
/// @title A mechanism for calculating dollars to be minted
interface IDollarMintingCalculator {
function getDollarsToMint() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.3;
import "./interfaces/IMetaPool.sol";
contract TWAPOracle {
address public immutable pool;
address public immutable token0;
address public immutable token1;
uint256 public price0Average;
uint256 public price1Average;
uint256 public pricesBlockTimestampLast;
uint256[2] public priceCumulativeLast;
constructor(
address _pool,
address _uADtoken0,
address _curve3CRVtoken1
) {
pool = _pool;
// coin at index 0 is uAD and index 1 is 3CRV
require(
IMetaPool(_pool).coins(0) == _uADtoken0 &&
IMetaPool(_pool).coins(1) == _curve3CRVtoken1,
"TWAPOracle: COIN_ORDER_MISMATCH"
);
token0 = _uADtoken0;
token1 = _curve3CRVtoken1;
uint256 _reserve0 = uint112(IMetaPool(_pool).balances(0));
uint256 _reserve1 = uint112(IMetaPool(_pool).balances(1));
// ensure that there's liquidity in the pair
require(_reserve0 != 0 && _reserve1 != 0, "TWAPOracle: NO_RESERVES");
// ensure that pair balance is perfect
require(_reserve0 == _reserve1, "TWAPOracle: PAIR_UNBALANCED");
priceCumulativeLast = IMetaPool(_pool).get_price_cumulative_last();
pricesBlockTimestampLast = IMetaPool(_pool).block_timestamp_last();
price0Average = 1 ether;
price1Average = 1 ether;
}
// calculate average price
function update() external {
(uint256[2] memory priceCumulative, uint256 blockTimestamp) =
_currentCumulativePrices();
if (blockTimestamp - pricesBlockTimestampLast > 0) {
// get the balances between now and the last price cumulative snapshot
uint256[2] memory twapBalances =
IMetaPool(pool).get_twap_balances(
priceCumulativeLast,
priceCumulative,
blockTimestamp - pricesBlockTimestampLast
);
// price to exchange amounIn uAD to 3CRV based on TWAP
price0Average = IMetaPool(pool).get_dy(0, 1, 1 ether, twapBalances);
// price to exchange amounIn 3CRV to uAD based on TWAP
price1Average = IMetaPool(pool).get_dy(1, 0, 1 ether, twapBalances);
// we update the priceCumulative
priceCumulativeLast = priceCumulative;
pricesBlockTimestampLast = blockTimestamp;
}
}
// note this will always return 0 before update has been called successfully
// for the first time.
function consult(address token) external view returns (uint256 amountOut) {
if (token == token0) {
// price to exchange 1 uAD to 3CRV based on TWAP
amountOut = price0Average;
} else {
require(token == token1, "TWAPOracle: INVALID_TOKEN");
// price to exchange 1 3CRV to uAD based on TWAP
amountOut = price1Average;
}
}
function _currentCumulativePrices()
internal
view
returns (uint256[2] memory priceCumulative, uint256 blockTimestamp)
{
priceCumulative = IMetaPool(pool).get_price_cumulative_last();
blockTimestamp = IMetaPool(pool).block_timestamp_last();
}
}
// SPDX-License-Identifier: BSD-4-Clause
/*
* ABDK Math Quad Smart Contract Library. Copyright © 2019 by ABDK Consulting.
* Author: Mikhail Vladimirov <[email protected]>
*/
pragma solidity ^0.8.0;
/**
* Smart contract library of mathematical functions operating with IEEE 754
* quadruple-precision binary floating-point numbers (quadruple precision
* numbers). As long as quadruple precision numbers are 16-bytes long, they are
* represented by bytes16 type.
*/
library ABDKMathQuad {
/*
* 0.
*/
bytes16 private constant _POSITIVE_ZERO =
0x00000000000000000000000000000000;
/*
* -0.
*/
bytes16 private constant _NEGATIVE_ZERO =
0x80000000000000000000000000000000;
/*
* +Infinity.
*/
bytes16 private constant _POSITIVE_INFINITY =
0x7FFF0000000000000000000000000000;
/*
* -Infinity.
*/
bytes16 private constant _NEGATIVE_INFINITY =
0xFFFF0000000000000000000000000000;
/*
* Canonical NaN value.
*/
bytes16 private constant NaN = 0x7FFF8000000000000000000000000000;
/**
* Convert signed 256-bit integer number into quadruple precision number.
*
* @param x signed 256-bit integer number
* @return quadruple precision number
*/
function fromInt(int256 x) internal pure returns (bytes16) {
unchecked {
if (x == 0) return bytes16(0);
else {
// We rely on overflow behavior here
uint256 result = uint256(x > 0 ? x : -x);
uint256 msb = mostSignificantBit(result);
if (msb < 112) result <<= 112 - msb;
else if (msb > 112) result >>= msb - 112;
result =
(result & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF) |
((16383 + msb) << 112);
if (x < 0) result |= 0x80000000000000000000000000000000;
return bytes16(uint128(result));
}
}
}
/**
* Convert quadruple precision number into signed 256-bit integer number
* rounding towards zero. Revert on overflow.
*
* @param x quadruple precision number
* @return signed 256-bit integer number
*/
function toInt(bytes16 x) internal pure returns (int256) {
unchecked {
uint256 exponent = (uint128(x) >> 112) & 0x7FFF;
require(exponent <= 16638); // Overflow
if (exponent < 16383) return 0; // Underflow
uint256 result =
(uint256(uint128(x)) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF) |
0x10000000000000000000000000000;
if (exponent < 16495) result >>= 16495 - exponent;
else if (exponent > 16495) result <<= exponent - 16495;
if (uint128(x) >= 0x80000000000000000000000000000000) {
// Negative
require(
result <=
0x8000000000000000000000000000000000000000000000000000000000000000
);
return -int256(result); // We rely on overflow behavior here
} else {
require(
result <=
0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
);
return int256(result);
}
}
}
/**
* Convert unsigned 256-bit integer number into quadruple precision number.
*
* @param x unsigned 256-bit integer number
* @return quadruple precision number
*/
function fromUInt(uint256 x) internal pure returns (bytes16) {
unchecked {
if (x == 0) return bytes16(0);
else {
uint256 result = x;
uint256 msb = mostSignificantBit(result);
if (msb < 112) result <<= 112 - msb;
else if (msb > 112) result >>= msb - 112;
result =
(result & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF) |
((16383 + msb) << 112);
return bytes16(uint128(result));
}
}
}
/**
* Convert quadruple precision number into unsigned 256-bit integer number
* rounding towards zero. Revert on underflow. Note, that negative floating
* point numbers in range (-1.0 .. 0.0) may be converted to unsigned integer
* without error, because they are rounded to zero.
*
* @param x quadruple precision number
* @return unsigned 256-bit integer number
*/
function toUInt(bytes16 x) internal pure returns (uint256) {
unchecked {
uint256 exponent = (uint128(x) >> 112) & 0x7FFF;
if (exponent < 16383) return 0; // Underflow
require(uint128(x) < 0x80000000000000000000000000000000); // Negative
require(exponent <= 16638); // Overflow
uint256 result =
(uint256(uint128(x)) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF) |
0x10000000000000000000000000000;
if (exponent < 16495) result >>= 16495 - exponent;
else if (exponent > 16495) result <<= exponent - 16495;
return result;
}
}
/**
* Convert signed 128.128 bit fixed point number into quadruple precision
* number.
*
* @param x signed 128.128 bit fixed point number
* @return quadruple precision number
*/
function from128x128(int256 x) internal pure returns (bytes16) {
unchecked {
if (x == 0) return bytes16(0);
else {
// We rely on overflow behavior here
uint256 result = uint256(x > 0 ? x : -x);
uint256 msb = mostSignificantBit(result);
if (msb < 112) result <<= 112 - msb;
else if (msb > 112) result >>= msb - 112;
result =
(result & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF) |
((16255 + msb) << 112);
if (x < 0) result |= 0x80000000000000000000000000000000;
return bytes16(uint128(result));
}
}
}
/**
* Convert quadruple precision number into signed 128.128 bit fixed point
* number. Revert on overflow.
*
* @param x quadruple precision number
* @return signed 128.128 bit fixed point number
*/
function to128x128(bytes16 x) internal pure returns (int256) {
unchecked {
uint256 exponent = (uint128(x) >> 112) & 0x7FFF;
require(exponent <= 16510); // Overflow
if (exponent < 16255) return 0; // Underflow
uint256 result =
(uint256(uint128(x)) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF) |
0x10000000000000000000000000000;
if (exponent < 16367) result >>= 16367 - exponent;
else if (exponent > 16367) result <<= exponent - 16367;
if (uint128(x) >= 0x80000000000000000000000000000000) {
// Negative
require(
result <=
0x8000000000000000000000000000000000000000000000000000000000000000
);
return -int256(result); // We rely on overflow behavior here
} else {
require(
result <=
0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
);
return int256(result);
}
}
}
/**
* Convert signed 64.64 bit fixed point number into quadruple precision
* number.
*
* @param x signed 64.64 bit fixed point number
* @return quadruple precision number
*/
function from64x64(int128 x) internal pure returns (bytes16) {
unchecked {
if (x == 0) return bytes16(0);
else {
// We rely on overflow behavior here
uint256 result = uint128(x > 0 ? x : -x);
uint256 msb = mostSignificantBit(result);
if (msb < 112) result <<= 112 - msb;
else if (msb > 112) result >>= msb - 112;
result =
(result & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF) |
((16319 + msb) << 112);
if (x < 0) result |= 0x80000000000000000000000000000000;
return bytes16(uint128(result));
}
}
}
/**
* Convert quadruple precision number into signed 64.64 bit fixed point
* number. Revert on overflow.
*
* @param x quadruple precision number
* @return signed 64.64 bit fixed point number
*/
function to64x64(bytes16 x) internal pure returns (int128) {
unchecked {
uint256 exponent = (uint128(x) >> 112) & 0x7FFF;
require(exponent <= 16446); // Overflow
if (exponent < 16319) return 0; // Underflow
uint256 result =
(uint256(uint128(x)) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF) |
0x10000000000000000000000000000;
if (exponent < 16431) result >>= 16431 - exponent;
else if (exponent > 16431) result <<= exponent - 16431;
if (uint128(x) >= 0x80000000000000000000000000000000) {
// Negative
require(result <= 0x80000000000000000000000000000000);
return -int128(int256(result)); // We rely on overflow behavior here
} else {
require(result <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return int128(int256(result));
}
}
}
/**
* Convert octuple precision number into quadruple precision number.
*
* @param x octuple precision number
* @return quadruple precision number
*/
function fromOctuple(bytes32 x) internal pure returns (bytes16) {
unchecked {
bool negative =
x &
0x8000000000000000000000000000000000000000000000000000000000000000 >
0;
uint256 exponent = (uint256(x) >> 236) & 0x7FFFF;
uint256 significand =
uint256(x) &
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (exponent == 0x7FFFF) {
if (significand > 0) return NaN;
else return negative ? _NEGATIVE_INFINITY : _POSITIVE_INFINITY;
}
if (exponent > 278526)
return negative ? _NEGATIVE_INFINITY : _POSITIVE_INFINITY;
else if (exponent < 245649)
return negative ? _NEGATIVE_ZERO : _POSITIVE_ZERO;
else if (exponent < 245761) {
significand =
(significand |
0x100000000000000000000000000000000000000000000000000000000000) >>
(245885 - exponent);
exponent = 0;
} else {
significand >>= 124;
exponent -= 245760;
}
uint128 result = uint128(significand | (exponent << 112));
if (negative) result |= 0x80000000000000000000000000000000;
return bytes16(result);
}
}
/**
* Convert quadruple precision number into octuple precision number.
*
* @param x quadruple precision number
* @return octuple precision number
*/
function toOctuple(bytes16 x) internal pure returns (bytes32) {
unchecked {
uint256 exponent = (uint128(x) >> 112) & 0x7FFF;
uint256 result = uint128(x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (exponent == 0x7FFF)
exponent = 0x7FFFF; // Infinity or NaN
else if (exponent == 0) {
if (result > 0) {
uint256 msb = mostSignificantBit(result);
result =
(result << (236 - msb)) &
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
exponent = 245649 + msb;
}
} else {
result <<= 124;
exponent += 245760;
}
result |= exponent << 236;
if (uint128(x) >= 0x80000000000000000000000000000000)
result |= 0x8000000000000000000000000000000000000000000000000000000000000000;
return bytes32(result);
}
}
/**
* Convert double precision number into quadruple precision number.
*
* @param x double precision number
* @return quadruple precision number
*/
function fromDouble(bytes8 x) internal pure returns (bytes16) {
unchecked {
uint256 exponent = (uint64(x) >> 52) & 0x7FF;
uint256 result = uint64(x) & 0xFFFFFFFFFFFFF;
if (exponent == 0x7FF)
exponent = 0x7FFF; // Infinity or NaN
else if (exponent == 0) {
if (result > 0) {
uint256 msb = mostSignificantBit(result);
result =
(result << (112 - msb)) &
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
exponent = 15309 + msb;
}
} else {
result <<= 60;
exponent += 15360;
}
result |= exponent << 112;
if (x & 0x8000000000000000 > 0)
result |= 0x80000000000000000000000000000000;
return bytes16(uint128(result));
}
}
/**
* Convert quadruple precision number into double precision number.
*
* @param x quadruple precision number
* @return double precision number
*/
function toDouble(bytes16 x) internal pure returns (bytes8) {
unchecked {
bool negative = uint128(x) >= 0x80000000000000000000000000000000;
uint256 exponent = (uint128(x) >> 112) & 0x7FFF;
uint256 significand = uint128(x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (exponent == 0x7FFF) {
if (significand > 0) return 0x7FF8000000000000;
// NaN
else
return
negative
? bytes8(0xFFF0000000000000) // -Infinity
: bytes8(0x7FF0000000000000); // Infinity
}
if (exponent > 17406)
return
negative
? bytes8(0xFFF0000000000000) // -Infinity
: bytes8(0x7FF0000000000000);
// Infinity
else if (exponent < 15309)
return
negative
? bytes8(0x8000000000000000) // -0
: bytes8(0x0000000000000000);
// 0
else if (exponent < 15361) {
significand =
(significand | 0x10000000000000000000000000000) >>
(15421 - exponent);
exponent = 0;
} else {
significand >>= 60;
exponent -= 15360;
}
uint64 result = uint64(significand | (exponent << 52));
if (negative) result |= 0x8000000000000000;
return bytes8(result);
}
}
/**
* Test whether given quadruple precision number is NaN.
*
* @param x quadruple precision number
* @return true if x is NaN, false otherwise
*/
function isNaN(bytes16 x) internal pure returns (bool) {
unchecked {
return
uint128(x) & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF >
0x7FFF0000000000000000000000000000;
}
}
/**
* Test whether given quadruple precision number is positive or negative
* infinity.
*
* @param x quadruple precision number
* @return true if x is positive or negative infinity, false otherwise
*/
function isInfinity(bytes16 x) internal pure returns (bool) {
unchecked {
return
uint128(x) & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF ==
0x7FFF0000000000000000000000000000;
}
}
/**
* Calculate sign of x, i.e. -1 if x is negative, 0 if x if zero, and 1 if x
* is positive. Note that sign (-0) is zero. Revert if x is NaN.
*
* @param x quadruple precision number
* @return sign of x
*/
function sign(bytes16 x) internal pure returns (int8) {
unchecked {
uint128 absoluteX = uint128(x) & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
require(absoluteX <= 0x7FFF0000000000000000000000000000); // Not NaN
if (absoluteX == 0) return 0;
else if (uint128(x) >= 0x80000000000000000000000000000000)
return -1;
else return 1;
}
}
/**
* Calculate sign (x - y). Revert if either argument is NaN, or both
* arguments are infinities of the same sign.
*
* @param x quadruple precision number
* @param y quadruple precision number
* @return sign (x - y)
*/
function cmp(bytes16 x, bytes16 y) internal pure returns (int8) {
unchecked {
uint128 absoluteX = uint128(x) & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
require(absoluteX <= 0x7FFF0000000000000000000000000000); // Not NaN
uint128 absoluteY = uint128(y) & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
require(absoluteY <= 0x7FFF0000000000000000000000000000); // Not NaN
// Not infinities of the same sign
require(x != y || absoluteX < 0x7FFF0000000000000000000000000000);
if (x == y) return 0;
else {
bool negativeX =
uint128(x) >= 0x80000000000000000000000000000000;
bool negativeY =
uint128(y) >= 0x80000000000000000000000000000000;
if (negativeX) {
if (negativeY) return absoluteX > absoluteY ? -1 : int8(1);
else return -1;
} else {
if (negativeY) return 1;
else return absoluteX > absoluteY ? int8(1) : -1;
}
}
}
}
/**
* Test whether x equals y. NaN, infinity, and -infinity are not equal to
* anything.
*
* @param x quadruple precision number
* @param y quadruple precision number
* @return true if x equals to y, false otherwise
*/
function eq(bytes16 x, bytes16 y) internal pure returns (bool) {
unchecked {
if (x == y) {
return
uint128(x) & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF <
0x7FFF0000000000000000000000000000;
} else return false;
}
}
/**
* Calculate x + y. Special values behave in the following way:
*
* NaN + x = NaN for any x.
* Infinity + x = Infinity for any finite x.
* -Infinity + x = -Infinity for any finite x.
* Infinity + Infinity = Infinity.
* -Infinity + -Infinity = -Infinity.
* Infinity + -Infinity = -Infinity + Infinity = NaN.
*
* @param x quadruple precision number
* @param y quadruple precision number
* @return quadruple precision number
*/
function add(bytes16 x, bytes16 y) internal pure returns (bytes16) {
unchecked {
uint256 xExponent = (uint128(x) >> 112) & 0x7FFF;
uint256 yExponent = (uint128(y) >> 112) & 0x7FFF;
if (xExponent == 0x7FFF) {
if (yExponent == 0x7FFF) {
if (x == y) return x;
else return NaN;
} else return x;
} else if (yExponent == 0x7FFF) return y;
else {
bool xSign = uint128(x) >= 0x80000000000000000000000000000000;
uint256 xSignifier =
uint128(x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (xExponent == 0) xExponent = 1;
else xSignifier |= 0x10000000000000000000000000000;
bool ySign = uint128(y) >= 0x80000000000000000000000000000000;
uint256 ySignifier =
uint128(y) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (yExponent == 0) yExponent = 1;
else ySignifier |= 0x10000000000000000000000000000;
if (xSignifier == 0)
return y == _NEGATIVE_ZERO ? _POSITIVE_ZERO : y;
else if (ySignifier == 0)
return x == _NEGATIVE_ZERO ? _POSITIVE_ZERO : x;
else {
int256 delta = int256(xExponent) - int256(yExponent);
if (xSign == ySign) {
if (delta > 112) return x;
else if (delta > 0) ySignifier >>= uint256(delta);
else if (delta < -112) return y;
else if (delta < 0) {
xSignifier >>= uint256(-delta);
xExponent = yExponent;
}
xSignifier += ySignifier;
if (xSignifier >= 0x20000000000000000000000000000) {
xSignifier >>= 1;
xExponent += 1;
}
if (xExponent == 0x7FFF)
return
xSign ? _NEGATIVE_INFINITY : _POSITIVE_INFINITY;
else {
if (xSignifier < 0x10000000000000000000000000000)
xExponent = 0;
else xSignifier &= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
return
bytes16(
uint128(
(
xSign
? 0x80000000000000000000000000000000
: 0
) |
(xExponent << 112) |
xSignifier
)
);
}
} else {
if (delta > 0) {
xSignifier <<= 1;
xExponent -= 1;
} else if (delta < 0) {
ySignifier <<= 1;
xExponent = yExponent - 1;
}
if (delta > 112) ySignifier = 1;
else if (delta > 1)
ySignifier =
((ySignifier - 1) >> uint256(delta - 1)) +
1;
else if (delta < -112) xSignifier = 1;
else if (delta < -1)
xSignifier =
((xSignifier - 1) >> uint256(-delta - 1)) +
1;
if (xSignifier >= ySignifier) xSignifier -= ySignifier;
else {
xSignifier = ySignifier - xSignifier;
xSign = ySign;
}
if (xSignifier == 0) return _POSITIVE_ZERO;
uint256 msb = mostSignificantBit(xSignifier);
if (msb == 113) {
xSignifier =
(xSignifier >> 1) &
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
xExponent += 1;
} else if (msb < 112) {
uint256 shift = 112 - msb;
if (xExponent > shift) {
xSignifier =
(xSignifier << shift) &
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
xExponent -= shift;
} else {
xSignifier <<= xExponent - 1;
xExponent = 0;
}
} else xSignifier &= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (xExponent == 0x7FFF)
return
xSign ? _NEGATIVE_INFINITY : _POSITIVE_INFINITY;
else
return
bytes16(
uint128(
(
xSign
? 0x80000000000000000000000000000000
: 0
) |
(xExponent << 112) |
xSignifier
)
);
}
}
}
}
}
/**
* Calculate x - y. Special values behave in the following way:
*
* NaN - x = NaN for any x.
* Infinity - x = Infinity for any finite x.
* -Infinity - x = -Infinity for any finite x.
* Infinity - -Infinity = Infinity.
* -Infinity - Infinity = -Infinity.
* Infinity - Infinity = -Infinity - -Infinity = NaN.
*
* @param x quadruple precision number
* @param y quadruple precision number
* @return quadruple precision number
*/
function sub(bytes16 x, bytes16 y) internal pure returns (bytes16) {
unchecked {return add(x, y ^ 0x80000000000000000000000000000000);}
}
/**
* Calculate x * y. Special values behave in the following way:
*
* NaN * x = NaN for any x.
* Infinity * x = Infinity for any finite positive x.
* Infinity * x = -Infinity for any finite negative x.
* -Infinity * x = -Infinity for any finite positive x.
* -Infinity * x = Infinity for any finite negative x.
* Infinity * 0 = NaN.
* -Infinity * 0 = NaN.
* Infinity * Infinity = Infinity.
* Infinity * -Infinity = -Infinity.
* -Infinity * Infinity = -Infinity.
* -Infinity * -Infinity = Infinity.
*
* @param x quadruple precision number
* @param y quadruple precision number
* @return quadruple precision number
*/
function mul(bytes16 x, bytes16 y) internal pure returns (bytes16) {
unchecked {
uint256 xExponent = (uint128(x) >> 112) & 0x7FFF;
uint256 yExponent = (uint128(y) >> 112) & 0x7FFF;
if (xExponent == 0x7FFF) {
if (yExponent == 0x7FFF) {
if (x == y)
return x ^ (y & 0x80000000000000000000000000000000);
else if (x ^ y == 0x80000000000000000000000000000000)
return x | y;
else return NaN;
} else {
if (y & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF == 0) return NaN;
else return x ^ (y & 0x80000000000000000000000000000000);
}
} else if (yExponent == 0x7FFF) {
if (x & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF == 0) return NaN;
else return y ^ (x & 0x80000000000000000000000000000000);
} else {
uint256 xSignifier =
uint128(x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (xExponent == 0) xExponent = 1;
else xSignifier |= 0x10000000000000000000000000000;
uint256 ySignifier =
uint128(y) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (yExponent == 0) yExponent = 1;
else ySignifier |= 0x10000000000000000000000000000;
xSignifier *= ySignifier;
if (xSignifier == 0)
return
(x ^ y) & 0x80000000000000000000000000000000 > 0
? _NEGATIVE_ZERO
: _POSITIVE_ZERO;
xExponent += yExponent;
uint256 msb =
xSignifier >=
0x200000000000000000000000000000000000000000000000000000000
? 225
: xSignifier >=
0x100000000000000000000000000000000000000000000000000000000
? 224
: mostSignificantBit(xSignifier);
if (xExponent + msb < 16496) {
// Underflow
xExponent = 0;
xSignifier = 0;
} else if (xExponent + msb < 16608) {
// Subnormal
if (xExponent < 16496) xSignifier >>= 16496 - xExponent;
else if (xExponent > 16496)
xSignifier <<= xExponent - 16496;
xExponent = 0;
} else if (xExponent + msb > 49373) {
xExponent = 0x7FFF;
xSignifier = 0;
} else {
if (msb > 112) xSignifier >>= msb - 112;
else if (msb < 112) xSignifier <<= 112 - msb;
xSignifier &= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
xExponent = xExponent + msb - 16607;
}
return
bytes16(
uint128(
uint128(
(x ^ y) & 0x80000000000000000000000000000000
) |
(xExponent << 112) |
xSignifier
)
);
}
}
}
/**
* Calculate x / y. Special values behave in the following way:
*
* NaN / x = NaN for any x.
* x / NaN = NaN for any x.
* Infinity / x = Infinity for any finite non-negative x.
* Infinity / x = -Infinity for any finite negative x including -0.
* -Infinity / x = -Infinity for any finite non-negative x.
* -Infinity / x = Infinity for any finite negative x including -0.
* x / Infinity = 0 for any finite non-negative x.
* x / -Infinity = -0 for any finite non-negative x.
* x / Infinity = -0 for any finite non-negative x including -0.
* x / -Infinity = 0 for any finite non-negative x including -0.
*
* Infinity / Infinity = NaN.
* Infinity / -Infinity = -NaN.
* -Infinity / Infinity = -NaN.
* -Infinity / -Infinity = NaN.
*
* Division by zero behaves in the following way:
*
* x / 0 = Infinity for any finite positive x.
* x / -0 = -Infinity for any finite positive x.
* x / 0 = -Infinity for any finite negative x.
* x / -0 = Infinity for any finite negative x.
* 0 / 0 = NaN.
* 0 / -0 = NaN.
* -0 / 0 = NaN.
* -0 / -0 = NaN.
*
* @param x quadruple precision number
* @param y quadruple precision number
* @return quadruple precision number
*/
function div(bytes16 x, bytes16 y) internal pure returns (bytes16) {
unchecked {
uint256 xExponent = (uint128(x) >> 112) & 0x7FFF;
uint256 yExponent = (uint128(y) >> 112) & 0x7FFF;
if (xExponent == 0x7FFF) {
if (yExponent == 0x7FFF) return NaN;
else return x ^ (y & 0x80000000000000000000000000000000);
} else if (yExponent == 0x7FFF) {
if (y & 0x0000FFFFFFFFFFFFFFFFFFFFFFFFFFFF != 0) return NaN;
else
return
_POSITIVE_ZERO |
((x ^ y) & 0x80000000000000000000000000000000);
} else if (y & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF == 0) {
if (x & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF == 0) return NaN;
else
return
_POSITIVE_INFINITY |
((x ^ y) & 0x80000000000000000000000000000000);
} else {
uint256 ySignifier =
uint128(y) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (yExponent == 0) yExponent = 1;
else ySignifier |= 0x10000000000000000000000000000;
uint256 xSignifier =
uint128(x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (xExponent == 0) {
if (xSignifier != 0) {
uint256 shift = 226 - mostSignificantBit(xSignifier);
xSignifier <<= shift;
xExponent = 1;
yExponent += shift - 114;
}
} else {
xSignifier =
(xSignifier | 0x10000000000000000000000000000) <<
114;
}
xSignifier = xSignifier / ySignifier;
if (xSignifier == 0)
return
(x ^ y) & 0x80000000000000000000000000000000 > 0
? _NEGATIVE_ZERO
: _POSITIVE_ZERO;
assert(xSignifier >= 0x1000000000000000000000000000);
uint256 msb =
xSignifier >= 0x80000000000000000000000000000
? mostSignificantBit(xSignifier)
: xSignifier >= 0x40000000000000000000000000000
? 114
: xSignifier >= 0x20000000000000000000000000000
? 113
: 112;
if (xExponent + msb > yExponent + 16497) {
// Overflow
xExponent = 0x7FFF;
xSignifier = 0;
} else if (xExponent + msb + 16380 < yExponent) {
// Underflow
xExponent = 0;
xSignifier = 0;
} else if (xExponent + msb + 16268 < yExponent) {
// Subnormal
if (xExponent + 16380 > yExponent)
xSignifier <<= xExponent + 16380 - yExponent;
else if (xExponent + 16380 < yExponent)
xSignifier >>= yExponent - xExponent - 16380;
xExponent = 0;
} else {
// Normal
if (msb > 112) xSignifier >>= msb - 112;
xSignifier &= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
xExponent = xExponent + msb + 16269 - yExponent;
}
return
bytes16(
uint128(
uint128(
(x ^ y) & 0x80000000000000000000000000000000
) |
(xExponent << 112) |
xSignifier
)
);
}
}
}
/**
* Calculate -x.
*
* @param x quadruple precision number
* @return quadruple precision number
*/
function neg(bytes16 x) internal pure returns (bytes16) {
unchecked {return x ^ 0x80000000000000000000000000000000;}
}
/**
* Calculate |x|.
*
* @param x quadruple precision number
* @return quadruple precision number
*/
function abs(bytes16 x) internal pure returns (bytes16) {
unchecked {return x & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;}
}
/**
* Calculate square root of x. Return NaN on negative x excluding -0.
*
* @param x quadruple precision number
* @return quadruple precision number
*/
function sqrt(bytes16 x) internal pure returns (bytes16) {
unchecked {
if (uint128(x) > 0x80000000000000000000000000000000) return NaN;
else {
uint256 xExponent = (uint128(x) >> 112) & 0x7FFF;
if (xExponent == 0x7FFF) return x;
else {
uint256 xSignifier =
uint128(x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (xExponent == 0) xExponent = 1;
else xSignifier |= 0x10000000000000000000000000000;
if (xSignifier == 0) return _POSITIVE_ZERO;
bool oddExponent = xExponent & 0x1 == 0;
xExponent = (xExponent + 16383) >> 1;
if (oddExponent) {
if (xSignifier >= 0x10000000000000000000000000000)
xSignifier <<= 113;
else {
uint256 msb = mostSignificantBit(xSignifier);
uint256 shift = (226 - msb) & 0xFE;
xSignifier <<= shift;
xExponent -= (shift - 112) >> 1;
}
} else {
if (xSignifier >= 0x10000000000000000000000000000)
xSignifier <<= 112;
else {
uint256 msb = mostSignificantBit(xSignifier);
uint256 shift = (225 - msb) & 0xFE;
xSignifier <<= shift;
xExponent -= (shift - 112) >> 1;
}
}
uint256 r = 0x10000000000000000000000000000;
r = (r + xSignifier / r) >> 1;
r = (r + xSignifier / r) >> 1;
r = (r + xSignifier / r) >> 1;
r = (r + xSignifier / r) >> 1;
r = (r + xSignifier / r) >> 1;
r = (r + xSignifier / r) >> 1;
r = (r + xSignifier / r) >> 1; // Seven iterations should be enough
uint256 r1 = xSignifier / r;
if (r1 < r) r = r1;
return
bytes16(
uint128(
(xExponent << 112) |
(r & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
)
);
}
}
}
}
/**
* Calculate binary logarithm of x. Return NaN on negative x excluding -0.
*
* @param x quadruple precision number
* @return quadruple precision number
*/
function log_2(bytes16 x) internal pure returns (bytes16) {
unchecked {
if (uint128(x) > 0x80000000000000000000000000000000) return NaN;
else if (x == 0x3FFF0000000000000000000000000000)
return _POSITIVE_ZERO;
else {
uint256 xExponent = (uint128(x) >> 112) & 0x7FFF;
if (xExponent == 0x7FFF) return x;
else {
uint256 xSignifier =
uint128(x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (xExponent == 0) xExponent = 1;
else xSignifier |= 0x10000000000000000000000000000;
if (xSignifier == 0) return _NEGATIVE_INFINITY;
bool resultNegative;
uint256 resultExponent = 16495;
uint256 resultSignifier;
if (xExponent >= 0x3FFF) {
resultNegative = false;
resultSignifier = xExponent - 0x3FFF;
xSignifier <<= 15;
} else {
resultNegative = true;
if (xSignifier >= 0x10000000000000000000000000000) {
resultSignifier = 0x3FFE - xExponent;
xSignifier <<= 15;
} else {
uint256 msb = mostSignificantBit(xSignifier);
resultSignifier = 16493 - msb;
xSignifier <<= 127 - msb;
}
}
if (xSignifier == 0x80000000000000000000000000000000) {
if (resultNegative) resultSignifier += 1;
uint256 shift =
112 - mostSignificantBit(resultSignifier);
resultSignifier <<= shift;
resultExponent -= shift;
} else {
uint256 bb = resultNegative ? 1 : 0;
while (
resultSignifier < 0x10000000000000000000000000000
) {
resultSignifier <<= 1;
resultExponent -= 1;
xSignifier *= xSignifier;
uint256 b = xSignifier >> 255;
resultSignifier += b ^ bb;
xSignifier >>= 127 + b;
}
}
return
bytes16(
uint128(
(
resultNegative
? 0x80000000000000000000000000000000
: 0
) |
(resultExponent << 112) |
(resultSignifier &
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
)
);
}
}
}
}
/**
* Calculate natural logarithm of x. Return NaN on negative x excluding -0.
*
* @param x quadruple precision number
* @return quadruple precision number
*/
function ln(bytes16 x) internal pure returns (bytes16) {
unchecked {return mul(log_2(x), 0x3FFE62E42FEFA39EF35793C7673007E5);}
}
/**
* Calculate 2^x.
*
* @param x quadruple precision number
* @return quadruple precision number
*/
function pow_2(bytes16 x) internal pure returns (bytes16) {
unchecked {
bool xNegative = uint128(x) > 0x80000000000000000000000000000000;
uint256 xExponent = (uint128(x) >> 112) & 0x7FFF;
uint256 xSignifier = uint128(x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (xExponent == 0x7FFF && xSignifier != 0) return NaN;
else if (xExponent > 16397)
return xNegative ? _POSITIVE_ZERO : _POSITIVE_INFINITY;
else if (xExponent < 16255)
return 0x3FFF0000000000000000000000000000;
else {
if (xExponent == 0) xExponent = 1;
else xSignifier |= 0x10000000000000000000000000000;
if (xExponent > 16367) xSignifier <<= xExponent - 16367;
else if (xExponent < 16367) xSignifier >>= 16367 - xExponent;
if (
xNegative &&
xSignifier > 0x406E00000000000000000000000000000000
) return _POSITIVE_ZERO;
if (
!xNegative &&
xSignifier > 0x3FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
) return _POSITIVE_INFINITY;
uint256 resultExponent = xSignifier >> 128;
xSignifier &= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (xNegative && xSignifier != 0) {
xSignifier = ~xSignifier;
resultExponent += 1;
}
uint256 resultSignifier = 0x80000000000000000000000000000000;
if (xSignifier & 0x80000000000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x16A09E667F3BCC908B2FB1366EA957D3E) >>
128;
if (xSignifier & 0x40000000000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1306FE0A31B7152DE8D5A46305C85EDEC) >>
128;
if (xSignifier & 0x20000000000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1172B83C7D517ADCDF7C8C50EB14A791F) >>
128;
if (xSignifier & 0x10000000000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10B5586CF9890F6298B92B71842A98363) >>
128;
if (xSignifier & 0x8000000000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1059B0D31585743AE7C548EB68CA417FD) >>
128;
if (xSignifier & 0x4000000000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x102C9A3E778060EE6F7CACA4F7A29BDE8) >>
128;
if (xSignifier & 0x2000000000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10163DA9FB33356D84A66AE336DCDFA3F) >>
128;
if (xSignifier & 0x1000000000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100B1AFA5ABCBED6129AB13EC11DC9543) >>
128;
if (xSignifier & 0x800000000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10058C86DA1C09EA1FF19D294CF2F679B) >>
128;
if (xSignifier & 0x400000000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1002C605E2E8CEC506D21BFC89A23A00F) >>
128;
if (xSignifier & 0x200000000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100162F3904051FA128BCA9C55C31E5DF) >>
128;
if (xSignifier & 0x100000000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000B175EFFDC76BA38E31671CA939725) >>
128;
if (xSignifier & 0x80000000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100058BA01FB9F96D6CACD4B180917C3D) >>
128;
if (xSignifier & 0x40000000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10002C5CC37DA9491D0985C348C68E7B3) >>
128;
if (xSignifier & 0x20000000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000162E525EE054754457D5995292026) >>
128;
if (xSignifier & 0x10000000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000B17255775C040618BF4A4ADE83FC) >>
128;
if (xSignifier & 0x8000000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000058B91B5BC9AE2EED81E9B7D4CFAB) >>
128;
if (xSignifier & 0x4000000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100002C5C89D5EC6CA4D7C8ACC017B7C9) >>
128;
if (xSignifier & 0x2000000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000162E43F4F831060E02D839A9D16D) >>
128;
if (xSignifier & 0x1000000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000B1721BCFC99D9F890EA06911763) >>
128;
if (xSignifier & 0x800000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000058B90CF1E6D97F9CA14DBCC1628) >>
128;
if (xSignifier & 0x400000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000002C5C863B73F016468F6BAC5CA2B) >>
128;
if (xSignifier & 0x200000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000162E430E5A18F6119E3C02282A5) >>
128;
if (xSignifier & 0x100000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000B1721835514B86E6D96EFD1BFE) >>
128;
if (xSignifier & 0x80000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000058B90C0B48C6BE5DF846C5B2EF) >>
128;
if (xSignifier & 0x40000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000002C5C8601CC6B9E94213C72737A) >>
128;
if (xSignifier & 0x20000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000162E42FFF037DF38AA2B219F06) >>
128;
if (xSignifier & 0x10000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000B17217FBA9C739AA5819F44F9) >>
128;
if (xSignifier & 0x8000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000058B90BFCDEE5ACD3C1CEDC823) >>
128;
if (xSignifier & 0x4000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000002C5C85FE31F35A6A30DA1BE50) >>
128;
if (xSignifier & 0x2000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000162E42FF0999CE3541B9FFFCF) >>
128;
if (xSignifier & 0x1000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000B17217F80F4EF5AADDA45554) >>
128;
if (xSignifier & 0x800000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000058B90BFBF8479BD5A81B51AD) >>
128;
if (xSignifier & 0x400000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000002C5C85FDF84BD62AE30A74CC) >>
128;
if (xSignifier & 0x200000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000162E42FEFB2FED257559BDAA) >>
128;
if (xSignifier & 0x100000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000B17217F7D5A7716BBA4A9AE) >>
128;
if (xSignifier & 0x80000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000058B90BFBE9DDBAC5E109CCE) >>
128;
if (xSignifier & 0x40000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000002C5C85FDF4B15DE6F17EB0D) >>
128;
if (xSignifier & 0x20000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000162E42FEFA494F1478FDE05) >>
128;
if (xSignifier & 0x10000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000B17217F7D20CF927C8E94C) >>
128;
if (xSignifier & 0x8000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000058B90BFBE8F71CB4E4B33D) >>
128;
if (xSignifier & 0x4000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000002C5C85FDF477B662B26945) >>
128;
if (xSignifier & 0x2000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000162E42FEFA3AE53369388C) >>
128;
if (xSignifier & 0x1000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000B17217F7D1D351A389D40) >>
128;
if (xSignifier & 0x800000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000058B90BFBE8E8B2D3D4EDE) >>
128;
if (xSignifier & 0x400000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000002C5C85FDF4741BEA6E77E) >>
128;
if (xSignifier & 0x200000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000162E42FEFA39FE95583C2) >>
128;
if (xSignifier & 0x100000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000B17217F7D1CFB72B45E1) >>
128;
if (xSignifier & 0x80000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000058B90BFBE8E7CC35C3F0) >>
128;
if (xSignifier & 0x40000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000002C5C85FDF473E242EA38) >>
128;
if (xSignifier & 0x20000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000162E42FEFA39F02B772C) >>
128;
if (xSignifier & 0x10000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000B17217F7D1CF7D83C1A) >>
128;
if (xSignifier & 0x8000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000058B90BFBE8E7BDCBE2E) >>
128;
if (xSignifier & 0x4000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000002C5C85FDF473DEA871F) >>
128;
if (xSignifier & 0x2000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000162E42FEFA39EF44D91) >>
128;
if (xSignifier & 0x1000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000B17217F7D1CF79E949) >>
128;
if (xSignifier & 0x800000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000058B90BFBE8E7BCE544) >>
128;
if (xSignifier & 0x400000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000002C5C85FDF473DE6ECA) >>
128;
if (xSignifier & 0x200000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000162E42FEFA39EF366F) >>
128;
if (xSignifier & 0x100000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000000B17217F7D1CF79AFA) >>
128;
if (xSignifier & 0x80000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000058B90BFBE8E7BCD6D) >>
128;
if (xSignifier & 0x40000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000002C5C85FDF473DE6B2) >>
128;
if (xSignifier & 0x20000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000000162E42FEFA39EF358) >>
128;
if (xSignifier & 0x10000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000000B17217F7D1CF79AB) >>
128;
if (xSignifier & 0x8000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000000058B90BFBE8E7BCD5) >>
128;
if (xSignifier & 0x4000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000002C5C85FDF473DE6A) >>
128;
if (xSignifier & 0x2000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000000162E42FEFA39EF34) >>
128;
if (xSignifier & 0x1000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000000B17217F7D1CF799) >>
128;
if (xSignifier & 0x800000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000000058B90BFBE8E7BCC) >>
128;
if (xSignifier & 0x400000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000000002C5C85FDF473DE5) >>
128;
if (xSignifier & 0x200000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000000162E42FEFA39EF2) >>
128;
if (xSignifier & 0x100000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000000000B17217F7D1CF78) >>
128;
if (xSignifier & 0x80000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000000058B90BFBE8E7BB) >>
128;
if (xSignifier & 0x40000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000000002C5C85FDF473DD) >>
128;
if (xSignifier & 0x20000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000000000162E42FEFA39EE) >>
128;
if (xSignifier & 0x10000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000000000B17217F7D1CF6) >>
128;
if (xSignifier & 0x8000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000000000058B90BFBE8E7A) >>
128;
if (xSignifier & 0x4000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000000002C5C85FDF473C) >>
128;
if (xSignifier & 0x2000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000000000162E42FEFA39D) >>
128;
if (xSignifier & 0x1000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000000000B17217F7D1CE) >>
128;
if (xSignifier & 0x800000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000000000058B90BFBE8E6) >>
128;
if (xSignifier & 0x400000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000000000002C5C85FDF472) >>
128;
if (xSignifier & 0x200000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000000000162E42FEFA38) >>
128;
if (xSignifier & 0x100000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000000000000B17217F7D1B) >>
128;
if (xSignifier & 0x80000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000000000058B90BFBE8D) >>
128;
if (xSignifier & 0x40000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000000000002C5C85FDF46) >>
128;
if (xSignifier & 0x20000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000000000000162E42FEFA2) >>
128;
if (xSignifier & 0x10000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000000000000B17217F7D0) >>
128;
if (xSignifier & 0x8000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000000000000058B90BFBE7) >>
128;
if (xSignifier & 0x4000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000000000002C5C85FDF3) >>
128;
if (xSignifier & 0x2000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000000000000162E42FEF9) >>
128;
if (xSignifier & 0x1000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000000000000B17217F7C) >>
128;
if (xSignifier & 0x800000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000000000000058B90BFBD) >>
128;
if (xSignifier & 0x400000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000000000000002C5C85FDE) >>
128;
if (xSignifier & 0x200000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000000000000162E42FEE) >>
128;
if (xSignifier & 0x100000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000000000000000B17217F6) >>
128;
if (xSignifier & 0x80000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000000000000058B90BFA) >>
128;
if (xSignifier & 0x40000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000000000000002C5C85FC) >>
128;
if (xSignifier & 0x20000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000000000000000162E42FD) >>
128;
if (xSignifier & 0x10000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000000000000000B17217E) >>
128;
if (xSignifier & 0x8000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000000000000000058B90BE) >>
128;
if (xSignifier & 0x4000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000000000000002C5C85E) >>
128;
if (xSignifier & 0x2000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000000000000000162E42E) >>
128;
if (xSignifier & 0x1000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000000000000000B17216) >>
128;
if (xSignifier & 0x800000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000000000000000058B90A) >>
128;
if (xSignifier & 0x400000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000000000000000002C5C84) >>
128;
if (xSignifier & 0x200000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000000000000000162E41) >>
128;
if (xSignifier & 0x100000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000000000000000000B1720) >>
128;
if (xSignifier & 0x80000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000000000000000058B8F) >>
128;
if (xSignifier & 0x40000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000000000000000002C5C7) >>
128;
if (xSignifier & 0x20000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000000000000000000162E3) >>
128;
if (xSignifier & 0x10000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000000000000000000B171) >>
128;
if (xSignifier & 0x8000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000000000000000000058B8) >>
128;
if (xSignifier & 0x4000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000000000000000002C5B) >>
128;
if (xSignifier & 0x2000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000000000000000000162D) >>
128;
if (xSignifier & 0x1000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000000000000000000B16) >>
128;
if (xSignifier & 0x800 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000000000000000000058A) >>
128;
if (xSignifier & 0x400 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000000000000000000002C4) >>
128;
if (xSignifier & 0x200 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000000000000000000161) >>
128;
if (xSignifier & 0x100 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000000000000000000000B0) >>
128;
if (xSignifier & 0x80 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000000000000000000057) >>
128;
if (xSignifier & 0x40 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000000000000000000002B) >>
128;
if (xSignifier & 0x20 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000000000000000000015) >>
128;
if (xSignifier & 0x10 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000000000000000000000A) >>
128;
if (xSignifier & 0x8 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000000000000000000004) >>
128;
if (xSignifier & 0x4 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000000000000000000001) >>
128;
if (!xNegative) {
resultSignifier =
(resultSignifier >> 15) &
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
resultExponent += 0x3FFF;
} else if (resultExponent <= 0x3FFE) {
resultSignifier =
(resultSignifier >> 15) &
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
resultExponent = 0x3FFF - resultExponent;
} else {
resultSignifier =
resultSignifier >>
(resultExponent - 16367);
resultExponent = 0;
}
return
bytes16(uint128((resultExponent << 112) | resultSignifier));
}
}
}
/**
* Calculate e^x.
*
* @param x quadruple precision number
* @return quadruple precision number
*/
function exp(bytes16 x) internal pure returns (bytes16) {
unchecked {return pow_2(mul(x, 0x3FFF71547652B82FE1777D0FFDA0D23A));}
}
/**
* Get index of the most significant non-zero bit in binary representation of
* x. Reverts if x is zero.
*
* @return index of the most significant non-zero bit in binary representation
* of x
*/
function mostSignificantBit(uint256 x) private pure returns (uint256) {
unchecked {
require(x > 0);
uint256 result = 0;
if (x >= 0x100000000000000000000000000000000) {
x >>= 128;
result += 128;
}
if (x >= 0x10000000000000000) {
x >>= 64;
result += 64;
}
if (x >= 0x100000000) {
x >>= 32;
result += 32;
}
if (x >= 0x10000) {
x >>= 16;
result += 16;
}
if (x >= 0x100) {
x >>= 8;
result += 8;
}
if (x >= 0x10) {
x >>= 4;
result += 4;
}
if (x >= 0x4) {
x >>= 2;
result += 2;
}
if (x >= 0x2) result += 1; // No need to shift x anymore
return result;
}
}
}
// 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;
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;
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: Apache-2.0
pragma solidity ^0.8.3;
import "./IERC20Ubiquity.sol";
/// @title UAD stablecoin interface
/// @author Ubiquity Algorithmic Dollar
interface IUbiquityAlgorithmicDollar is IERC20Ubiquity {
event IncentiveContractUpdate(
address indexed _incentivized,
address indexed _incentiveContract
);
function setIncentiveContract(address account, address incentive) external;
function incentiveContract(address account) external view returns (address);
}
// SPDX-License-Identifier: MIT
// !! THIS FILE WAS AUTOGENERATED BY abi-to-sol. SEE BELOW FOR SOURCE. !!
pragma solidity ^0.8.3;
interface ICurveFactory {
event BasePoolAdded(address base_pool, address implementat);
event MetaPoolDeployed(
address coin,
address base_pool,
uint256 A,
uint256 fee,
address deployer
);
function find_pool_for_coins(address _from, address _to)
external
view
returns (address);
function find_pool_for_coins(
address _from,
address _to,
uint256 i
) external view returns (address);
function get_n_coins(address _pool)
external
view
returns (uint256, uint256);
function get_coins(address _pool) external view returns (address[2] memory);
function get_underlying_coins(address _pool)
external
view
returns (address[8] memory);
function get_decimals(address _pool)
external
view
returns (uint256[2] memory);
function get_underlying_decimals(address _pool)
external
view
returns (uint256[8] memory);
function get_rates(address _pool) external view returns (uint256[2] memory);
function get_balances(address _pool)
external
view
returns (uint256[2] memory);
function get_underlying_balances(address _pool)
external
view
returns (uint256[8] memory);
function get_A(address _pool) external view returns (uint256);
function get_fees(address _pool) external view returns (uint256, uint256);
function get_admin_balances(address _pool)
external
view
returns (uint256[2] memory);
function get_coin_indices(
address _pool,
address _from,
address _to
)
external
view
returns (
int128,
int128,
bool
);
function add_base_pool(
address _base_pool,
address _metapool_implementation,
address _fee_receiver
) external;
function deploy_metapool(
address _base_pool,
string memory _name,
string memory _symbol,
address _coin,
uint256 _A,
uint256 _fee
) external returns (address);
function commit_transfer_ownership(address addr) external;
function accept_transfer_ownership() external;
function set_fee_receiver(address _base_pool, address _fee_receiver)
external;
function convert_fees() external returns (bool);
function admin() external view returns (address);
function future_admin() external view returns (address);
function pool_list(uint256 arg0) external view returns (address);
function pool_count() external view returns (uint256);
function base_pool_list(uint256 arg0) external view returns (address);
function base_pool_count() external view returns (uint256);
function fee_receiver(address arg0) external view returns (address);
}
// SPDX-License-Identifier: UNLICENSED
// !! THIS FILE WAS AUTOGENERATED BY abi-to-sol. SEE BELOW FOR SOURCE. !!
pragma solidity ^0.8.3;
interface IMetaPool {
event Transfer(
address indexed sender,
address indexed receiver,
uint256 value
);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
event TokenExchange(
address indexed buyer,
int128 sold_id,
uint256 tokens_sold,
int128 bought_id,
uint256 tokens_bought
);
event TokenExchangeUnderlying(
address indexed buyer,
int128 sold_id,
uint256 tokens_sold,
int128 bought_id,
uint256 tokens_bought
);
event AddLiquidity(
address indexed provider,
uint256[2] token_amounts,
uint256[2] fees,
uint256 invariant,
uint256 token_supply
);
event RemoveLiquidity(
address indexed provider,
uint256[2] token_amounts,
uint256[2] fees,
uint256 token_supply
);
event RemoveLiquidityOne(
address indexed provider,
uint256 token_amount,
uint256 coin_amount,
uint256 token_supply
);
event RemoveLiquidityImbalance(
address indexed provider,
uint256[2] token_amounts,
uint256[2] fees,
uint256 invariant,
uint256 token_supply
);
event CommitNewAdmin(uint256 indexed deadline, address indexed admin);
event NewAdmin(address indexed admin);
event CommitNewFee(
uint256 indexed deadline,
uint256 fee,
uint256 admin_fee
);
event NewFee(uint256 fee, uint256 admin_fee);
event RampA(
uint256 old_A,
uint256 new_A,
uint256 initial_time,
uint256 future_time
);
event StopRampA(uint256 A, uint256 t);
function initialize(
string memory _name,
string memory _symbol,
address _coin,
uint256 _decimals,
uint256 _A,
uint256 _fee,
address _admin
) external;
function decimals() external view returns (uint256);
function transfer(address _to, uint256 _value) external returns (bool);
function transferFrom(
address _from,
address _to,
uint256 _value
) external returns (bool);
function approve(address _spender, uint256 _value) external returns (bool);
function get_previous_balances() external view returns (uint256[2] memory);
function get_balances() external view returns (uint256[2] memory);
function get_twap_balances(
uint256[2] memory _first_balances,
uint256[2] memory _last_balances,
uint256 _time_elapsed
) external view returns (uint256[2] memory);
function get_price_cumulative_last()
external
view
returns (uint256[2] memory);
function admin_fee() external view returns (uint256);
function A() external view returns (uint256);
function A_precise() external view returns (uint256);
function get_virtual_price() external view returns (uint256);
function calc_token_amount(uint256[2] memory _amounts, bool _is_deposit)
external
view
returns (uint256);
function calc_token_amount(
uint256[2] memory _amounts,
bool _is_deposit,
bool _previous
) external view returns (uint256);
function add_liquidity(uint256[2] memory _amounts, uint256 _min_mint_amount)
external
returns (uint256);
function add_liquidity(
uint256[2] memory _amounts,
uint256 _min_mint_amount,
address _receiver
) external returns (uint256);
function get_dy(
int128 i,
int128 j,
uint256 dx
) external view returns (uint256);
function get_dy(
int128 i,
int128 j,
uint256 dx,
uint256[2] memory _balances
) external view returns (uint256);
function get_dy_underlying(
int128 i,
int128 j,
uint256 dx
) external view returns (uint256);
function get_dy_underlying(
int128 i,
int128 j,
uint256 dx,
uint256[2] memory _balances
) external view returns (uint256);
function exchange(
int128 i,
int128 j,
uint256 dx,
uint256 min_dy
) external returns (uint256);
function exchange(
int128 i,
int128 j,
uint256 dx,
uint256 min_dy,
address _receiver
) external returns (uint256);
function exchange_underlying(
int128 i,
int128 j,
uint256 dx,
uint256 min_dy
) external returns (uint256);
function exchange_underlying(
int128 i,
int128 j,
uint256 dx,
uint256 min_dy,
address _receiver
) external returns (uint256);
function remove_liquidity(
uint256 _burn_amount,
uint256[2] memory _min_amounts
) external returns (uint256[2] memory);
function remove_liquidity(
uint256 _burn_amount,
uint256[2] memory _min_amounts,
address _receiver
) external returns (uint256[2] memory);
function remove_liquidity_imbalance(
uint256[2] memory _amounts,
uint256 _max_burn_amount
) external returns (uint256);
function remove_liquidity_imbalance(
uint256[2] memory _amounts,
uint256 _max_burn_amount,
address _receiver
) external returns (uint256);
function calc_withdraw_one_coin(uint256 _burn_amount, int128 i)
external
view
returns (uint256);
function calc_withdraw_one_coin(
uint256 _burn_amount,
int128 i,
bool _previous
) external view returns (uint256);
function remove_liquidity_one_coin(
uint256 _burn_amount,
int128 i,
uint256 _min_received
) external returns (uint256);
function remove_liquidity_one_coin(
uint256 _burn_amount,
int128 i,
uint256 _min_received,
address _receiver
) external returns (uint256);
function ramp_A(uint256 _future_A, uint256 _future_time) external;
function stop_ramp_A() external;
function admin_balances(uint256 i) external view returns (uint256);
function withdraw_admin_fees() external;
function admin() external view returns (address);
function coins(uint256 arg0) external view returns (address);
function balances(uint256 arg0) external view returns (uint256);
function fee() external view returns (uint256);
function block_timestamp_last() external view returns (uint256);
function initial_A() external view returns (uint256);
function future_A() external view returns (uint256);
function initial_A_time() external view returns (uint256);
function future_A_time() external view returns (uint256);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function balanceOf(address arg0) external view returns (uint256);
function allowance(address arg0, address arg1)
external
view
returns (uint256);
function totalSupply() external view returns (uint256);
}
// 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 "../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;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.3;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/// @title ERC20 Ubiquiti preset interface
/// @author Ubiquity Algorithmic Dollar
interface IERC20Ubiquity is IERC20 {
// ----------- Events -----------
event Minting(
address indexed _to,
address indexed _minter,
uint256 _amount
);
event Burning(address indexed _burned, uint256 _amount);
// ----------- State changing api -----------
function burn(uint256 amount) external;
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
// ----------- Burner only state changing api -----------
function burnFrom(address account, uint256 amount) external;
// ----------- Minter only state changing api -----------
function mint(address account, uint256 amount) external;
}
// 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);
}
| Convert quadruple precision number into signed 128.128 bit fixed point number. Revert on overflow. x quadruple precision number return signed 128.128 bit fixed point number/ Negative | function to128x128(bytes16 x) internal pure returns (int256) {
unchecked {
uint256 exponent = (uint128(x) >> 112) & 0x7FFF;
uint256 result =
(uint256(uint128(x)) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF) |
0x10000000000000000000000000000;
if (exponent < 16367) result >>= 16367 - exponent;
else if (exponent > 16367) result <<= exponent - 16367;
if (uint128(x) >= 0x80000000000000000000000000000000) {
require(
result <=
0x8000000000000000000000000000000000000000000000000000000000000000
);
require(
result <=
0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
);
return int256(result);
}
}
}
| 96,078 |
./partial_match/1/0x2c8652acBAba3d398952BD291b0baF29ba6f0ae8/sources/TubeChief.sol | get token per share with current block number | function getAccTokenInfo(uint poolId) public view returns (uint) {
if (pools[poolId].accLpStaked <= 0) {
return 0;
}
uint reward_block = pools[poolId].rewardPerBlock;
uint multiplier = pools[poolId].multiplier;
uint total_staked = pools[poolId].accLpStaked;
uint pending = block.number.sub(pools[poolId].accLastBlockNo);
uint result = reward_block.mul(multiplier, DECIMAL).mul(pending, DECIMAL).mul(FARMER, DECIMAL);
return result.div(total_staked, DECIMAL);
}
| 2,688,746 |
// Verified using https://dapp.tools
// hevm: flattened sources of src/token.sol
// SPDX-License-Identifier: MIT AND GPL-3.0-only
pragma solidity >=0.8.0 <0.9.0 >=0.8.2 <0.9.0 >=0.8.7 <0.9.0;
////// lib/openzeppelin-contracts/contracts/utils/Context.sol
/* pragma solidity ^0.8.0; */
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
////// lib/openzeppelin-contracts/contracts/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);
}
}
////// lib/openzeppelin-contracts/contracts/proxy/beacon/IBeacon.sol
/* pragma solidity ^0.8.0; */
/**
* @dev This is the interface that {BeaconProxy} expects of its beacon.
*/
interface IBeacon {
/**
* @dev Must return an address that can be used as a delegate call target.
*
* {BeaconProxy} will check that this address is a contract.
*/
function implementation() external view returns (address);
}
////// lib/openzeppelin-contracts/contracts/utils/Address.sol
/* pragma solidity ^0.8.0; */
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
////// lib/openzeppelin-contracts/contracts/utils/StorageSlot.sol
/* pragma solidity ^0.8.0; */
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC1967 implementation slot:
* ```
* contract ERC1967 {
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._
*/
library StorageSlot {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
assembly {
r.slot := slot
}
}
}
////// lib/openzeppelin-contracts/contracts/proxy/ERC1967/ERC1967Upgrade.sol
/* pragma solidity ^0.8.2; */
/* import "../beacon/IBeacon.sol"; */
/* import "../../utils/Address.sol"; */
/* import "../../utils/StorageSlot.sol"; */
/**
* @dev This abstract contract provides getters and event emitting update functions for
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
*
* _Available since v4.1._
*
* @custom:oz-upgrades-unsafe-allow delegatecall
*/
abstract contract ERC1967Upgrade {
// This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1
bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Returns the current implementation address.
*/
function _getImplementation() internal view returns (address) {
return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
}
/**
* @dev Perform implementation upgrade
*
* Emits an {Upgraded} event.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Perform implementation upgrade with additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCall(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
_upgradeTo(newImplementation);
if (data.length > 0 || forceCall) {
Address.functionDelegateCall(newImplementation, data);
}
}
/**
* @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCallSecure(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
address oldImplementation = _getImplementation();
// Initial upgrade and setup call
_setImplementation(newImplementation);
if (data.length > 0 || forceCall) {
Address.functionDelegateCall(newImplementation, data);
}
// Perform rollback test if not already in progress
StorageSlot.BooleanSlot storage rollbackTesting = StorageSlot.getBooleanSlot(_ROLLBACK_SLOT);
if (!rollbackTesting.value) {
// Trigger rollback using upgradeTo from the new implementation
rollbackTesting.value = true;
Address.functionDelegateCall(
newImplementation,
abi.encodeWithSignature("upgradeTo(address)", oldImplementation)
);
rollbackTesting.value = false;
// Check rollback was effective
require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades");
// Finally reset to the new implementation and log the upgrade
_upgradeTo(newImplementation);
}
}
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Returns the current admin.
*/
function _getAdmin() internal view returns (address) {
return StorageSlot.getAddressSlot(_ADMIN_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
require(newAdmin != address(0), "ERC1967: new admin is the zero address");
StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {AdminChanged} event.
*/
function _changeAdmin(address newAdmin) internal {
emit AdminChanged(_getAdmin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
* This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.
*/
bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/**
* @dev Emitted when the beacon is upgraded.
*/
event BeaconUpgraded(address indexed beacon);
/**
* @dev Returns the current beacon.
*/
function _getBeacon() internal view returns (address) {
return StorageSlot.getAddressSlot(_BEACON_SLOT).value;
}
/**
* @dev Stores a new beacon in the EIP1967 beacon slot.
*/
function _setBeacon(address newBeacon) private {
require(Address.isContract(newBeacon), "ERC1967: new beacon is not a contract");
require(
Address.isContract(IBeacon(newBeacon).implementation()),
"ERC1967: beacon implementation is not a contract"
);
StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon;
}
/**
* @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does
* not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).
*
* Emits a {BeaconUpgraded} event.
*/
function _upgradeBeaconToAndCall(
address newBeacon,
bytes memory data,
bool forceCall
) internal {
_setBeacon(newBeacon);
emit BeaconUpgraded(newBeacon);
if (data.length > 0 || forceCall) {
Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
}
}
}
////// lib/openzeppelin-contracts/contracts/proxy/Proxy.sol
/* pragma solidity ^0.8.0; */
/**
* @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM
* instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to
* be specified by overriding the virtual {_implementation} function.
*
* Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a
* different contract through the {_delegate} function.
*
* The success and return data of the delegated call will be returned back to the caller of the proxy.
*/
abstract contract Proxy {
/**
* @dev Delegates the current call to `implementation`.
*
* This function does not return to its internall call site, it will return directly to the external caller.
*/
function _delegate(address implementation) internal virtual {
assembly {
// Copy msg.data. We take full control of memory in this inline assembly
// block because it will not return to Solidity code. We overwrite the
// Solidity scratch pad at memory position 0.
calldatacopy(0, 0, calldatasize())
// Call the implementation.
// out and outsize are 0 because we don't know the size yet.
let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)
// Copy the returned data.
returndatacopy(0, 0, returndatasize())
switch result
// delegatecall returns 0 on error.
case 0 {
revert(0, returndatasize())
}
default {
return(0, returndatasize())
}
}
}
/**
* @dev This is a virtual function that should be overriden so it returns the address to which the fallback function
* and {_fallback} should delegate.
*/
function _implementation() internal view virtual returns (address);
/**
* @dev Delegates the current call to the address returned by `_implementation()`.
*
* This function does not return to its internall call site, it will return directly to the external caller.
*/
function _fallback() internal virtual {
_beforeFallback();
_delegate(_implementation());
}
/**
* @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other
* function in the contract matches the call data.
*/
fallback() external payable virtual {
_fallback();
}
/**
* @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data
* is empty.
*/
receive() external payable virtual {
_fallback();
}
/**
* @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback`
* call, or as part of the Solidity `fallback` or `receive` functions.
*
* If overriden should call `super._beforeFallback()`.
*/
function _beforeFallback() internal virtual {}
}
////// lib/openzeppelin-contracts/contracts/proxy/ERC1967/ERC1967Proxy.sol
/* pragma solidity ^0.8.0; */
/* import "../Proxy.sol"; */
/* import "./ERC1967Upgrade.sol"; */
/**
* @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an
* implementation address that can be changed. This address is stored in storage in the location specified by
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the
* implementation behind the proxy.
*/
contract ERC1967Proxy is Proxy, ERC1967Upgrade {
/**
* @dev Initializes the upgradeable proxy with an initial implementation specified by `_logic`.
*
* If `_data` is nonempty, it's used as data in a delegate call to `_logic`. This will typically be an encoded
* function call, and allows initializating the storage of the proxy like a Solidity constructor.
*/
constructor(address _logic, bytes memory _data) payable {
assert(_IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1));
_upgradeToAndCall(_logic, _data, false);
}
/**
* @dev Returns the current implementation address.
*/
function _implementation() internal view virtual override returns (address impl) {
return ERC1967Upgrade._getImplementation();
}
}
////// lib/openzeppelin-contracts/contracts/proxy/utils/UUPSUpgradeable.sol
/* pragma solidity ^0.8.0; */
/* import "../ERC1967/ERC1967Upgrade.sol"; */
/**
* @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
* {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
*
* A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
* reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
* `UUPSUpgradeable` with a custom implementation of upgrades.
*
* The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
*
* _Available since v4.1._
*/
abstract contract UUPSUpgradeable is ERC1967Upgrade {
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment
address private immutable __self = address(this);
/**
* @dev Check that the execution is being performed through a delegatecall call and that the execution context is
* a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case
* for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
* function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
* fail.
*/
modifier onlyProxy() {
require(address(this) != __self, "Function must be called through delegatecall");
require(_getImplementation() == __self, "Function must be called through active proxy");
_;
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*/
function upgradeTo(address newImplementation) external virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallSecure(newImplementation, new bytes(0), false);
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
* encoded in `data`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*/
function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallSecure(newImplementation, data, true);
}
/**
* @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
* {upgradeTo} and {upgradeToAndCall}.
*
* Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
*
* ```solidity
* function _authorizeUpgrade(address) internal override onlyOwner {}
* ```
*/
function _authorizeUpgrade(address newImplementation) internal virtual;
}
////// lib/openzeppelin-contracts/contracts/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);
}
////// lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol
/* pragma solidity ^0.8.0; */
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
////// lib/openzeppelin-contracts/contracts/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;
}
////// lib/openzeppelin-contracts/contracts/token/ERC721/IERC721Receiver.sol
/* pragma solidity ^0.8.0; */
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
////// lib/openzeppelin-contracts/contracts/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);
}
////// lib/openzeppelin-contracts/contracts/utils/Strings.sol
/* pragma solidity ^0.8.0; */
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
////// lib/openzeppelin-contracts/contracts/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;
}
}
////// lib/openzeppelin-contracts/contracts/token/ERC721/ERC721.sol
/* pragma solidity ^0.8.0; */
/* import "./IERC721.sol"; */
/* import "./IERC721Receiver.sol"; */
/* import "./extensions/IERC721Metadata.sol"; */
/* import "../../utils/Address.sol"; */
/* import "../../utils/Context.sol"; */
/* import "../../utils/Strings.sol"; */
/* import "../../utils/introspection/ERC165.sol"; */
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
////// lib/radicle-drips-hub/src/Dai.sol
/* pragma solidity ^0.8.7; */
/* import {IERC20} from "openzeppelin-contracts/token/ERC20/IERC20.sol"; */
interface IDai is IERC20 {
function permit(
address holder,
address spender,
uint256 nonce,
uint256 expiry,
bool allowed,
uint8 v,
bytes32 r,
bytes32 s
) external;
}
////// lib/radicle-drips-hub/src/ERC20Reserve.sol
/* pragma solidity ^0.8.7; */
/* import {Ownable} from "openzeppelin-contracts/access/Ownable.sol"; */
/* import {IERC20} from "openzeppelin-contracts/token/ERC20/IERC20.sol"; */
interface IERC20Reserve {
function erc20() external view returns (IERC20);
function withdraw(uint256 amt) external;
function deposit(uint256 amt) external;
}
contract ERC20Reserve is IERC20Reserve, Ownable {
IERC20 public immutable override erc20;
address public user;
uint256 public balance;
event Withdrawn(address to, uint256 amt);
event Deposited(address from, uint256 amt);
event ForceWithdrawn(address to, uint256 amt);
event UserSet(address oldUser, address newUser);
constructor(
IERC20 _erc20,
address owner,
address _user
) {
erc20 = _erc20;
setUser(_user);
transferOwnership(owner);
}
modifier onlyUser() {
require(_msgSender() == user, "Reserve: caller is not the user");
_;
}
function withdraw(uint256 amt) public override onlyUser {
require(balance >= amt, "Reserve: withdrawal over balance");
balance -= amt;
emit Withdrawn(_msgSender(), amt);
require(erc20.transfer(_msgSender(), amt), "Reserve: transfer failed");
}
function deposit(uint256 amt) public override onlyUser {
balance += amt;
emit Deposited(_msgSender(), amt);
require(erc20.transferFrom(_msgSender(), address(this), amt), "Reserve: transfer failed");
}
function forceWithdraw(uint256 amt) public onlyOwner {
emit ForceWithdrawn(_msgSender(), amt);
require(erc20.transfer(_msgSender(), amt), "Reserve: transfer failed");
}
function setUser(address newUser) public onlyOwner {
emit UserSet(user, newUser);
user = newUser;
}
}
////// lib/radicle-drips-hub/src/DaiReserve.sol
/* pragma solidity ^0.8.7; */
/* import {ERC20Reserve, IERC20Reserve} from "./ERC20Reserve.sol"; */
/* import {IDai} from "./Dai.sol"; */
interface IDaiReserve is IERC20Reserve {
function dai() external view returns (IDai);
}
contract DaiReserve is ERC20Reserve, IDaiReserve {
IDai public immutable override dai;
constructor(
IDai _dai,
address owner,
address user
) ERC20Reserve(_dai, owner, user) {
dai = _dai;
}
}
////// lib/radicle-drips-hub/src/DripsHub.sol
/* pragma solidity ^0.8.7; */
struct DripsReceiver {
address receiver;
uint128 amtPerSec;
}
struct SplitsReceiver {
address receiver;
uint32 weight;
}
/// @notice Drips hub contract. Automatically drips and splits funds between users.
///
/// The user can transfer some funds to their drips balance in the contract
/// and configure a list of receivers, to whom they want to drip these funds.
/// As soon as the drips balance is enough to cover at least 1 second of dripping
/// to the configured receivers, the funds start dripping automatically.
/// Every second funds are deducted from the drips balance and moved to their receivers' accounts.
/// The process stops automatically when the drips balance is not enough to cover another second.
///
/// The user can have any number of independent configurations and drips balances by using accounts.
/// An account is identified by the user address and an account identifier.
/// Accounts of different users are separate entities, even if they have the same identifiers.
/// An account can be used to drip or give, but not to receive funds.
///
/// Every user has a receiver balance, in which they have funds received from other users.
/// The dripped funds are added to the receiver balances in global cycles.
/// Every `cycleSecs` seconds the drips hub adds dripped funds to the receivers' balances,
/// so recently dripped funds may not be collectable immediately.
/// `cycleSecs` is a constant configured when the drips hub is deployed.
/// The receiver balance is independent from the drips balance,
/// to drip received funds they need to be first collected and then added to the drips balance.
///
/// The user can share collected funds with other users by using splits.
/// When collecting, the user gives each of their splits receivers a fraction of the received funds.
/// Funds received from splits are available for collection immediately regardless of the cycle.
/// They aren't exempt from being split, so they too can be split when collected.
/// Users can build chains and networks of splits between each other.
/// Anybody can request collection of funds for any user,
/// which can be used to enforce the flow of funds in the network of splits.
///
/// The concept of something happening periodically, e.g. every second or every `cycleSecs` are
/// only high-level abstractions for the user, Ethereum isn't really capable of scheduling work.
/// The actual implementation emulates that behavior by calculating the results of the scheduled
/// events based on how many seconds have passed and only when the user needs their outcomes.
///
/// The contract assumes that all amounts in the system can be stored in signed 128-bit integers.
/// It's guaranteed to be safe only when working with assets with supply lower than `2 ^ 127`.
abstract contract DripsHub {
/// @notice On every timestamp `T`, which is a multiple of `cycleSecs`, the receivers
/// gain access to drips collected during `T - cycleSecs` to `T - 1`.
uint64 public immutable cycleSecs;
/// @notice Timestamp at which all drips must be finished
uint64 internal constant MAX_TIMESTAMP = type(uint64).max - 2;
/// @notice Maximum number of drips receivers of a single user.
/// Limits cost of changes in drips configuration.
uint32 public constant MAX_DRIPS_RECEIVERS = 100;
/// @notice Maximum number of splits receivers of a single user.
/// Limits cost of collecting.
uint32 public constant MAX_SPLITS_RECEIVERS = 200;
/// @notice The total splits weight of a user
uint32 public constant TOTAL_SPLITS_WEIGHT = 1_000_000;
/// @notice The ERC-1967 storage slot for the contract.
/// It holds a single `DripsHubStorage` structure.
bytes32 private constant SLOT_STORAGE =
bytes32(uint256(keccak256("eip1967.dripsHub.storage")) - 1);
/// @notice Emitted when drips from a user to a receiver are updated.
/// Funds are being dripped on every second between the event block's timestamp (inclusively)
/// and`endTime` (exclusively) or until the timestamp of the next drips update (exclusively).
/// @param user The dripping user
/// @param receiver The receiver of the updated drips
/// @param amtPerSec The new amount per second dripped from the user
/// to the receiver or 0 if the drips are stopped
/// @param endTime The timestamp when dripping will stop,
/// always larger than the block timestamp or equal to it if the drips are stopped
event Dripping(
address indexed user,
address indexed receiver,
uint128 amtPerSec,
uint64 endTime
);
/// @notice Emitted when drips from a user's account to a receiver are updated.
/// Funds are being dripped on every second between the event block's timestamp (inclusively)
/// and`endTime` (exclusively) or until the timestamp of the next drips update (exclusively).
/// @param user The user
/// @param account The dripping account
/// @param receiver The receiver of the updated drips
/// @param amtPerSec The new amount per second dripped from the user's account
/// to the receiver or 0 if the drips are stopped
/// @param endTime The timestamp when dripping will stop,
/// always larger than the block timestamp or equal to it if the drips are stopped
event Dripping(
address indexed user,
uint256 indexed account,
address indexed receiver,
uint128 amtPerSec,
uint64 endTime
);
/// @notice Emitted when the drips configuration of a user is updated.
/// @param user The user
/// @param balance The new drips balance. These funds will be dripped to the receivers.
/// @param receivers The new list of the drips receivers.
event DripsUpdated(address indexed user, uint128 balance, DripsReceiver[] receivers);
/// @notice Emitted when the drips configuration of a user's account is updated.
/// @param user The user
/// @param account The account
/// @param balance The new drips balance. These funds will be dripped to the receivers.
/// @param receivers The new list of the drips receivers.
event DripsUpdated(
address indexed user,
uint256 indexed account,
uint128 balance,
DripsReceiver[] receivers
);
/// @notice Emitted when the user's splits are updated.
/// @param user The user
/// @param receivers The list of the user's splits receivers.
event SplitsUpdated(address indexed user, SplitsReceiver[] receivers);
/// @notice Emitted when a user collects funds
/// @param user The user
/// @param collected The collected amount
/// @param split The amount split to the user's splits receivers
event Collected(address indexed user, uint128 collected, uint128 split);
/// @notice Emitted when funds are split from a user to a receiver.
/// This is caused by the user collecting received funds.
/// @param user The user
/// @param receiver The splits receiver
/// @param amt The amount split to the receiver
event Split(address indexed user, address indexed receiver, uint128 amt);
/// @notice Emitted when funds are given from the user to the receiver.
/// @param user The address of the user
/// @param receiver The receiver
/// @param amt The given amount
event Given(address indexed user, address indexed receiver, uint128 amt);
/// @notice Emitted when funds are given from the user's account to the receiver.
/// @param user The address of the user
/// @param account The user's account
/// @param receiver The receiver
/// @param amt The given amount
event Given(
address indexed user,
uint256 indexed account,
address indexed receiver,
uint128 amt
);
struct ReceiverState {
// The amount collectable independently from cycles
uint128 collectable;
// The next cycle to be collected
uint64 nextCollectedCycle;
// --- SLOT BOUNDARY
// The changes of collected amounts on specific cycle.
// The keys are cycles, each cycle `C` becomes collectable on timestamp `C * cycleSecs`.
// Values for cycles before `nextCollectedCycle` are guaranteed to be zeroed.
// This means that the value of `amtDeltas[nextCollectedCycle].thisCycle` is always
// relative to 0 or in other words it's an absolute value independent from other cycles.
mapping(uint64 => AmtDelta) amtDeltas;
}
struct AmtDelta {
// Amount delta applied on this cycle
int128 thisCycle;
// Amount delta applied on the next cycle
int128 nextCycle;
}
struct UserOrAccount {
bool isAccount;
address user;
uint256 account;
}
struct DripsHubStorage {
/// @notice Users' splits configuration hashes, see `hashSplits`.
/// The key is the user address.
mapping(address => bytes32) splitsHash;
/// @notice Users' drips configuration hashes, see `hashDrips`.
/// The key is the user address.
mapping(address => bytes32) userDripsHashes;
/// @notice Users' accounts' configuration hashes, see `hashDrips`.
/// The key are the user address and the account.
mapping(address => mapping(uint256 => bytes32)) accountDripsHashes;
/// @notice Users' receiver states.
/// The key is the user address.
mapping(address => ReceiverState) receiverStates;
}
/// @param _cycleSecs The length of cycleSecs to be used in the contract instance.
/// Low value makes funds more available by shortening the average time of funds being frozen
/// between being taken from the users' drips balances and being collectable by their receivers.
/// High value makes collecting cheaper by making it process less cycles for a given time range.
constructor(uint64 _cycleSecs) {
cycleSecs = _cycleSecs;
}
/// @notice Returns the contract storage.
/// @return dripsHubStorage The storage.
function _storage() internal pure returns (DripsHubStorage storage dripsHubStorage) {
bytes32 slot = SLOT_STORAGE;
// solhint-disable-next-line no-inline-assembly
assembly {
// Based on OpenZeppelin's StorageSlot
dripsHubStorage.slot := slot
}
}
/// @notice Returns amount of received funds available for collection for a user.
/// @param user The user
/// @param currReceivers The list of the user's current splits receivers.
/// @return collected The collected amount
/// @return split The amount split to the user's splits receivers
function collectable(address user, SplitsReceiver[] memory currReceivers)
public
view
returns (uint128 collected, uint128 split)
{
ReceiverState storage receiver = _storage().receiverStates[user];
_assertCurrSplits(user, currReceivers);
// Collectable independently from cycles
collected = receiver.collectable;
// Collectable from cycles
uint64 collectedCycle = receiver.nextCollectedCycle;
uint64 currFinishedCycle = _currTimestamp() / cycleSecs;
if (collectedCycle != 0 && collectedCycle <= currFinishedCycle) {
int128 cycleAmt = 0;
for (; collectedCycle <= currFinishedCycle; collectedCycle++) {
cycleAmt += receiver.amtDeltas[collectedCycle].thisCycle;
collected += uint128(cycleAmt);
cycleAmt += receiver.amtDeltas[collectedCycle].nextCycle;
}
}
// split when collected
if (collected > 0 && currReceivers.length > 0) {
uint32 splitsWeight = 0;
for (uint256 i = 0; i < currReceivers.length; i++) {
splitsWeight += currReceivers[i].weight;
}
split = uint128((uint160(collected) * splitsWeight) / TOTAL_SPLITS_WEIGHT);
collected -= split;
}
}
/// @notice Collects all received funds available for the user
/// and transfers them out of the drips hub contract to that user's wallet.
/// @param user The user
/// @param currReceivers The list of the user's current splits receivers.
/// @return collected The collected amount
/// @return split The amount split to the user's splits receivers
function collect(address user, SplitsReceiver[] memory currReceivers)
public
virtual
returns (uint128 collected, uint128 split)
{
(collected, split) = _collectInternal(user, currReceivers);
_transfer(user, int128(collected));
}
/// @notice Counts cycles which will need to be analyzed when collecting or flushing.
/// This function can be used to detect that there are too many cycles
/// to analyze in a single transaction and flushing is needed.
/// @param user The user
/// @return flushable The number of cycles which can be flushed
function flushableCycles(address user) public view returns (uint64 flushable) {
uint64 nextCollectedCycle = _storage().receiverStates[user].nextCollectedCycle;
if (nextCollectedCycle == 0) return 0;
uint64 currFinishedCycle = _currTimestamp() / cycleSecs;
return currFinishedCycle + 1 - nextCollectedCycle;
}
/// @notice Flushes uncollected cycles of the user.
/// Flushed cycles won't need to be analyzed when the user collects from them.
/// Calling this function does not collect and does not affect the collectable amount.
///
/// This function is needed when collecting funds received over a period so long, that the gas
/// needed for analyzing all the uncollected cycles can't fit in a single transaction.
/// Calling this function allows spreading the analysis cost over multiple transactions.
/// A cycle is never flushed more than once, even if this function is called many times.
/// @param user The user
/// @param maxCycles The maximum number of flushed cycles.
/// If too low, flushing will be cheap, but will cut little gas from the next collection.
/// If too high, flushing may become too expensive to fit in a single transaction.
/// @return flushable The number of cycles which can be flushed
function flushCycles(address user, uint64 maxCycles) public virtual returns (uint64 flushable) {
flushable = flushableCycles(user);
uint64 cycles = maxCycles < flushable ? maxCycles : flushable;
flushable -= cycles;
uint128 collected = _flushCyclesInternal(user, cycles);
if (collected > 0) _storage().receiverStates[user].collectable += collected;
}
/// @notice Collects all received funds available for the user,
/// but doesn't transfer them to the user's wallet.
/// @param user The user
/// @param currReceivers The list of the user's current splits receivers.
/// @return collected The collected amount
/// @return split The amount split to the user's splits receivers
function _collectInternal(address user, SplitsReceiver[] memory currReceivers)
internal
returns (uint128 collected, uint128 split)
{
mapping(address => ReceiverState) storage receiverStates = _storage().receiverStates;
ReceiverState storage receiver = receiverStates[user];
_assertCurrSplits(user, currReceivers);
// Collectable independently from cycles
collected = receiver.collectable;
if (collected > 0) receiver.collectable = 0;
// Collectable from cycles
uint64 cycles = flushableCycles(user);
collected += _flushCyclesInternal(user, cycles);
// split when collected
if (collected > 0 && currReceivers.length > 0) {
uint32 splitsWeight = 0;
for (uint256 i = 0; i < currReceivers.length; i++) {
splitsWeight += currReceivers[i].weight;
uint128 splitsAmt = uint128(
(uint160(collected) * splitsWeight) / TOTAL_SPLITS_WEIGHT - split
);
split += splitsAmt;
address splitsReceiver = currReceivers[i].receiver;
receiverStates[splitsReceiver].collectable += splitsAmt;
emit Split(user, splitsReceiver, splitsAmt);
}
collected -= split;
}
emit Collected(user, collected, split);
}
/// @notice Collects and clears user's cycles
/// @param user The user
/// @param count The number of flushed cycles.
/// @return collectedAmt The collected amount
function _flushCyclesInternal(address user, uint64 count)
internal
returns (uint128 collectedAmt)
{
if (count == 0) return 0;
ReceiverState storage receiver = _storage().receiverStates[user];
uint64 cycle = receiver.nextCollectedCycle;
int128 cycleAmt = 0;
for (uint256 i = 0; i < count; i++) {
cycleAmt += receiver.amtDeltas[cycle].thisCycle;
collectedAmt += uint128(cycleAmt);
cycleAmt += receiver.amtDeltas[cycle].nextCycle;
delete receiver.amtDeltas[cycle];
cycle++;
}
// The next cycle delta must be relative to the last collected cycle, which got zeroed.
// In other words the next cycle delta must be an absolute value.
if (cycleAmt != 0) receiver.amtDeltas[cycle].thisCycle += cycleAmt;
receiver.nextCollectedCycle = cycle;
}
/// @notice Gives funds from the user or their account to the receiver.
/// The receiver can collect them immediately.
/// Transfers the funds to be given from the user's wallet to the drips hub contract.
/// @param userOrAccount The user or their account
/// @param receiver The receiver
/// @param amt The given amount
function _give(
UserOrAccount memory userOrAccount,
address receiver,
uint128 amt
) internal {
_storage().receiverStates[receiver].collectable += amt;
if (userOrAccount.isAccount) {
emit Given(userOrAccount.user, userOrAccount.account, receiver, amt);
} else {
emit Given(userOrAccount.user, receiver, amt);
}
_transfer(userOrAccount.user, -int128(amt));
}
/// @notice Current user's drips hash, see `hashDrips`.
/// @param user The user
/// @return currDripsHash The current user's drips hash
function dripsHash(address user) public view returns (bytes32 currDripsHash) {
return _storage().userDripsHashes[user];
}
/// @notice Current user account's drips hash, see `hashDrips`.
/// @param user The user
/// @param account The account
/// @return currDripsHash The current user account's drips hash
function dripsHash(address user, uint256 account) public view returns (bytes32 currDripsHash) {
return _storage().accountDripsHashes[user][account];
}
/// @notice Sets the user's or the account's drips configuration.
/// Transfers funds between the user's wallet and the drips hub contract
/// to fulfill the change of the drips balance.
/// @param userOrAccount The user or their account
/// @param lastUpdate The timestamp of the last drips update of the user or the account.
/// If this is the first update, pass zero.
/// @param lastBalance The drips balance after the last drips update of the user or the account.
/// If this is the first update, pass zero.
/// @param currReceivers The list of the drips receivers set in the last drips update
/// of the user or the account.
/// If this is the first update, pass an empty array.
/// @param balanceDelta The drips balance change to be applied.
/// Positive to add funds to the drips balance, negative to remove them.
/// @param newReceivers The list of the drips receivers of the user or the account to be set.
/// Must be sorted by the receivers' addresses, deduplicated and without 0 amtPerSecs.
/// @return newBalance The new drips balance of the user or the account.
/// Pass it as `lastBalance` when updating that user or the account for the next time.
/// @return realBalanceDelta The actually applied drips balance change.
function _setDrips(
UserOrAccount memory userOrAccount,
uint64 lastUpdate,
uint128 lastBalance,
DripsReceiver[] memory currReceivers,
int128 balanceDelta,
DripsReceiver[] memory newReceivers
) internal returns (uint128 newBalance, int128 realBalanceDelta) {
_assertCurrDrips(userOrAccount, lastUpdate, lastBalance, currReceivers);
uint128 newAmtPerSec = _assertDripsReceiversValid(newReceivers);
uint128 currAmtPerSec = _totalDripsAmtPerSec(currReceivers);
uint64 currEndTime = _dripsEndTime(lastUpdate, lastBalance, currAmtPerSec);
(newBalance, realBalanceDelta) = _updateDripsBalance(
lastUpdate,
lastBalance,
currEndTime,
currAmtPerSec,
balanceDelta
);
uint64 newEndTime = _dripsEndTime(_currTimestamp(), newBalance, newAmtPerSec);
_updateDripsReceiversStates(
userOrAccount,
currReceivers,
currEndTime,
newReceivers,
newEndTime
);
_storeNewDrips(userOrAccount, newBalance, newReceivers);
_emitDripsUpdated(userOrAccount, newBalance, newReceivers);
_transfer(userOrAccount.user, -realBalanceDelta);
}
/// @notice Validates a list of drips receivers.
/// @param receivers The list of drips receivers.
/// Must be sorted by the receivers' addresses, deduplicated and without 0 amtPerSecs.
/// @return totalAmtPerSec The total amount per second of all drips receivers.
function _assertDripsReceiversValid(DripsReceiver[] memory receivers)
internal
pure
returns (uint128 totalAmtPerSec)
{
require(receivers.length <= MAX_DRIPS_RECEIVERS, "Too many drips receivers");
uint256 amtPerSec = 0;
address prevReceiver;
for (uint256 i = 0; i < receivers.length; i++) {
uint128 amt = receivers[i].amtPerSec;
require(amt != 0, "Drips receiver amtPerSec is zero");
amtPerSec += amt;
address receiver = receivers[i].receiver;
if (i > 0) {
require(prevReceiver != receiver, "Duplicate drips receivers");
require(prevReceiver < receiver, "Drips receivers not sorted by address");
}
prevReceiver = receiver;
}
require(amtPerSec <= type(uint128).max, "Total drips receivers amtPerSec too high");
return uint128(amtPerSec);
}
/// @notice Calculates the total amount per second of all the drips receivers.
/// @param receivers The list of the receivers.
/// It must have passed `_assertDripsReceiversValid` in the past.
/// @return totalAmtPerSec The total amount per second of all the drips receivers
function _totalDripsAmtPerSec(DripsReceiver[] memory receivers)
internal
pure
returns (uint128 totalAmtPerSec)
{
uint256 length = receivers.length;
uint256 i = 0;
while (i < length) {
// Safe, because `receivers` passed `_assertDripsReceiversValid` in the past
unchecked {
totalAmtPerSec += receivers[i++].amtPerSec;
}
}
}
/// @notice Updates drips balance.
/// @param lastUpdate The timestamp of the last drips update.
/// If this is the first update, pass zero.
/// @param lastBalance The drips balance after the last drips update.
/// If this is the first update, pass zero.
/// @param currEndTime Time when drips were supposed to end according to the last drips update.
/// @param currAmtPerSec The total amount per second of all drips receivers
/// according to the last drips update.
/// @param balanceDelta The drips balance change to be applied.
/// Positive to add funds to the drips balance, negative to remove them.
/// @return newBalance The new drips balance.
/// Pass it as `lastBalance` when updating for the next time.
/// @return realBalanceDelta The actually applied drips balance change.
/// If positive, this is the amount which should be transferred from the user to the drips hub,
/// or if negative, from the drips hub to the user.
function _updateDripsBalance(
uint64 lastUpdate,
uint128 lastBalance,
uint64 currEndTime,
uint128 currAmtPerSec,
int128 balanceDelta
) internal view returns (uint128 newBalance, int128 realBalanceDelta) {
if (currEndTime > _currTimestamp()) currEndTime = _currTimestamp();
uint128 dripped = (currEndTime - lastUpdate) * currAmtPerSec;
int128 currBalance = int128(lastBalance - dripped);
int136 balance = currBalance + int136(balanceDelta);
if (balance < 0) balance = 0;
return (uint128(uint136(balance)), int128(balance - currBalance));
}
/// @notice Emit an event when drips are updated.
/// @param userOrAccount The user or their account
/// @param balance The new drips balance.
/// @param receivers The new list of the drips receivers.
function _emitDripsUpdated(
UserOrAccount memory userOrAccount,
uint128 balance,
DripsReceiver[] memory receivers
) internal {
if (userOrAccount.isAccount) {
emit DripsUpdated(userOrAccount.user, userOrAccount.account, balance, receivers);
} else {
emit DripsUpdated(userOrAccount.user, balance, receivers);
}
}
/// @notice Updates the user's or the account's drips receivers' states.
/// It applies the effects of the change of the drips configuration.
/// @param userOrAccount The user or their account
/// @param currReceivers The list of the drips receivers set in the last drips update
/// of the user or the account.
/// If this is the first update, pass an empty array.
/// @param currEndTime Time when drips were supposed to end according to the last drips update.
/// @param newReceivers The list of the drips receivers of the user or the account to be set.
/// Must be sorted by the receivers' addresses, deduplicated and without 0 amtPerSecs.
/// @param newEndTime Time when drips will end according to the new drips configuration.
function _updateDripsReceiversStates(
UserOrAccount memory userOrAccount,
DripsReceiver[] memory currReceivers,
uint64 currEndTime,
DripsReceiver[] memory newReceivers,
uint64 newEndTime
) internal {
// Skip iterating over `currReceivers` if dripping has run out
uint256 currIdx = currEndTime > _currTimestamp() ? 0 : currReceivers.length;
// Skip iterating over `newReceivers` if no new dripping is started
uint256 newIdx = newEndTime > _currTimestamp() ? 0 : newReceivers.length;
while (true) {
// Each iteration gets the next drips update and applies it on the receiver state.
// A drips update is composed of two drips receiver configurations,
// one current and one new, or from a single drips receiver configuration
// if the drips receiver is being added or removed.
bool pickCurr = currIdx < currReceivers.length;
bool pickNew = newIdx < newReceivers.length;
if (!pickCurr && !pickNew) break;
if (pickCurr && pickNew) {
// There are two candidate drips receiver configurations to create a drips update.
// Pick both if they describe the same receiver or the one with a lower address.
// The one with a higher address won't be used in this iteration.
// Because drips receivers lists are sorted by addresses and deduplicated,
// all matching pairs of drips receiver configurations will be found.
address currReceiver = currReceivers[currIdx].receiver;
address newReceiver = newReceivers[newIdx].receiver;
pickCurr = currReceiver <= newReceiver;
pickNew = newReceiver <= currReceiver;
}
// The drips update parameters
address receiver;
int128 currAmtPerSec = 0;
int128 newAmtPerSec = 0;
if (pickCurr) {
receiver = currReceivers[currIdx].receiver;
currAmtPerSec = int128(currReceivers[currIdx].amtPerSec);
// Clear the obsolete drips end
_setDelta(receiver, currEndTime, currAmtPerSec);
currIdx++;
}
if (pickNew) {
receiver = newReceivers[newIdx].receiver;
newAmtPerSec = int128(newReceivers[newIdx].amtPerSec);
// Apply the new drips end
_setDelta(receiver, newEndTime, -newAmtPerSec);
newIdx++;
}
// Apply the drips update since now
_setDelta(receiver, _currTimestamp(), newAmtPerSec - currAmtPerSec);
_emitDripping(userOrAccount, receiver, uint128(newAmtPerSec), newEndTime);
// The receiver may have never been used
if (!pickCurr) {
ReceiverState storage receiverState = _storage().receiverStates[receiver];
// The receiver has never been used, initialize it
if (receiverState.nextCollectedCycle == 0) {
receiverState.nextCollectedCycle = _currTimestamp() / cycleSecs + 1;
}
}
}
}
/// @notice Emit an event when drips from a user to a receiver are updated.
/// @param userOrAccount The user or their account
/// @param receiver The receiver
/// @param amtPerSec The new amount per second dripped from the user or the account
/// to the receiver or 0 if the drips are stopped
/// @param endTime The timestamp when dripping will stop
function _emitDripping(
UserOrAccount memory userOrAccount,
address receiver,
uint128 amtPerSec,
uint64 endTime
) internal {
if (amtPerSec == 0) endTime = _currTimestamp();
if (userOrAccount.isAccount) {
emit Dripping(userOrAccount.user, userOrAccount.account, receiver, amtPerSec, endTime);
} else {
emit Dripping(userOrAccount.user, receiver, amtPerSec, endTime);
}
}
/// @notice Calculates the timestamp when dripping will end.
/// @param startTime Time when dripping is started.
/// @param startBalance The drips balance when dripping is started.
/// @param totalAmtPerSec The total amount per second of all the drips receivers
/// @return dripsEndTime The dripping end time.
function _dripsEndTime(
uint64 startTime,
uint128 startBalance,
uint128 totalAmtPerSec
) internal pure returns (uint64 dripsEndTime) {
if (totalAmtPerSec == 0) return startTime;
uint256 endTime = startTime + uint256(startBalance / totalAmtPerSec);
return endTime > MAX_TIMESTAMP ? MAX_TIMESTAMP : uint64(endTime);
}
/// @notice Asserts that the drips configuration is the currently used one.
/// @param userOrAccount The user or their account
/// @param lastUpdate The timestamp of the last drips update of the user or the account.
/// If this is the first update, pass zero.
/// @param lastBalance The drips balance after the last drips update of the user or the account.
/// If this is the first update, pass zero.
/// @param currReceivers The list of the drips receivers set in the last drips update
/// of the user or the account.
/// If this is the first update, pass an empty array.
function _assertCurrDrips(
UserOrAccount memory userOrAccount,
uint64 lastUpdate,
uint128 lastBalance,
DripsReceiver[] memory currReceivers
) internal view {
bytes32 expectedHash;
if (userOrAccount.isAccount) {
expectedHash = _storage().accountDripsHashes[userOrAccount.user][userOrAccount.account];
} else {
expectedHash = _storage().userDripsHashes[userOrAccount.user];
}
bytes32 actualHash = hashDrips(lastUpdate, lastBalance, currReceivers);
require(actualHash == expectedHash, "Invalid current drips configuration");
}
/// @notice Stores the hash of the new drips configuration to be used in `_assertCurrDrips`.
/// @param userOrAccount The user or their account
/// @param newBalance The user or the account drips balance.
/// @param newReceivers The list of the drips receivers of the user or the account.
/// Must be sorted by the receivers' addresses, deduplicated and without 0 amtPerSecs.
function _storeNewDrips(
UserOrAccount memory userOrAccount,
uint128 newBalance,
DripsReceiver[] memory newReceivers
) internal {
bytes32 newDripsHash = hashDrips(_currTimestamp(), newBalance, newReceivers);
if (userOrAccount.isAccount) {
_storage().accountDripsHashes[userOrAccount.user][userOrAccount.account] = newDripsHash;
} else {
_storage().userDripsHashes[userOrAccount.user] = newDripsHash;
}
}
/// @notice Calculates the hash of the drips configuration.
/// It's used to verify if drips configuration is the previously set one.
/// @param update The timestamp of the drips update.
/// If the drips have never been updated, pass zero.
/// @param balance The drips balance.
/// If the drips have never been updated, pass zero.
/// @param receivers The list of the drips receivers.
/// Must be sorted by the receivers' addresses, deduplicated and without 0 amtPerSecs.
/// If the drips have never been updated, pass an empty array.
/// @return dripsConfigurationHash The hash of the drips configuration
function hashDrips(
uint64 update,
uint128 balance,
DripsReceiver[] memory receivers
) public pure returns (bytes32 dripsConfigurationHash) {
if (update == 0 && balance == 0 && receivers.length == 0) return bytes32(0);
return keccak256(abi.encode(receivers, update, balance));
}
/// @notice Collects funds received by the user and sets their splits.
/// The collected funds are split according to `currReceivers`.
/// @param user The user
/// @param currReceivers The list of the user's splits receivers which is currently in use.
/// If this function is called for the first time for the user, should be an empty array.
/// @param newReceivers The new list of the user's splits receivers.
/// Must be sorted by the splits receivers' addresses, deduplicated and without 0 weights.
/// Each splits receiver will be getting `weight / TOTAL_SPLITS_WEIGHT`
/// share of the funds collected by the user.
/// @return collected The collected amount
/// @return split The amount split to the user's splits receivers
function _setSplits(
address user,
SplitsReceiver[] memory currReceivers,
SplitsReceiver[] memory newReceivers
) internal returns (uint128 collected, uint128 split) {
(collected, split) = _collectInternal(user, currReceivers);
_assertSplitsValid(newReceivers);
_storage().splitsHash[user] = hashSplits(newReceivers);
emit SplitsUpdated(user, newReceivers);
_transfer(user, int128(collected));
}
/// @notice Validates a list of splits receivers
/// @param receivers The list of splits receivers
/// Must be sorted by the splits receivers' addresses, deduplicated and without 0 weights.
function _assertSplitsValid(SplitsReceiver[] memory receivers) internal pure {
require(receivers.length <= MAX_SPLITS_RECEIVERS, "Too many splits receivers");
uint64 totalWeight = 0;
address prevReceiver;
for (uint256 i = 0; i < receivers.length; i++) {
uint32 weight = receivers[i].weight;
require(weight != 0, "Splits receiver weight is zero");
totalWeight += weight;
address receiver = receivers[i].receiver;
if (i > 0) {
require(prevReceiver != receiver, "Duplicate splits receivers");
require(prevReceiver < receiver, "Splits receivers not sorted by address");
}
prevReceiver = receiver;
}
require(totalWeight <= TOTAL_SPLITS_WEIGHT, "Splits weights sum too high");
}
/// @notice Current user's splits hash, see `hashSplits`.
/// @param user The user
/// @return currSplitsHash The current user's splits hash
function splitsHash(address user) public view returns (bytes32 currSplitsHash) {
return _storage().splitsHash[user];
}
/// @notice Asserts that the list of splits receivers is the user's currently used one.
/// @param user The user
/// @param currReceivers The list of the user's current splits receivers.
function _assertCurrSplits(address user, SplitsReceiver[] memory currReceivers) internal view {
require(
hashSplits(currReceivers) == _storage().splitsHash[user],
"Invalid current splits receivers"
);
}
/// @notice Calculates the hash of the list of splits receivers.
/// @param receivers The list of the splits receivers.
/// Must be sorted by the splits receivers' addresses, deduplicated and without 0 weights.
/// @return receiversHash The hash of the list of splits receivers.
function hashSplits(SplitsReceiver[] memory receivers)
public
pure
returns (bytes32 receiversHash)
{
if (receivers.length == 0) return bytes32(0);
return keccak256(abi.encode(receivers));
}
/// @notice Called when funds need to be transferred between the user and the drips hub.
/// The function must be called no more than once per transaction.
/// @param user The user
/// @param amt The transferred amount.
/// Positive to transfer funds to the user, negative to transfer from them.
function _transfer(address user, int128 amt) internal virtual;
/// @notice Sets amt delta of a user on a given timestamp
/// @param user The user
/// @param timestamp The timestamp from which the delta takes effect
/// @param amtPerSecDelta Change of the per-second receiving rate
function _setDelta(
address user,
uint64 timestamp,
int128 amtPerSecDelta
) internal {
if (amtPerSecDelta == 0) return;
mapping(uint64 => AmtDelta) storage amtDeltas = _storage().receiverStates[user].amtDeltas;
// In order to set a delta on a specific timestamp it must be introduced in two cycles.
// The cycle delta is split proportionally based on how much this cycle is affected.
// The next cycle has the rest of the delta applied, so the update is fully completed.
uint64 thisCycle = timestamp / cycleSecs + 1;
uint64 nextCycleSecs = timestamp % cycleSecs;
uint64 thisCycleSecs = cycleSecs - nextCycleSecs;
amtDeltas[thisCycle].thisCycle += int128(uint128(thisCycleSecs)) * amtPerSecDelta;
amtDeltas[thisCycle].nextCycle += int128(uint128(nextCycleSecs)) * amtPerSecDelta;
}
function _userOrAccount(address user) internal pure returns (UserOrAccount memory) {
return UserOrAccount({isAccount: false, user: user, account: 0});
}
function _userOrAccount(address user, uint256 account)
internal
pure
returns (UserOrAccount memory)
{
return UserOrAccount({isAccount: true, user: user, account: account});
}
function _currTimestamp() internal view returns (uint64) {
return uint64(block.timestamp);
}
}
////// lib/radicle-drips-hub/src/ManagedDripsHub.sol
/* pragma solidity ^0.8.7; */
/* import {UUPSUpgradeable} from "openzeppelin-contracts/proxy/utils/UUPSUpgradeable.sol"; */
/* import {ERC1967Proxy} from "openzeppelin-contracts/proxy/ERC1967/ERC1967Proxy.sol"; */
/* import {ERC1967Upgrade} from "openzeppelin-contracts/proxy/ERC1967/ERC1967Upgrade.sol"; */
/* import {StorageSlot} from "openzeppelin-contracts/utils/StorageSlot.sol"; */
/* import {DripsHub, SplitsReceiver} from "./DripsHub.sol"; */
/// @notice The DripsHub which is UUPS-upgradable, pausable and has an admin.
/// It can't be used directly, only via a proxy.
///
/// ManagedDripsHub uses the ERC-1967 admin slot to store the admin address.
/// All instances of the contracts are owned by address `0x00`.
/// While this contract is capable of updating the admin,
/// the proxy is expected to set up the initial value of the ERC-1967 admin.
///
/// All instances of the contracts are paused and can't be unpaused.
/// When a proxy uses such contract via delegation, it's initially unpaused.
abstract contract ManagedDripsHub is DripsHub, UUPSUpgradeable {
/// @notice The ERC-1967 storage slot for the contract.
/// It holds a single boolean indicating if the contract is paused.
bytes32 private constant SLOT_PAUSED =
bytes32(uint256(keccak256("eip1967.managedDripsHub.paused")) - 1);
/// @notice Emitted when the pause is triggered.
/// @param account The account which triggered the change.
event Paused(address account);
/// @notice Emitted when the pause is lifted.
/// @param account The account which triggered the change.
event Unpaused(address account);
/// @notice Initializes the contract in paused state and with no admin.
/// The contract instance can be used only as a call delegation target for a proxy.
/// @param cycleSecs The length of cycleSecs to be used in the contract instance.
/// Low value makes funds more available by shortening the average time of funds being frozen
/// between being taken from the users' drips balances and being collectable by their receivers.
/// High value makes collecting cheaper by making it process less cycles for a given time range.
constructor(uint64 cycleSecs) DripsHub(cycleSecs) {
_pausedSlot().value = true;
}
/// @notice Collects all received funds available for the user
/// and transfers them out of the drips hub contract to that user's wallet.
/// @param user The user
/// @param currReceivers The list of the user's current splits receivers.
/// @return collected The collected amount
/// @return split The amount split to the user's splits receivers
function collect(address user, SplitsReceiver[] memory currReceivers)
public
override
whenNotPaused
returns (uint128 collected, uint128 split)
{
return super.collect(user, currReceivers);
}
/// @notice Flushes uncollected cycles of the user.
/// Flushed cycles won't need to be analyzed when the user collects from them.
/// Calling this function does not collect and does not affect the collectable amount.
///
/// This function is needed when collecting funds received over a period so long, that the gas
/// needed for analyzing all the uncollected cycles can't fit in a single transaction.
/// Calling this function allows spreading the analysis cost over multiple transactions.
/// A cycle is never flushed more than once, even if this function is called many times.
/// @param user The user
/// @param maxCycles The maximum number of flushed cycles.
/// If too low, flushing will be cheap, but will cut little gas from the next collection.
/// If too high, flushing may become too expensive to fit in a single transaction.
/// @return flushable The number of cycles which can be flushed
function flushCycles(address user, uint64 maxCycles)
public
override
whenNotPaused
returns (uint64 flushable)
{
return super.flushCycles(user, maxCycles);
}
/// @notice Authorizes the contract upgrade. See `UUPSUpgradable` docs for more details.
function _authorizeUpgrade(address newImplementation) internal view override onlyAdmin {
newImplementation;
}
/// @notice Returns the address of the current admin.
function admin() public view returns (address) {
return _getAdmin();
}
/// @notice Changes the admin of the contract.
/// Can only be called by the current admin.
function changeAdmin(address newAdmin) public onlyAdmin {
_changeAdmin(newAdmin);
}
/// @notice Throws if called by any account other than the admin.
modifier onlyAdmin() {
require(admin() == msg.sender, "Caller is not the admin");
_;
}
/// @notice Returns true if the contract is paused, and false otherwise.
function paused() public view returns (bool isPaused) {
return _pausedSlot().value;
}
/// @notice Triggers stopped state.
function pause() public whenNotPaused onlyAdmin {
_pausedSlot().value = true;
emit Paused(msg.sender);
}
/// @notice Returns to normal state.
function unpause() public whenPaused onlyAdmin {
_pausedSlot().value = false;
emit Unpaused(msg.sender);
}
/// @notice Modifier to make a function callable only when the contract is not paused.
modifier whenNotPaused() {
require(!paused(), "Contract paused");
_;
}
/// @notice Modifier to make a function callable only when the contract is paused.
modifier whenPaused() {
require(paused(), "Contract not paused");
_;
}
/// @notice Gets the storage slot holding the paused flag.
function _pausedSlot() private pure returns (StorageSlot.BooleanSlot storage) {
return StorageSlot.getBooleanSlot(SLOT_PAUSED);
}
}
/// @notice A generic ManagedDripsHub proxy.
contract ManagedDripsHubProxy is ERC1967Proxy {
constructor(ManagedDripsHub hubLogic, address admin)
ERC1967Proxy(address(hubLogic), new bytes(0))
{
_changeAdmin(admin);
}
}
////// lib/radicle-drips-hub/src/ERC20DripsHub.sol
/* pragma solidity ^0.8.7; */
/* import {SplitsReceiver, DripsReceiver} from "./DripsHub.sol"; */
/* import {ManagedDripsHub} from "./ManagedDripsHub.sol"; */
/* import {IERC20Reserve} from "./ERC20Reserve.sol"; */
/* import {IERC20} from "openzeppelin-contracts/token/ERC20/IERC20.sol"; */
/* import {StorageSlot} from "openzeppelin-contracts/utils/StorageSlot.sol"; */
/// @notice Drips hub contract for any ERC-20 token. Must be used via a proxy.
/// See the base `DripsHub` and `ManagedDripsHub` contract docs for more details.
contract ERC20DripsHub is ManagedDripsHub {
/// @notice The ERC-1967 storage slot for the contract.
/// It holds a single address of the ERC-20 reserve.
bytes32 private constant SLOT_RESERVE =
bytes32(uint256(keccak256("eip1967.erc20DripsHub.reserve")) - 1);
/// @notice The address of the ERC-20 contract which tokens the drips hub works with
IERC20 public immutable erc20;
/// @notice Emitted when the reserve address is set
event ReserveSet(IERC20Reserve oldReserve, IERC20Reserve newReserve);
/// @param cycleSecs The length of cycleSecs to be used in the contract instance.
/// Low value makes funds more available by shortening the average time of funds being frozen
/// between being taken from the users' drips balances and being collectable by their receivers.
/// High value makes collecting cheaper by making it process less cycles for a given time range.
/// @param _erc20 The address of an ERC-20 contract which tokens the drips hub will work with.
constructor(uint64 cycleSecs, IERC20 _erc20) ManagedDripsHub(cycleSecs) {
erc20 = _erc20;
}
/// @notice Sets the drips configuration of the `msg.sender`.
/// Transfers funds to or from the sender to fulfill the update of the drips balance.
/// The sender must first grant the contract a sufficient allowance.
/// @param lastUpdate The timestamp of the last drips update of the `msg.sender`.
/// If this is the first update, pass zero.
/// @param lastBalance The drips balance after the last drips update of the `msg.sender`.
/// If this is the first update, pass zero.
/// @param currReceivers The list of the drips receivers set in the last drips update
/// of the `msg.sender`.
/// If this is the first update, pass an empty array.
/// @param balanceDelta The drips balance change to be applied.
/// Positive to add funds to the drips balance, negative to remove them.
/// @param newReceivers The list of the drips receivers of the `msg.sender` to be set.
/// Must be sorted by the receivers' addresses, deduplicated and without 0 amtPerSecs.
/// @return newBalance The new drips balance of the `msg.sender`.
/// Pass it as `lastBalance` when updating that user or the account for the next time.
/// @return realBalanceDelta The actually applied drips balance change.
function setDrips(
uint64 lastUpdate,
uint128 lastBalance,
DripsReceiver[] memory currReceivers,
int128 balanceDelta,
DripsReceiver[] memory newReceivers
) public whenNotPaused returns (uint128 newBalance, int128 realBalanceDelta) {
return
_setDrips(
_userOrAccount(msg.sender),
lastUpdate,
lastBalance,
currReceivers,
balanceDelta,
newReceivers
);
}
/// @notice Sets the drips configuration of an account of the `msg.sender`.
/// See `setDrips` for more details
/// @param account The account
function setDrips(
uint256 account,
uint64 lastUpdate,
uint128 lastBalance,
DripsReceiver[] memory currReceivers,
int128 balanceDelta,
DripsReceiver[] memory newReceivers
) public whenNotPaused returns (uint128 newBalance, int128 realBalanceDelta) {
return
_setDrips(
_userOrAccount(msg.sender, account),
lastUpdate,
lastBalance,
currReceivers,
balanceDelta,
newReceivers
);
}
/// @notice Gives funds from the `msg.sender` to the receiver.
/// The receiver can collect them immediately.
/// Transfers the funds to be given from the sender's wallet to the drips hub contract.
/// @param receiver The receiver
/// @param amt The given amount
function give(address receiver, uint128 amt) public whenNotPaused {
_give(_userOrAccount(msg.sender), receiver, amt);
}
/// @notice Gives funds from the account of the `msg.sender` to the receiver.
/// The receiver can collect them immediately.
/// Transfers the funds to be given from the sender's wallet to the drips hub contract.
/// @param account The account
/// @param receiver The receiver
/// @param amt The given amount
function give(
uint256 account,
address receiver,
uint128 amt
) public whenNotPaused {
_give(_userOrAccount(msg.sender, account), receiver, amt);
}
/// @notice Collects funds received by the `msg.sender` and sets their splits.
/// The collected funds are split according to `currReceivers`.
/// @param currReceivers The list of the user's splits receivers which is currently in use.
/// If this function is called for the first time for the user, should be an empty array.
/// @param newReceivers The new list of the user's splits receivers.
/// Must be sorted by the splits receivers' addresses, deduplicated and without 0 weights.
/// Each splits receiver will be getting `weight / TOTAL_SPLITS_WEIGHT`
/// share of the funds collected by the user.
/// @return collected The collected amount
/// @return split The amount split to the user's splits receivers
function setSplits(SplitsReceiver[] memory currReceivers, SplitsReceiver[] memory newReceivers)
public
whenNotPaused
returns (uint128 collected, uint128 split)
{
return _setSplits(msg.sender, currReceivers, newReceivers);
}
/// @notice Gets the the reserve where funds are stored.
function reserve() public view returns (IERC20Reserve) {
return IERC20Reserve(_reserveSlot().value);
}
/// @notice Set the new reserve address to store funds.
/// @param newReserve The new reserve.
function setReserve(IERC20Reserve newReserve) public onlyAdmin {
require(newReserve.erc20() == erc20, "Invalid reserve ERC-20 address");
IERC20Reserve oldReserve = reserve();
if (address(oldReserve) != address(0)) erc20.approve(address(oldReserve), 0);
_reserveSlot().value = address(newReserve);
erc20.approve(address(newReserve), type(uint256).max);
emit ReserveSet(oldReserve, newReserve);
}
function _reserveSlot() private pure returns (StorageSlot.AddressSlot storage) {
return StorageSlot.getAddressSlot(SLOT_RESERVE);
}
function _transfer(address user, int128 amt) internal override {
IERC20Reserve erc20Reserve = reserve();
require(address(erc20Reserve) != address(0), "Reserve unset");
if (amt > 0) {
uint256 withdraw = uint128(amt);
erc20Reserve.withdraw(withdraw);
erc20.transfer(user, withdraw);
} else if (amt < 0) {
uint256 deposit = uint128(-amt);
erc20.transferFrom(user, address(this), deposit);
erc20Reserve.deposit(deposit);
}
}
}
////// lib/radicle-drips-hub/src/DaiDripsHub.sol
/* pragma solidity ^0.8.7; */
/* import {ERC20DripsHub, DripsReceiver, SplitsReceiver} from "./ERC20DripsHub.sol"; */
/* import {IDai} from "./Dai.sol"; */
/* import {IDaiReserve} from "./DaiReserve.sol"; */
struct PermitArgs {
uint256 nonce;
uint256 expiry;
uint8 v;
bytes32 r;
bytes32 s;
}
/// @notice Drips hub contract for DAI token. Must be used via a proxy.
/// See the base `DripsHub` contract docs for more details.
contract DaiDripsHub is ERC20DripsHub {
/// @notice The address of the Dai contract which tokens the drips hub works with.
/// Always equal to `erc20`, but more strictly typed.
IDai public immutable dai;
/// @notice See `ERC20DripsHub` constructor documentation for more details.
constructor(uint64 cycleSecs, IDai _dai) ERC20DripsHub(cycleSecs, _dai) {
dai = _dai;
}
/// @notice Sets the drips configuration of the `msg.sender`
/// and permits spending their Dai by the drips hub.
/// This function is an extension of `setDrips`, see its documentation for more details.
///
/// The user must sign a Dai permission document allowing the drips hub to spend their funds.
/// These parameters will be passed to the Dai contract by this function.
/// @param permitArgs The Dai permission arguments.
function setDripsAndPermit(
uint64 lastUpdate,
uint128 lastBalance,
DripsReceiver[] memory currReceivers,
int128 balanceDelta,
DripsReceiver[] memory newReceivers,
PermitArgs calldata permitArgs
) public whenNotPaused returns (uint128 newBalance, int128 realBalanceDelta) {
_permit(permitArgs);
return setDrips(lastUpdate, lastBalance, currReceivers, balanceDelta, newReceivers);
}
/// @notice Sets the drips configuration of an account of the `msg.sender`
/// and permits spending their Dai by the drips hub.
/// This function is an extension of `setDrips`, see its documentation for more details.
///
/// The user must sign a Dai permission document allowing the drips hub to spend their funds.
/// These parameters will be passed to the Dai contract by this function.
/// @param permitArgs The Dai permission arguments.
function setDripsAndPermit(
uint256 account,
uint64 lastUpdate,
uint128 lastBalance,
DripsReceiver[] memory currReceivers,
int128 balanceDelta,
DripsReceiver[] memory newReceivers,
PermitArgs calldata permitArgs
) public whenNotPaused returns (uint128 newBalance, int128 realBalanceDelta) {
_permit(permitArgs);
return
setDrips(account, lastUpdate, lastBalance, currReceivers, balanceDelta, newReceivers);
}
/// @notice Gives funds from the `msg.sender` to the receiver
/// and permits spending sender's Dai by the drips hub.
/// This function is an extension of `give`, see its documentation for more details.
///
/// The user must sign a Dai permission document allowing the drips hub to spend their funds.
/// These parameters will be passed to the Dai contract by this function.
/// @param permitArgs The Dai permission arguments.
function giveAndPermit(
address receiver,
uint128 amt,
PermitArgs calldata permitArgs
) public whenNotPaused {
_permit(permitArgs);
give(receiver, amt);
}
/// @notice Gives funds from the account of the `msg.sender` to the receiver
/// and permits spending sender's Dai by the drips hub.
/// This function is an extension of `give` see its documentation for more details.
///
/// The user must sign a Dai permission document allowing the drips hub to spend their funds.
/// These parameters will be passed to the Dai contract by this function.
/// @param permitArgs The Dai permission arguments.
function giveAndPermit(
uint256 account,
address receiver,
uint128 amt,
PermitArgs calldata permitArgs
) public whenNotPaused {
_permit(permitArgs);
give(account, receiver, amt);
}
/// @notice Permits the drips hub to spend the message sender's Dai.
/// @param permitArgs The Dai permission arguments.
function _permit(PermitArgs calldata permitArgs) internal {
dai.permit(
msg.sender,
address(this),
permitArgs.nonce,
permitArgs.expiry,
true,
permitArgs.v,
permitArgs.r,
permitArgs.s
);
}
}
////// src/builder/interface.sol
/* pragma solidity ^0.8.7; */
interface IBuilder {
function buildMetaData(
string memory projectName,
uint128 tokenId,
uint128 nftType,
bool streaming,
uint128 amtPerCycle,
bool active
) external view returns (string memory);
function buildMetaData(
string memory projectName,
uint128 tokenId,
uint128 nftType,
bool streaming,
uint128 amtPerCycle,
bool active,
string memory ipfsHash
) external view returns (string memory);
}
////// src/token.sol
/* pragma solidity ^0.8.7; */
/* import {ERC721} from "openzeppelin-contracts/token/ERC721/ERC721.sol"; */
/* import {IERC20} from "openzeppelin-contracts/token/ERC20/IERC20.sol"; */
/* import {Ownable} from "openzeppelin-contracts/access/Ownable.sol"; */
/* import {DaiDripsHub, DripsReceiver, IDai, SplitsReceiver} from "drips-hub/DaiDripsHub.sol"; */
/* import {IBuilder} from "./builder/interface.sol"; */
struct InputType {
uint128 nftTypeId;
uint64 limit;
// minimum amtPerSecond or minGiveAmt
uint128 minAmt;
bool streaming;
string ipfsHash;
}
interface IDripsToken {
function init(
string calldata name_,
string calldata symbol_,
address owner,
string calldata contractURI_,
InputType[] memory inputTypes,
IBuilder builder_,
SplitsReceiver[] memory splits
) external;
}
contract DripsToken is ERC721, Ownable, IDripsToken {
address public immutable deployer;
DaiDripsHub public immutable hub;
IDai public immutable dai;
uint64 public immutable cycleSecs;
IBuilder public builder;
string internal _name;
string internal _symbol;
string public contractURI;
bool public initialized;
struct Type {
uint64 limit;
uint64 minted;
uint128 minAmt;
bool streaming;
string ipfsHash;
}
struct Token {
uint64 timeMinted;
// amtPerSec if the Token is streaming otherwise the amt given at mint
uint128 amt;
uint128 lastBalance;
uint64 lastUpdate;
}
mapping(uint128 => Type) public nftTypes;
mapping(uint256 => Token) public nfts;
// events
event NewType(
uint128 indexed nftType,
uint64 limit,
uint128 minAmt,
bool streaming,
string ipfsHash
);
event NewStreamingToken(
uint256 indexed tokenId,
address indexed receiver,
uint128 indexed typeId,
uint128 topUp,
uint128 amtPerSec
);
event NewToken(
uint256 indexed tokenId,
address indexed receiver,
uint128 indexed typeId,
uint128 giveAmt
);
event NewContractURI(string contractURI);
event NewBuilder(IBuilder builder);
event SplitsUpdated(SplitsReceiver[] splits);
constructor(DaiDripsHub hub_, address deployer_) ERC721("", "") {
deployer = deployer_;
hub = hub_;
dai = hub_.dai();
cycleSecs = hub_.cycleSecs();
}
modifier onlyTokenHolder(uint256 tokenId) {
require(ownerOf(tokenId) == msg.sender, "not-nft-owner");
_;
}
function init(
string calldata name_,
string calldata symbol_,
address owner,
string calldata contractURI_,
InputType[] memory inputTypes,
IBuilder builder_,
SplitsReceiver[] memory splits
) public override {
require(!initialized, "already-initialized");
initialized = true;
require(msg.sender == deployer, "not-deployer");
require(owner != address(0), "owner-address-is-zero");
_name = name_;
_symbol = symbol_;
_changeBuilder(builder_);
_addTypes(inputTypes);
_changeContractURI(contractURI_);
_transferOwnership(owner);
if (splits.length > 0) {
_changeSplitsReceivers(new SplitsReceiver[](0), splits);
}
dai.approve(address(hub), type(uint256).max);
}
function changeContractURI(string calldata contractURI_) public onlyOwner {
_changeContractURI(contractURI_);
}
function _changeContractURI(string calldata contractURI_) internal {
contractURI = contractURI_;
emit NewContractURI(contractURI_);
}
function _changeBuilder(IBuilder newBuilder) internal {
builder = newBuilder;
emit NewBuilder(newBuilder);
}
function addTypes(InputType[] memory inputTypes) public onlyOwner {
_addTypes(inputTypes);
}
function _addTypes(InputType[] memory inputTypes) internal {
for (uint256 i = 0; i < inputTypes.length; i++) {
_addType(
inputTypes[i].nftTypeId,
inputTypes[i].limit,
inputTypes[i].minAmt,
inputTypes[i].ipfsHash,
inputTypes[i].streaming
);
}
}
function addStreamingType(
uint128 newTypeId,
uint64 limit,
uint128 minAmtPerSec,
string memory ipfsHash
) public onlyOwner {
_addType(newTypeId, limit, minAmtPerSec, ipfsHash, true);
}
function addType(
uint128 newTypeId,
uint64 limit,
uint128 minGiveAmt,
string memory ipfsHash
) public onlyOwner {
_addType(newTypeId, limit, minGiveAmt, ipfsHash, false);
}
function _addType(
uint128 newTypeId,
uint64 limit,
uint128 minAmt,
string memory ipfsHash,
bool streaming_
) internal {
require(nftTypes[newTypeId].limit == 0, "nft-type-already-exists");
require(limit > 0, "zero-limit-not-allowed");
nftTypes[newTypeId].minAmt = minAmt;
nftTypes[newTypeId].limit = limit;
nftTypes[newTypeId].ipfsHash = ipfsHash;
nftTypes[newTypeId].streaming = streaming_;
emit NewType(newTypeId, limit, minAmt, streaming_, ipfsHash);
}
function createTokenId(uint128 id, uint128 nftType) public pure returns (uint256 tokenId) {
return uint256((uint256(nftType) << 128)) | id;
}
function tokenType(uint256 tokenId) public pure returns (uint128 nftType) {
return uint128(tokenId >> 128);
}
function mintStreaming(
address nftReceiver,
uint128 typeId,
uint128 topUpAmt,
uint128 amtPerSec,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256) {
dai.permit(msg.sender, address(this), nonce, expiry, true, v, r, s);
return mintStreaming(nftReceiver, typeId, topUpAmt, amtPerSec);
}
function mint(
address nftReceiver,
uint128 typeId,
uint128 amtGive,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256) {
dai.permit(msg.sender, address(this), nonce, expiry, true, v, r, s);
return mint(nftReceiver, typeId, amtGive);
}
function mint(
address nftReceiver,
uint128 typeId,
uint128 giveAmt
) public returns (uint256 newTokenId) {
require(giveAmt >= nftTypes[typeId].minAmt, "giveAmt-too-low");
require(nftTypes[typeId].streaming == false, "type-is-streaming");
newTokenId = _mintInternal(nftReceiver, typeId, giveAmt);
// one time give instead of streaming
hub.give(newTokenId, address(this), giveAmt);
nfts[newTokenId].amt = giveAmt;
emit NewToken(newTokenId, nftReceiver, typeId, giveAmt);
}
function authMint(
address nftReceiver,
uint128 typeId,
uint128 value
) public onlyOwner returns (uint256 newTokenId) {
require(nftTypes[typeId].streaming == false, "type-is-streaming");
newTokenId = _mintInternal(nftReceiver, typeId, 0);
// amt is needed for influence
nfts[newTokenId].amt = value;
emit NewToken(newTokenId, nftReceiver, typeId, 0);
}
function _mintInternal(
address nftReceiver,
uint128 typeId,
uint128 topUpAmt
) internal returns (uint256 newTokenId) {
require(nftTypes[typeId].minted++ < nftTypes[typeId].limit, "nft-type-reached-limit");
newTokenId = createTokenId(nftTypes[typeId].minted, typeId);
_mint(nftReceiver, newTokenId);
nfts[newTokenId].timeMinted = uint64(block.timestamp);
// transfer currency to Token registry
if (topUpAmt > 0) dai.transferFrom(nftReceiver, address(this), topUpAmt);
}
function mintStreaming(
address nftReceiver,
uint128 typeId,
uint128 topUpAmt,
uint128 amtPerSec
) public returns (uint256 newTokenId) {
require(amtPerSec >= nftTypes[typeId].minAmt, "amt-per-sec-too-low");
require(nftTypes[typeId].streaming, "nft-type-not-streaming");
require(topUpAmt >= amtPerSec * cycleSecs, "toUp-too-low");
newTokenId = _mintInternal(nftReceiver, typeId, topUpAmt);
// start streaming
hub.setDrips(newTokenId, 0, 0, _receivers(0), int128(topUpAmt), _receivers(amtPerSec));
nfts[newTokenId].amt = amtPerSec;
nfts[newTokenId].lastUpdate = uint64(block.timestamp);
nfts[newTokenId].lastBalance = topUpAmt;
emit NewStreamingToken(newTokenId, nftReceiver, typeId, topUpAmt, amtPerSec);
}
function collect(SplitsReceiver[] calldata currSplits)
public
onlyOwner
returns (uint128 collected, uint128 split)
{
(, split) = hub.collect(address(this), currSplits);
collected = uint128(dai.balanceOf(address(this)));
dai.transfer(owner(), collected);
}
function collectable(SplitsReceiver[] calldata currSplits)
public
view
returns (uint128 toCollect, uint128 toSplit)
{
(toCollect, toSplit) = hub.collectable(address(this), currSplits);
toCollect += uint128(dai.balanceOf(address(this)));
}
function topUp(
uint256 tokenId,
uint128 topUpAmt,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) public {
dai.permit(msg.sender, address(this), nonce, expiry, true, v, r, s);
topUp(tokenId, topUpAmt);
}
function topUp(uint256 tokenId, uint128 topUpAmt) public onlyTokenHolder(tokenId) {
require(nftTypes[tokenType(tokenId)].streaming, "not-a-streaming-nft");
dai.transferFrom(msg.sender, address(this), topUpAmt);
DripsReceiver[] memory receivers = _tokenReceivers(tokenId);
(uint128 newBalance, ) = hub.setDrips(
tokenId,
nfts[tokenId].lastUpdate,
nfts[tokenId].lastBalance,
receivers,
int128(topUpAmt),
receivers
);
nfts[tokenId].lastUpdate = uint64(block.timestamp);
nfts[tokenId].lastBalance = newBalance;
}
function withdraw(uint256 tokenId, uint128 withdrawAmt)
public
onlyTokenHolder(tokenId)
returns (uint128 withdrawn)
{
uint128 withdrawableAmt = withdrawable(tokenId);
if (withdrawAmt > withdrawableAmt) {
withdrawAmt = withdrawableAmt;
}
DripsReceiver[] memory receivers = _tokenReceivers(tokenId);
(uint128 newBalance, int128 realBalanceDelta) = hub.setDrips(
tokenId,
nfts[tokenId].lastUpdate,
nfts[tokenId].lastBalance,
receivers,
-int128(withdrawAmt),
receivers
);
nfts[tokenId].lastUpdate = uint64(block.timestamp);
nfts[tokenId].lastBalance = newBalance;
withdrawn = uint128(-realBalanceDelta);
dai.transfer(msg.sender, withdrawn);
}
function changeSplitsReceivers(
SplitsReceiver[] memory currSplits,
SplitsReceiver[] memory newSplits
) public onlyOwner {
_changeSplitsReceivers(currSplits, newSplits);
}
function _changeSplitsReceivers(
SplitsReceiver[] memory currSplits,
SplitsReceiver[] memory newSplits
) internal {
hub.setSplits(currSplits, newSplits);
emit SplitsUpdated(newSplits);
}
function withdrawable(uint256 tokenId) public view returns (uint128) {
require(_exists(tokenId), "nonexistent-token");
if (nftTypes[tokenType(tokenId)].streaming == false) return 0;
Token storage nft = nfts[tokenId];
uint64 spentUntil = uint64(block.timestamp);
uint64 minSpentUntil = nft.timeMinted + cycleSecs;
if (spentUntil < minSpentUntil) spentUntil = minSpentUntil;
uint192 spent = (spentUntil - nft.lastUpdate) * uint192(nft.amt);
if (nft.lastBalance < spent) return nft.lastBalance % nft.amt;
return nft.lastBalance - uint128(spent);
}
function activeUntil(uint256 tokenId) public view returns (uint128) {
require(_exists(tokenId), "nonexistent-token");
Type storage nftType = nftTypes[tokenType(tokenId)];
if (nftType.streaming == false || nftType.minAmt == 0) {
return type(uint128).max;
}
Token storage nft = nfts[tokenId];
return nft.lastUpdate + nft.lastBalance / nft.amt - 1;
}
function active(uint256 tokenId) public view returns (bool) {
return activeUntil(tokenId) >= block.timestamp;
}
function streaming(uint256 tokenId) public view returns (bool) {
return nftTypes[tokenType(tokenId)].streaming;
}
function name() public view override returns (string memory) {
return _name;
}
function symbol() public view override returns (string memory) {
return _symbol;
}
function changeBuilder(IBuilder newBuilder) public onlyOwner {
_changeBuilder(newBuilder);
}
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "nonexistent-token");
string memory ipfsHash = nftTypes[tokenType(tokenId)].ipfsHash;
uint128 amtPerCycle = nfts[tokenId].amt * cycleSecs;
if (bytes(ipfsHash).length == 0) {
return
builder.buildMetaData(
name(),
uint128(tokenId),
tokenType(tokenId),
nftTypes[tokenType(tokenId)].streaming,
amtPerCycle,
active(tokenId)
);
}
return
builder.buildMetaData(
name(),
uint128(tokenId),
tokenType(tokenId),
nftTypes[tokenType(tokenId)].streaming,
amtPerCycle,
active(tokenId),
ipfsHash
);
}
function currLeftSecsInCycle() public view returns (uint64) {
return cycleSecs - (uint64(block.timestamp) % cycleSecs);
}
function influence(uint256 tokenId) public view returns (uint256 influenceScore) {
if (active(tokenId)) {
if (streaming(tokenId) == false) {
return nfts[tokenId].amt;
}
return nfts[tokenId].amt * (block.timestamp - nfts[tokenId].timeMinted);
}
return 0;
}
function _tokenReceivers(uint256 tokenId)
internal
view
returns (DripsReceiver[] memory receivers)
{
return _receivers(nfts[tokenId].amt);
}
function _receivers(uint128 amtPerSec)
internal
view
returns (DripsReceiver[] memory receivers)
{
if (amtPerSec == 0) return new DripsReceiver[](0);
receivers = new DripsReceiver[](1);
receivers[0] = DripsReceiver(address(this), amtPerSec);
}
}
| Permits the drips hub to spend the message sender's Dai. permitArgs The Dai permission arguments. | function _permit(PermitArgs calldata permitArgs) internal {
dai.permit(
msg.sender,
address(this),
permitArgs.nonce,
permitArgs.expiry,
true,
permitArgs.v,
permitArgs.r,
permitArgs.s
);
}
| 13,437,463 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/proxy/Clones.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "./ERC20.sol";
import "../wallet/ShardedWallet.sol";
import "../governance/IGovernance.sol";
import "../interface/IERC1363Receiver.sol";
import "../interface/IERC1363Spender.sol";
contract LiquidityToken is ERC20 {
address public controler;
modifier onlyControler() {
require(msg.sender == controler);
_;
}
constructor() {
controler = address(0xdead);
}
function initialize(address controler_, string memory name_, string memory symbol_) public {
require(controler == address(0));
controler = controler_;
_initialize(name_, symbol_);
}
function controllerTransfer(address sender, address recipient, uint256 amount) public onlyControler {
_transfer(sender, recipient, amount);
}
function controllerMint(address account, uint256 amount) public onlyControler {
_mint(account, amount);
}
function controllerBurn(address account, uint256 amount) public onlyControler {
_burn(account, amount);
}
}
contract BondingCurve4 is IERC1363Spender {
struct CurveCoordinates {
uint256 x;
uint256 k;
}
struct Asset {
uint256 underlyingSupply;
uint256 feeToNiftex;
uint256 feeToArtist;
}
LiquidityToken immutable internal _template;
// bytes32 public constant PCT_FEE_SUPPLIERS = bytes32(uint256(keccak256("PCT_FEE_SUPPLIERS")) - 1);
bytes32 public constant PCT_FEE_SUPPLIERS = 0xe4f5729eb40e38b5a39dfb36d76ead9f9bc286f06852595980c5078f1af7e8c9;
// bytes32 public constant PCT_FEE_ARTIST = bytes32(uint256(keccak256("PCT_FEE_ARTIST")) - 1);
bytes32 public constant PCT_FEE_ARTIST = 0xdd0618e2e2a17ff193a933618181c8f8909dc169e9707cce1921893a88739ca0;
// bytes32 public constant PCT_FEE_NIFTEX = bytes32(uint256(keccak256("PCT_FEE_NIFTEX")) - 1);
bytes32 public constant PCT_FEE_NIFTEX = 0xcfb1dd89e6f4506eca597e7558fbcfe22dbc7e0b9f2b3956e121d0e344d6f7aa;
// bytes32 public constant LIQUIDITY_TIMELOCK = bytes32(uint256(keccak256("LIQUIDITY_TIMELOCK")) - 1);
bytes32 public constant LIQUIDITY_TIMELOCK = 0x4babff57ebd34f251a515a845400ed950a51f0a64c92e803a3e144fc40623fa8;
LiquidityToken public etherLPToken;
LiquidityToken public shardLPToken;
CurveCoordinates public curve;
Asset internal _etherLPExtra;
Asset internal _shardLPExtra;
address public wallet;
address public recipient;
uint256 public deadline;
uint256 public recordedTotalSupply;
event Initialized(address wallet);
event ShardsBought(address indexed account, uint256 amount, uint256 cost);
event ShardsSold(address indexed account, uint256 amount, uint256 payout);
event ShardsSupplied(address indexed provider, uint256 amount);
event EtherSupplied(address indexed provider, uint256 amount);
event ShardsWithdrawn(address indexed provider, uint256 payout, uint256 shards, uint256 amountLPToken);
event EtherWithdrawn(address indexed provider, uint256 value, uint256 payout, uint256 amountLPToken);
constructor() {
_template = new LiquidityToken();
wallet = address(0xdead);
}
function initialize(
uint256 supply,
address wallet_,
address recipient_,
uint256 price
)
public payable
{
require(wallet == address(0));
recordedTotalSupply = ShardedWallet(payable(wallet_)).totalSupply();
string memory name_ = ShardedWallet(payable(wallet_)).name();
string memory symbol_ = ShardedWallet(payable(wallet_)).symbol();
etherLPToken = LiquidityToken(Clones.clone(address(_template)));
shardLPToken = LiquidityToken(Clones.clone(address(_template)));
etherLPToken.initialize(address(this), string(abi.encodePacked(name_, "-EtherLP")), string(abi.encodePacked(symbol_, "-ELP")));
shardLPToken.initialize(address(this), string(abi.encodePacked(name_, "-ShardLP")), string(abi.encodePacked(symbol_, "-SLP")));
wallet = wallet_;
recipient = recipient_;
deadline = block.timestamp + ShardedWallet(payable(wallet_)).governance().getConfig(wallet_, LIQUIDITY_TIMELOCK);
emit Initialized(wallet_);
// transfer assets
if (supply > 0) {
require(ShardedWallet(payable(wallet_)).transferFrom(msg.sender, address(this), supply));
}
{
// setup curve
uint256 decimals_ = ShardedWallet(payable(wallet_)).decimals();
curve.x = recordedTotalSupply * 4 / 10;
curve.k = recordedTotalSupply * recordedTotalSupply * price / 10**decimals_ * 16 / 100;
}
// mint liquidity
etherLPToken.controllerMint(address(this), msg.value);
shardLPToken.controllerMint(address(this), supply);
_etherLPExtra.underlyingSupply = msg.value;
_shardLPExtra.underlyingSupply = supply;
emit EtherSupplied(address(this), msg.value);
emit ShardsSupplied(address(this), supply);
}
function buyShards(uint256 amount, uint256 maxCost) public payable {
uint256 cost = _buyShards(msg.sender, amount, maxCost);
require(cost <= msg.value);
if (msg.value > cost) {
Address.sendValue(payable(msg.sender), msg.value - cost);
}
}
function sellShards(uint256 amount, uint256 minPayout) public {
require(ShardedWallet(payable(wallet)).transferFrom(msg.sender, address(this), amount));
_sellShards(msg.sender, amount, minPayout);
}
function supplyEther() public payable {
_supplyEther(msg.sender, msg.value);
}
function supplyShards(uint256 amount) public {
require(ShardedWallet(payable(wallet)).transferFrom(msg.sender, address(this), amount));
_supplyShards(msg.sender, amount);
}
function onApprovalReceived(address owner, uint256 amount, bytes calldata data) public override returns (bytes4) {
require(msg.sender == wallet);
require(ShardedWallet(payable(wallet)).transferFrom(owner, address(this), amount));
bytes4 selector = abi.decode(data, (bytes4));
if (selector == this.sellShards.selector) {
(,uint256 minPayout) = abi.decode(data, (bytes4, uint256));
_sellShards(owner, amount, minPayout);
} else if (selector == this.supplyShards.selector) {
_supplyShards(owner, amount);
} else {
revert("invalid selector in onApprovalReceived data");
}
return this.onApprovalReceived.selector;
}
function _buyShards(address buyer, uint256 amount, uint256 maxCost) internal returns (uint256) {
IGovernance governance = ShardedWallet(payable(wallet)).governance();
address owner = ShardedWallet(payable(wallet)).owner();
address artist = ShardedWallet(payable(wallet)).artistWallet();
// pause if someone else reclaimed the ownership of shardedWallet
require(owner == address(0) || governance.isModule(wallet, owner));
// compute fees
uint256[3] memory fees;
fees[0] = governance.getConfig(wallet, PCT_FEE_SUPPLIERS);
fees[1] = governance.getConfig(wallet, PCT_FEE_NIFTEX);
fees[2] = artist == address(0) ? 0 : governance.getConfig(wallet, PCT_FEE_ARTIST);
uint256 amountWithFee = amount * (10**18 + fees[0] + fees[1] + fees[2]) / 10**18;
// check curve update
uint256 newX = curve.x - amountWithFee;
uint256 newY = curve.k / newX;
require(newX > 0 && newY > 0);
// check cost
uint256 cost = newY - curve.k / curve.x;
require(cost <= maxCost);
// consistency check
require(ShardedWallet(payable(wallet)).balanceOf(address(this)) - _shardLPExtra.feeToNiftex - _shardLPExtra.feeToArtist >= amount * (10**18 + fees[1] + fees[2]) / 10**18);
// update curve
curve.x = curve.x - amount * (10**18 + fees[1] + fees[2]) / 10**18;
// update LP supply
_shardLPExtra.underlyingSupply += amount * fees[0] / 10**18;
_shardLPExtra.feeToNiftex += amount * fees[1] / 10**18;
_shardLPExtra.feeToArtist += amount * fees[2] / 10**18;
// transfer
ShardedWallet(payable(wallet)).transfer(buyer, amount);
emit ShardsBought(buyer, amount, cost);
return cost;
}
function _sellShards(address seller, uint256 amount, uint256 minPayout) internal returns (uint256) {
IGovernance governance = ShardedWallet(payable(wallet)).governance();
address owner = ShardedWallet(payable(wallet)).owner();
address artist = ShardedWallet(payable(wallet)).artistWallet();
// pause if someone else reclaimed the ownership of shardedWallet
require(owner == address(0) || governance.isModule(wallet, owner));
// compute fees
uint256[3] memory fees;
fees[0] = governance.getConfig(wallet, PCT_FEE_SUPPLIERS);
fees[1] = governance.getConfig(wallet, PCT_FEE_NIFTEX);
fees[2] = artist == address(0) ? 0 : governance.getConfig(wallet, PCT_FEE_ARTIST);
uint256 newX = curve.x + amount;
uint256 newY = curve.k / newX;
require(newX > 0 && newY > 0);
// check payout
uint256 payout = curve.k / curve.x - newY;
require(payout <= address(this).balance - _etherLPExtra.feeToNiftex - _etherLPExtra.feeToArtist);
uint256 value = payout * (10**18 - fees[0] - fees[1] - fees[2]) / 10**18;
require(value >= minPayout);
// update curve
curve.x = newX;
// update LP supply
_etherLPExtra.underlyingSupply += payout * fees[0] / 10**18;
_etherLPExtra.feeToNiftex += payout * fees[1] / 10**18;
_etherLPExtra.feeToArtist += payout * fees[2] / 10**18;
// transfer
Address.sendValue(payable(seller), value);
emit ShardsSold(seller, amount, value);
return value;
}
function _supplyEther(address supplier, uint256 amount) internal {
etherLPToken.controllerMint(supplier, calcNewEthLPTokensToIssue(amount));
_etherLPExtra.underlyingSupply += amount;
emit EtherSupplied(supplier, amount);
}
function _supplyShards(address supplier, uint256 amount) internal {
shardLPToken.controllerMint(supplier, calcNewShardLPTokensToIssue(amount));
_shardLPExtra.underlyingSupply += amount;
emit ShardsSupplied(supplier, amount);
}
function calcNewShardLPTokensToIssue(uint256 amount) public view returns (uint256) {
uint256 pool = _shardLPExtra.underlyingSupply;
if (pool == 0) { return amount; }
uint256 proportion = amount * 10**18 / (pool + amount);
return proportion * shardLPToken.totalSupply() / (10**18 - proportion);
}
function calcNewEthLPTokensToIssue(uint256 amount) public view returns (uint256) {
uint256 pool = _etherLPExtra.underlyingSupply;
if (pool == 0) { return amount; }
uint256 proportion = amount * 10**18 / (pool + amount);
return proportion * etherLPToken.totalSupply() / (10**18 - proportion);
}
function calcShardsForEthSuppliers() public view returns (uint256) {
uint256 balance = ShardedWallet(payable(wallet)).balanceOf(address(this)) - _shardLPExtra.feeToNiftex - _shardLPExtra.feeToArtist;
return balance < _shardLPExtra.underlyingSupply ? 0 : balance - _shardLPExtra.underlyingSupply;
}
function calcEthForShardSuppliers() public view returns (uint256) {
uint256 balance = address(this).balance - _etherLPExtra.feeToNiftex - _etherLPExtra.feeToArtist;
return balance < _etherLPExtra.underlyingSupply ? 0 : balance - _etherLPExtra.underlyingSupply;
}
function withdrawSuppliedEther(uint256 amount) external returns (uint256, uint256) {
require(amount > 0);
uint256 etherLPTokenSupply = etherLPToken.totalSupply();
uint256 balance = address(this).balance - _etherLPExtra.feeToNiftex - _etherLPExtra.feeToArtist;
uint256 value = (balance <= _etherLPExtra.underlyingSupply)
? balance * amount / etherLPTokenSupply
: _etherLPExtra.underlyingSupply * amount / etherLPTokenSupply;
uint256 payout = calcShardsForEthSuppliers() * amount / etherLPTokenSupply;
// update balances
_etherLPExtra.underlyingSupply *= etherLPTokenSupply - amount;
_etherLPExtra.underlyingSupply /= etherLPTokenSupply;
etherLPToken.controllerBurn(msg.sender, amount);
// transfer
Address.sendValue(payable(msg.sender), value);
if (payout > 0) {
ShardedWallet(payable(wallet)).transfer(msg.sender, payout);
}
emit EtherWithdrawn(msg.sender, value, payout, amount);
return (value, payout);
}
function withdrawSuppliedShards(uint256 amount) external returns (uint256, uint256) {
require(amount > 0);
uint256 shardLPTokenSupply = shardLPToken.totalSupply();
uint256 balance = ShardedWallet(payable(wallet)).balanceOf(address(this)) - _shardLPExtra.feeToNiftex - _shardLPExtra.feeToArtist;
uint256 shards = (balance <= _shardLPExtra.underlyingSupply)
? balance * amount / shardLPTokenSupply
: _shardLPExtra.underlyingSupply * amount / shardLPTokenSupply;
uint256 payout = calcEthForShardSuppliers() * amount / shardLPTokenSupply;
// update balances
_shardLPExtra.underlyingSupply *= shardLPTokenSupply - amount;
_shardLPExtra.underlyingSupply /= shardLPTokenSupply;
shardLPToken.controllerBurn(msg.sender, amount);
// transfer
ShardedWallet(payable(wallet)).transfer(msg.sender, shards);
if (payout > 0) {
Address.sendValue(payable(msg.sender), payout);
}
emit ShardsWithdrawn(msg.sender, payout, shards, amount);
return (payout, shards);
}
function withdrawNiftexOrArtistFees(address to) public {
uint256 etherFees = 0;
uint256 shardFees = 0;
if (msg.sender == ShardedWallet(payable(wallet)).artistWallet()) {
etherFees += _etherLPExtra.feeToArtist;
shardFees += _shardLPExtra.feeToArtist;
delete _etherLPExtra.feeToArtist;
delete _shardLPExtra.feeToArtist;
}
if (msg.sender == ShardedWallet(payable(wallet)).governance().getNiftexWallet()) {
etherFees += _etherLPExtra.feeToNiftex;
shardFees += _shardLPExtra.feeToNiftex;
delete _etherLPExtra.feeToNiftex;
delete _shardLPExtra.feeToNiftex;
}
Address.sendValue(payable(to), etherFees);
ShardedWallet(payable(wallet)).transfer(to, shardFees);
}
function rebaseWhenTotalSupplyChange() public {
uint256 newTotalSupply_ = ShardedWallet(payable(wallet)).totalSupply();
require (newTotalSupply_ != recordedTotalSupply);
curve.k = curve.k * newTotalSupply_ / recordedTotalSupply * newTotalSupply_ / recordedTotalSupply; // new k = (new supply/old supply)^2 * old k, intentionally * / * / to avoid uint overflow;
curve.x = curve.x * newTotalSupply_ / recordedTotalSupply; // new x = (new supply/old supply) * old x
recordedTotalSupply = newTotalSupply_;
assert(curve.k > 0);
assert(curve.x > 0);
assert(recordedTotalSupply > 0);
}
function transferTimelockLiquidity() public {
require(deadline < block.timestamp);
etherLPToken.controllerTransfer(address(this), recipient, getEthLPTokens(address(this)));
shardLPToken.controllerTransfer(address(this), recipient, getShardLPTokens(address(this)));
}
function getEthLPTokens(address owner) public view returns (uint256) {
return etherLPToken.balanceOf(owner);
}
function getShardLPTokens(address owner) public view returns (uint256) {
return shardLPToken.balanceOf(owner);
}
function transferEthLPTokens(address to, uint256 amount) public {
etherLPToken.controllerTransfer(msg.sender, to, amount);
}
function transferShardLPTokens(address to, uint256 amount) public {
shardLPToken.controllerTransfer(msg.sender, to, amount);
}
function getCurrentPrice() external view returns (uint256) {
return curve.k * 10**18 / curve.x / curve.x;
}
function getEthSuppliers() external view returns (uint256, uint256, uint256, uint256) {
return (_etherLPExtra.underlyingSupply, etherLPToken.totalSupply(), _etherLPExtra.feeToNiftex, _etherLPExtra.feeToArtist);
}
function getShardSuppliers() external view returns (uint256, uint256, uint256, uint256) {
return (_shardLPExtra.underlyingSupply, shardLPToken.totalSupply(), _shardLPExtra.feeToNiftex, _shardLPExtra.feeToArtist);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev https://eips.ethereum.org/EIPS/eip-1167[EIP 1167] is a standard for
* deploying minimal proxy contracts, also known as "clones".
*
* > To simply and cheaply clone contract functionality in an immutable way, this standard specifies
* > a minimal bytecode implementation that delegates all calls to a known, fixed address.
*
* The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2`
* (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the
* deterministic method.
*
* _Available since v3.4._
*/
library Clones {
/**
* @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.
*
* This function uses the create opcode, which should never revert.
*/
function clone(address implementation) internal returns (address instance) {
// solhint-disable-next-line no-inline-assembly
assembly {
let ptr := mload(0x40)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(ptr, 0x14), shl(0x60, implementation))
mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
instance := create(0, ptr, 0x37)
}
require(instance != address(0), "ERC1167: create failed");
}
/**
* @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.
*
* This function uses the create2 opcode and a `salt` to deterministically deploy
* the clone. Using the same `implementation` and `salt` multiple time will revert, since
* the clones cannot be deployed twice at the same address.
*/
function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance) {
// solhint-disable-next-line no-inline-assembly
assembly {
let ptr := mload(0x40)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(ptr, 0x14), shl(0x60, implementation))
mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
instance := create2(0, ptr, 0x37, salt)
}
require(instance != address(0), "ERC1167: create2 failed");
}
/**
* @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
*/
function predictDeterministicAddress(address implementation, bytes32 salt, address deployer) internal pure returns (address predicted) {
// solhint-disable-next-line no-inline-assembly
assembly {
let ptr := mload(0x40)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(ptr, 0x14), shl(0x60, implementation))
mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf3ff00000000000000000000000000000000)
mstore(add(ptr, 0x38), shl(0x60, deployer))
mstore(add(ptr, 0x4c), salt)
mstore(add(ptr, 0x6c), keccak256(ptr, 0x37))
predicted := keccak256(add(ptr, 0x37), 0x55)
}
}
/**
* @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
*/
function predictDeterministicAddress(address implementation, bytes32 salt) internal view returns (address predicted) {
return predictDeterministicAddress(implementation, salt, address(this));
}
}
// 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;
import "@openzeppelin/contracts/utils/Context.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.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 {
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
function _initialize(string memory name_, string memory symbol_) internal virtual {
_name = name_;
_symbol = symbol_;
}
/**
* @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 this function is
* overloaded;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
_approve(sender, _msgSender(), currentAllowance - amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
return true;
}
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public virtual {
_burn(_msgSender(), amount);
}
/**
* @dev Destroys `amount` tokens from `account`, deducting from the caller's
* allowance.
*
* See {ERC20-_burn} and {ERC20-allowance}.
*
* Requirements:
*
* - the caller must have allowance for ``accounts``'s tokens of at least
* `amount`.
*/
function burnFrom(address account, uint256 amount) public virtual {
uint256 currentAllowance = allowance(account, _msgSender());
require(currentAllowance >= amount, "ERC20: burn amount exceeds allowance");
_approve(account, _msgSender(), currentAllowance - amount);
_burn(account, amount);
}
/**
* @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;
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/math/Math.sol";
import "../governance/IGovernance.sol";
import "../initializable/Ownable.sol";
import "../initializable/ERC20.sol";
import "../initializable/ERC1363.sol";
contract ShardedWallet is Ownable, ERC20, ERC1363Approve
{
// bytes32 public constant ALLOW_GOVERNANCE_UPGRADE = bytes32(uint256(keccak256("ALLOW_GOVERNANCE_UPGRADE")) - 1);
bytes32 public constant ALLOW_GOVERNANCE_UPGRADE = 0xedde61aea0459bc05d70dd3441790ccfb6c17980a380201b00eca6f9ef50452a;
IGovernance public governance;
address public artistWallet;
event Received(address indexed sender, uint256 value, bytes data);
event Execute(address indexed to, uint256 value, bytes data);
event ModuleExecute(address indexed module, address indexed to, uint256 value, bytes data);
event GovernanceUpdated(address indexed oldGovernance, address indexed newGovernance);
event ArtistUpdated(address indexed oldArtist, address indexed newArtist);
modifier onlyModule()
{
require(_isModule(msg.sender), "Access restricted to modules");
_;
}
/*************************************************************************
* Contructor and fallbacks *
*************************************************************************/
constructor()
{
governance = IGovernance(address(0xdead));
}
receive()
external payable
{
emit Received(msg.sender, msg.value, bytes(""));
}
fallback()
external payable
{
address module = governance.getModule(address(this), msg.sig);
if (module != address(0) && _isModule(module))
{
(bool success, /*bytes memory returndata*/) = module.staticcall(msg.data);
// returning bytes in fallback is not supported until solidity 0.8.0
// solhint-disable-next-line no-inline-assembly
assembly {
returndatacopy(0, 0, returndatasize())
switch success
case 0 { revert(0, returndatasize()) }
default { return (0, returndatasize()) }
}
}
else
{
emit Received(msg.sender, msg.value, msg.data);
}
}
/*************************************************************************
* Initialization *
*************************************************************************/
function initialize(
address governance_,
address minter_,
string calldata name_,
string calldata symbol_,
address artistWallet_
)
external
{
require(address(governance) == address(0));
governance = IGovernance(governance_);
Ownable._setOwner(minter_);
ERC20._initialize(name_, symbol_);
artistWallet = artistWallet_;
emit GovernanceUpdated(address(0), governance_);
}
function _isModule(address module)
internal view returns (bool)
{
return governance.isModule(address(this), module);
}
/*************************************************************************
* Owner interactions *
*************************************************************************/
function execute(address to, uint256 value, bytes calldata data)
external onlyOwner()
{
Address.functionCallWithValue(to, data, value);
emit Execute(to, value, data);
}
function retrieve(address newOwner)
external
{
ERC20._burn(msg.sender, Math.max(ERC20.totalSupply(), 1));
Ownable._setOwner(newOwner);
}
/*************************************************************************
* Module interactions *
*************************************************************************/
function moduleExecute(address to, uint256 value, bytes calldata data)
external onlyModule()
{
if (Address.isContract(to))
{
Address.functionCallWithValue(to, data, value);
}
else
{
Address.sendValue(payable(to), value);
}
emit ModuleExecute(msg.sender, to, value, data);
}
function moduleMint(address to, uint256 value)
external onlyModule()
{
ERC20._mint(to, value);
}
function moduleBurn(address from, uint256 value)
external onlyModule()
{
ERC20._burn(from, value);
}
function moduleTransfer(address from, address to, uint256 value)
external onlyModule()
{
ERC20._transfer(from, to, value);
}
function moduleTransferOwnership(address to)
external onlyModule()
{
Ownable._setOwner(to);
}
function updateGovernance(address newGovernance)
external onlyModule()
{
emit GovernanceUpdated(address(governance), newGovernance);
require(governance.getConfig(address(this), ALLOW_GOVERNANCE_UPGRADE) > 0);
require(Address.isContract(newGovernance));
governance = IGovernance(newGovernance);
}
function updateArtistWallet(address newArtistWallet)
external onlyModule()
{
emit ArtistUpdated(artistWallet, newArtistWallet);
artistWallet = newArtistWallet;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IGovernance
{
function isModule(address, address) external view returns (bool);
function isAuthorized(address, address) external view returns (bool);
function getModule(address, bytes4) external view returns (address);
function getConfig(address, bytes32) external view returns (uint256);
function getNiftexWallet() external view returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC1363Receiver interface
* @dev Interface for any contract that wants to support `transferAndCall` or `transferFromAndCall`
* from ERC1363 token contracts.
*/
interface IERC1363Receiver {
/*
* Note: the ERC-165 identifier for this interface is 0x88a7ca5c.
* 0x88a7ca5c === bytes4(keccak256("onTransferReceived(address,address,uint256,bytes)"))
*/
/**
* @notice Handle the receipt of ERC1363 tokens
* @dev Any ERC1363 smart contract calls this function on the recipient
* after a `transfer` or a `transferFrom`. This function MAY throw to revert and reject the
* transfer. Return of other than the magic value MUST result in the
* transaction being reverted.
* Note: the token contract address is always the message sender.
* @param operator address The address which called `transferAndCall` or `transferFromAndCall` function
* @param from address The address which are token transferred from
* @param value uint256 The amount of tokens transferred
* @param data bytes Additional data with no specified format
* @return `bytes4(keccak256("onTransferReceived(address,address,uint256,bytes)"))`
* unless throwing
*/
function onTransferReceived(address operator, address from, uint256 value, bytes calldata data) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC1363Spender interface
* @dev Interface for any contract that wants to support `approveAndCall`
* from ERC1363 token contracts.
*/
interface IERC1363Spender {
/*
* Note: the ERC-165 identifier for this interface is 0.8.04a2d0.
* 0.8.04a2d0 === bytes4(keccak256("onApprovalReceived(address,uint256,bytes)"))
*/
/**
* @notice Handle the approval of ERC1363 tokens
* @dev Any ERC1363 smart contract calls this function on the recipient
* after an `approve`. This function MAY throw to revert and reject the
* approval. Return of other than the magic value MUST result in the
* transaction being reverted.
* Note: the token contract address is always the message sender.
* @param owner address The address which called `approveAndCall` function
* @param value uint256 The amount of tokens to be spent
* @param data bytes Additional data with no specified format
* @return `bytes4(keccak256("onApprovalReceived(address,uint256,bytes)"))`
* unless throwing
*/
function onApprovalReceived(address owner, uint256 value, bytes calldata data) external returns (bytes4);
}
// 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 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 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.8.0;
import "@openzeppelin/contracts/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.
*/
function _setOwner(address owner_) internal {
emit OwnershipTransferred(_owner, owner_);
_owner = owner_;
}
/**
* @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 {
_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);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./ERC20.sol";
import "../interface/IERC1363.sol";
import "../interface/IERC1363Receiver.sol";
import "../interface/IERC1363Spender.sol";
abstract contract ERC1363Transfer is ERC20, IERC1363Transfer {
function transferAndCall(address to, uint256 value) public override returns (bool) {
return transferAndCall(to, value, bytes(""));
}
function transferAndCall(address to, uint256 value, bytes memory data) public override returns (bool) {
require(transfer(to, value));
try IERC1363Receiver(to).onTransferReceived(_msgSender(), _msgSender(), value, data) returns (bytes4 selector) {
require(selector == IERC1363Receiver(to).onTransferReceived.selector, "ERC1363: onTransferReceived invalid result");
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1363: onTransferReceived reverted without reason");
}
return true;
}
function transferFromAndCall(address from, address to, uint256 value) public override returns (bool) {
return transferFromAndCall(from, to, value, bytes(""));
}
function transferFromAndCall(address from, address to, uint256 value, bytes memory data) public override returns (bool) {
require(transferFrom(from, to, value));
try IERC1363Receiver(to).onTransferReceived(_msgSender(), from, value, data) returns (bytes4 selector) {
require(selector == IERC1363Receiver(to).onTransferReceived.selector, "ERC1363: onTransferReceived invalid result");
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1363: onTransferReceived reverted without reason");
}
return true;
}
}
abstract contract ERC1363Approve is ERC20, IERC1363Approve {
function approveAndCall(address spender, uint256 value) public override returns (bool) {
return approveAndCall(spender, value, bytes(""));
}
function approveAndCall(address spender, uint256 value, bytes memory data) public override returns (bool) {
require(approve(spender, value));
try IERC1363Spender(spender).onApprovalReceived(_msgSender(), value, data) returns (bytes4 selector) {
require(selector == IERC1363Spender(spender).onApprovalReceived.selector, "ERC1363: onApprovalReceived invalid result");
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1363: onApprovalReceived reverted without reason");
}
return true;
}
}
abstract contract ERC1363 is ERC1363Transfer, ERC1363Approve {}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IERC1363Transfer {
/*
* Note: the ERC-165 identifier for this interface is 0x4bbee2df.
* 0x4bbee2df ===
* bytes4(keccak256('transferAndCall(address,uint256)')) ^
* bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)'))
*/
/**
* @notice Transfer tokens from `msg.sender` to another address and then call `onTransferReceived` on receiver
* @param to address The address which you want to transfer to
* @param value uint256 The amount of tokens to be transferred
* @return true unless throwing
*/
function transferAndCall(address to, uint256 value) external returns (bool);
/**
* @notice Transfer tokens from `msg.sender` to another address and then call `onTransferReceived` on receiver
* @param to address The address which you want to transfer to
* @param value uint256 The amount of tokens to be transferred
* @param data bytes Additional data with no specified format, sent in call to `to`
* @return true unless throwing
*/
function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @notice Transfer tokens from one address to another and then call `onTransferReceived` on receiver
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 The amount of tokens to be transferred
* @return true unless throwing
*/
function transferFromAndCall(address from, address to, uint256 value) external returns (bool);
/**
* @notice Transfer tokens from one address to another and then call `onTransferReceived` on receiver
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 The amount of tokens to be transferred
* @param data bytes Additional data with no specified format, sent in call to `to`
* @return true unless throwing
*/
function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);
}
interface IERC1363Approve {
/*
* Note: the ERC-165 identifier for this interface is 0xfb9ec8ce.
* 0xfb9ec8ce ===
* bytes4(keccak256('approveAndCall(address,uint256)')) ^
* bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
*/
/**
* @notice Approve the passed address to spend the specified amount of tokens on behalf of msg.sender
* and then call `onApprovalReceived` on spender.
* @param spender address The address which will spend the funds
* @param value uint256 The amount of tokens to be spent
*/
function approveAndCall(address spender, uint256 value) external returns (bool);
/**
* @notice Approve the passed address to spend the specified amount of tokens on behalf of msg.sender
* and then call `onApprovalReceived` on spender.
* @param spender address The address which will spend the funds
* @param value uint256 The amount of tokens to be spent
* @param data bytes Additional data with no specified format, sent in call to `spender`
*/
function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}
interface IERC1363 is IERC1363Transfer, IERC1363Approve {
}
| Computes the address of a clone deployed using {Clones-cloneDeterministic}./ | function predictDeterministicAddress(address implementation, bytes32 salt) internal view returns (address predicted) {
return predictDeterministicAddress(implementation, salt, address(this));
}
| 4,364 |
pragma solidity ^0.8.9;
// SPDX-License-Identifier: MIT
/**
* @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);
}
/**
* @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 IERC1155Upgradeable is IERC165Upgradeable {
/**
* @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;
}
/**
* @dev _Available since v3.1._
*/
interface IERC1155ReceiverUpgradeable is IERC165Upgradeable {
/**
@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);
}
/**
* @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 IERC1155MetadataURIUpgradeable is IERC1155Upgradeable {
/**
* @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);
}
/**
* @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);
}
}
}
}
/**
* @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;
}
}
}
/**
* @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;
}
/**
* @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;
}
/**
* @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 ERC1155Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC1155Upgradeable, IERC1155MetadataURIUpgradeable {
using AddressUpgradeable 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}.
*/
function __ERC1155_init(string memory uri_) internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC1155_init_unchained(uri_);
}
function __ERC1155_init_unchained(string memory uri_) internal initializer {
_setURI(uri_);
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) {
return
interfaceId == type(IERC1155Upgradeable).interfaceId ||
interfaceId == type(IERC1155MetadataURIUpgradeable).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 IERC1155ReceiverUpgradeable(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) {
if (response != IERC1155ReceiverUpgradeable.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 IERC1155ReceiverUpgradeable(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (
bytes4 response
) {
if (response != IERC1155ReceiverUpgradeable.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;
}
uint256[47] private __gap;
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
uint256[49] private __gap;
}
/**
* @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);
}
/**
* @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
}
}
}
/**
* @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 {
_upgradeTo(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
_upgradeTo(newImplementation);
}
}
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Returns the current admin.
*/
function _getAdmin() internal view returns (address) {
return 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 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 Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function _functionDelegateCall(address target, bytes memory data) private returns (bytes memory) {
require(AddressUpgradeable.isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return AddressUpgradeable.verifyCallResult(success, returndata, "Address: low-level delegate call failed");
}
uint256[50] private __gap;
}
/**
* @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
* {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
*
* A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
* reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
* `UUPSUpgradeable` with a custom implementation of upgrades.
*
* 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 {
}
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment
address private immutable __self = address(this);
/**
* @dev Check that the execution is being performed through a delegatecall call and that the execution context is
* a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case
* for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
* function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
* fail.
*/
modifier onlyProxy() {
require(address(this) != __self, "Function must be called through delegatecall");
require(_getImplementation() == __self, "Function must be called through active proxy");
_;
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*/
function upgradeTo(address newImplementation) external virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallSecure(newImplementation, new bytes(0), false);
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
* encoded in `data`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*/
function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallSecure(newImplementation, data, true);
}
/**
* @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
* {upgradeTo} and {upgradeToAndCall}.
*
* Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
*
* ```solidity
* function _authorizeUpgrade(address) internal override onlyOwner {}
* ```
*/
function _authorizeUpgrade(address newImplementation) internal virtual;
uint256[50] private __gap;
}
contract OwnableDelegateProxy {}
contract ProxyRegistry {
mapping(address => OwnableDelegateProxy) public proxies;
}
/// @title Crypto Heroes Contract
/// @notice Crypto Heroes is a limited-edition ECR-1155 crypto token collection that depicts
/// a world full of hidden plans, conspiracy theories, predictions, and the heroes &
/// personalities around them. The cards were created by J35, an anonymous figure who travelled
/// back in time to reveal the plans of the global power elite—and honor the heroes fighting
/// against it. We chose to deliver his message through a censorship-resistant 32-card set,
/// forever stored in the Ethereum blockchain
/// @author Qrypto Labs LLC
contract CryptoHeroes is Initializable, ERC1155Upgradeable, OwnableUpgradeable, UUPSUpgradeable {
error SaleNotActive();
error InvalidNumOfPacks(uint8 numPacks);
error NotEnoughEth(uint256 valueWei);
error NotOwnerOf(uint8 numPacks);
error QuantityNotAvailable(uint256 numPacks);
// Settings
uint8 constant DECK_SIZE = 32;
uint8 constant NUM_CARDS_PER_PACK = 2;
uint256 constant PACK_PRICE = 0.06 ether;
uint256 constant MAX_PACKS = 10000;
uint8 constant MAX_PACKS_PER_TX = 20;
uint8 constant RESERVED_PACKS = 16;
// Token ID
uint8 constant PACK_ID = 0;
// Card classes
uint16 constant COMMON = 770;
uint16 constant RARE = 300;
uint16 constant SECRET = 150;
uint16 constant ULTRA = 10;
// Contract state
uint16[DECK_SIZE] private availableCards;
address private proxyRegistry;
uint256 private seed;
uint256 public availablePacks;
string private contractMetadataUri;
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() initializer {}
/// Initializes contract state
function initialize(string memory _uri, string memory _contractMetadataUri, address _proxyRegistry) public initializer {
__ERC1155_init(_uri);
__Ownable_init();
__UUPSUpgradeable_init();
contractMetadataUri = _contractMetadataUri;
proxyRegistry = _proxyRegistry;
availableCards = [
COMMON - 1,
COMMON - 1,
COMMON - 1,
COMMON - 1,
COMMON - 1,
COMMON - 1,
COMMON - 1,
COMMON - 1,
COMMON - 1,
COMMON - 1,
COMMON - 1,
COMMON - 1,
COMMON - 1,
COMMON - 1,
COMMON - 1,
COMMON - 1,
COMMON - 1,
COMMON - 1,
COMMON - 1,
COMMON - 1,
COMMON - 1,
COMMON - 1,
COMMON - 1,
COMMON - 1,
RARE - 1,
RARE - 1,
RARE - 1,
RARE - 1,
SECRET - 1,
SECRET - 1,
ULTRA - 1,
ULTRA - 1
];
availablePacks = MAX_PACKS - RESERVED_PACKS;
}
/// returns the contract-level metadata URI
function contractURI() public view returns (string memory) {
return contractMetadataUri;
}
/// Sets the URI for the contract-level metadata URI
/// @param _newUri the new URI
function setContractURI(string memory _newUri) public onlyOwner {
contractMetadataUri = _newUri;
}
/// Sets the URI for the ECR-1155 Metadata JSON Schema
/// @param _newUri the new URI
function setURI(string memory _newUri) public onlyOwner {
_setURI(_newUri);
}
/// Only the owner can upgrade the contract implementation
function _authorizeUpgrade(address newImplementation) internal override onlyOwner {}
/// Avoids an additional authorization step (and gas fee) from OpenSea users
/// @param _account the user account address
/// @param _operator the OpenSea's proxy registry address
function isApprovedForAll(address _account, address _operator) public view virtual override returns (bool) {
ProxyRegistry _proxyRegistry = ProxyRegistry(proxyRegistry);
if (address(_proxyRegistry.proxies(_account)) == _operator) {
return true;
}
return super.isApprovedForAll(_account, _operator);
}
/// Ensures limit on number of packs
modifier checkAvailablePacks(uint256 _numPacks) {
if (availablePacks < _numPacks) {
// sold out or not enough packs left
revert QuantityNotAvailable(_numPacks);
}
_;
}
/// Mints a tradable pack. The packs can be "opened" once the sale is active
/// @param _to the recipients' addresses
/// @param _numPacks the number of packs to give away to each recipient
function mintGiveAwayPacks(address[] memory _to, uint8 _numPacks)
external
onlyOwner
checkAvailablePacks(_to.length * _numPacks)
{
availablePacks -= _to.length * _numPacks;
for (uint256 i = 0; i < _to.length; i++) {
_mint(_to[i], PACK_ID, _numPacks, '');
}
}
/// Mints two pseudo-randomly selected cards for each pack that
/// the sender wants to "open", as long as he/she owns them. "Opened"
/// packs are burned.
/// @param _numPacks the number of packs to "open"
function mintFromExistingPacks(uint8 _numPacks) public {
if (_numPacks > balanceOf(msg.sender, PACK_ID)) {
revert NotOwnerOf(_numPacks);
}
_burn(msg.sender, PACK_ID, _numPacks);
_mint(_numPacks);
}
/// Mints two pseudo-randomly selected cards for each pack
/// @param _numPacks the number of packs to "open"
function mintFromNewPacks(uint8 _numPacks) public payable checkAvailablePacks(_numPacks) {
if (msg.value < (uint256(_numPacks) * PACK_PRICE)) {
revert NotEnoughEth(msg.value);
}
if (_numPacks == 0 || _numPacks > MAX_PACKS_PER_TX) {
revert InvalidNumOfPacks(_numPacks);
}
availablePacks -= _numPacks;
_mint(_numPacks);
}
/// One copy of each card is reserved for the team so we can share the
/// collection's copyright
function mintDeckForTeam() public onlyOwner {
uint256[] memory _ids = new uint256[](DECK_SIZE);
uint256[] memory _amounts = new uint256[](DECK_SIZE);
for (uint256 i = 0; i < DECK_SIZE; i++) {
_ids[i] = i + 1;
_amounts[i] = 1;
}
_mintBatch(msg.sender, _ids, _amounts, '');
}
/// Main minting function: it mints two pseudo-randomly cards per pack. There
/// are pre-defined probabilities for each card, which are based on each card's
/// rarity. A seed, which is dependant with each card selection, the previous
/// block hash, and the transaction sender is used to add a source of additional
/// pseudo-randomness
/// @param _numPacks the number of packs to "open"
function _mint(uint8 _numPacks) internal virtual {
if (seed == 0) {
revert SaleNotActive();
}
uint256 _randomNumber = _random(seed);
uint256[] memory _ids = new uint256[](_numPacks*2);
uint256[] memory _amounts = new uint256[](_numPacks*2);
uint16[DECK_SIZE] memory _cardsProbabilities = [
20000,
19230,
18460,
17690,
16920,
16150,
15380,
14610,
13840,
13070,
12300,
11530,
10760,
9990,
9220,
8450,
7680,
6910,
6140,
5370,
4600,
3830,
3060,
2290,
1520,
1220,
920,
620,
320,
170,
20,
10
];
uint256 _counter = 0;
for (uint256 i = 0; i < _numPacks * NUM_CARDS_PER_PACK; i++) {
bool _selected;
uint16 _value = uint16(_randomNumber % (MAX_PACKS * NUM_CARDS_PER_PACK));
for (uint256 j = _cardsProbabilities.length - 1; j > 0; j--) {
uint16 _probability = _cardsProbabilities[j];
if (_value < _probability && availableCards[j] > 0) {
_ids[_counter] = j + 1;
_amounts[_counter]++;
availableCards[j]--;
_selected = true;
_counter++;
break;
}
}
if (!_selected) {
// if there are no cards left with a given (or lower) rarity,
// mint the first available card with the next lowest rarity
for (uint256 j = 0; j < _cardsProbabilities.length; j++) {
if (availableCards[j] > 0) {
_ids[_counter] = j + 1;
_amounts[_counter]++;
availableCards[j]--;
_counter++;
break;
}
}
}
_randomNumber = _random(_randomNumber);
}
seed = _randomNumber;
_mintBatch(msg.sender, _ids, _amounts, '');
}
/// Withdraws the contract's balance
function withdraw() public onlyOwner {
uint256 balance = address(this).balance;
payable(msg.sender).transfer(balance);
}
/// Returns a pseudorandom number
/// @param _seed additional source of pseudo-randomness
/// @return the pseudorandom number
function _random(uint256 _seed) internal view returns (uint256) {
return uint256(keccak256(abi.encodePacked(blockhash(block.number - 1), msg.sender, _seed)));
}
/// A non-zero value activates the sale and improves the pseudorandom
/// number generator
/// @param _newSeed the seed to use for the next transaction
function setSeed(uint256 _newSeed) public onlyOwner {
seed = _newSeed;
}
/// Returns true if the sale is active; false otherwise
function isSaleActive() public view returns (bool) {
return seed != 0;
}
/// Returns the available quantity for each card
function getAllAvailableCards() public view returns (uint16[DECK_SIZE] memory) {
return availableCards;
}
} | Returns a pseudorandom number _seed additional source of pseudo-randomness return the pseudorandom number | function _random(uint256 _seed) internal view returns (uint256) {
return uint256(keccak256(abi.encodePacked(blockhash(block.number - 1), msg.sender, _seed)));
}
| 12,181,946 |
pragma solidity 0.5.4;
library safemath3 { //inject NONSTANDARD NAMING
uint256 constant internal max_uint25 = 2 ** 256 - 1; // max uint256 //inject NONSTANDARD NAMING
function MUL14(uint256 _a, uint256 _b) internal pure returns(uint256) { //inject NONSTANDARD NAMING
if (_a == 0) {
return 0;
}
require(max_uint25 / _a >= _b);
return _a * _b;
}
function DIV12(uint256 _a, uint256 _b) internal pure returns(uint256) { //inject NONSTANDARD NAMING
require(_b != 0);
return _a / _b;
}
function SUB94(uint256 _a, uint256 _b) internal pure returns(uint256) { //inject NONSTANDARD NAMING
require(_b <= _a);
return _a - _b;
}
function ADD70(uint256 _a, uint256 _b) internal pure returns(uint256) { //inject NONSTANDARD NAMING
require(max_uint25 - _a >= _b);
return _a + _b;
}
}
interface abcinterface55 { //inject NONSTANDARD NAMING
function DECIMALS31() external view returns (uint8); //inject NONSTANDARD NAMING
function TOKENFALLBACK96(address _from, uint _value, bytes calldata _data) external; //inject NONSTANDARD NAMING
function TRANSFER8(address _to, uint _value) external returns (bool); //inject NONSTANDARD NAMING
}
contract ownable89 { //inject NONSTANDARD NAMING
address public owner;
event OWNERSHIPTRANSFERRED5(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING
constructor () public {
owner = msg.sender;
}
modifier ONLYOWNER84() { //inject NONSTANDARD NAMING
require(msg.sender == owner);
_;
}
function TRANSFEROWNERSHIP95(address newOwner) public ONLYOWNER84 { //inject NONSTANDARD NAMING
_TRANSFEROWNERSHIP10(newOwner);
}
function _TRANSFEROWNERSHIP10(address newOwner) internal { //inject NONSTANDARD NAMING
require(newOwner != address(0));
emit OWNERSHIPTRANSFERRED5(owner, newOwner);
owner = newOwner;
}
}
contract pausable6 is ownable89 { //inject NONSTANDARD NAMING
event PAUSE44(); //inject NONSTANDARD NAMING
event UNPAUSE10(); //inject NONSTANDARD NAMING
bool public paused = false;
modifier WHENNOTPAUSED65() { //inject NONSTANDARD NAMING
require(!paused);
_;
}
modifier WHENPAUSED45() { //inject NONSTANDARD NAMING
require(paused);
_;
}
function PAUSE13() public ONLYOWNER84 WHENNOTPAUSED65 { //inject NONSTANDARD NAMING
paused = true;
emit PAUSE44();
}
function UNPAUSE100() public ONLYOWNER84 WHENPAUSED45 { //inject NONSTANDARD NAMING
paused = false;
emit UNPAUSE10();
}
}
contract standardtoken75 { //inject NONSTANDARD NAMING
using safemath3 for uint256;
mapping(address => uint256) internal balances;
mapping(address => mapping(address => uint256)) internal allowed;
uint256 public totalSupply;
event TRANSFER15(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL37(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
function BALANCEOF36(address _owner) public view returns(uint256) { //inject NONSTANDARD NAMING
return balances[_owner];
}
function ALLOWANCE8(address _owner, address _spender) public view returns(uint256) { //inject NONSTANDARD NAMING
return allowed[_owner][_spender];
}
function TRANSFER8(address _to, uint256 _value) public returns(bool) { //inject NONSTANDARD NAMING
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].SUB94(_value);
balances[_to] = balances[_to].ADD70(_value);
emit TRANSFER15(msg.sender, _to, _value);
return true;
}
function APPROVE5(address _spender, uint256 _value) public returns(bool) { //inject NONSTANDARD NAMING
allowed[msg.sender][_spender] = _value;
emit APPROVAL37(msg.sender, _spender, _value);
return true;
}
function TRANSFERFROM4(address _from, address _to, uint256 _value) public returns(bool) { //inject NONSTANDARD NAMING
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].SUB94(_value);
balances[_to] = balances[_to].ADD70(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].SUB94(_value);
emit TRANSFER15(_from, _to, _value);
return true;
}
function INCREASEAPPROVAL59(address _spender, uint256 _addedValue) public returns(bool) { //inject NONSTANDARD NAMING
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].ADD70(_addedValue);
emit APPROVAL37(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function DECREASEAPPROVAL60(address _spender, uint256 _subtractedValue) public returns(bool) { //inject NONSTANDARD NAMING
uint256 oldValue = allowed[msg.sender][_spender];
if (_subtractedValue >= oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.SUB94(_subtractedValue);
}
emit APPROVAL37(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function _BURN20(address account, uint256 value) internal { //inject NONSTANDARD NAMING
require(account != address(0));
totalSupply = totalSupply.SUB94(value);
balances[account] = balances[account].SUB94(value);
emit TRANSFER15(account, address(0), value);
}
function _BURNFROM53(address account, uint256 value) internal { //inject NONSTANDARD NAMING
// Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted,
// this function needs to emit an event with the updated approval.
allowed[account][msg.sender] = allowed[account][msg.sender].SUB94(value);
_BURN20(account, value);
}
}
contract burnabletoken62 is standardtoken75 { //inject NONSTANDARD NAMING
function BURN76(uint256 value) public { //inject NONSTANDARD NAMING
_BURN20(msg.sender, value);
}
function BURNFROM19(address from, uint256 value) public { //inject NONSTANDARD NAMING
_BURNFROM53(from, value);
}
}
contract pausabletoken80 is standardtoken75, pausable6 { //inject NONSTANDARD NAMING
function TRANSFER8(address to, uint256 value) public WHENNOTPAUSED65 returns (bool) { //inject NONSTANDARD NAMING
return super.TRANSFER8(to, value);
}
function TRANSFERFROM4(address from, address to, uint256 value) public WHENNOTPAUSED65 returns (bool) { //inject NONSTANDARD NAMING
return super.TRANSFERFROM4(from, to, value);
}
function APPROVE5(address spender, uint256 value) public WHENNOTPAUSED65 returns (bool) { //inject NONSTANDARD NAMING
return super.APPROVE5(spender, value);
}
function INCREASEAPPROVAL59(address spender, uint256 addedValue) public WHENNOTPAUSED65 returns (bool success) { //inject NONSTANDARD NAMING
return super.INCREASEAPPROVAL59(spender, addedValue);
}
function DECREASEAPPROVAL60(address spender, uint256 subtractedValue) public WHENNOTPAUSED65 returns (bool success) { //inject NONSTANDARD NAMING
return super.DECREASEAPPROVAL60(spender, subtractedValue);
}
}
contract token13 is pausabletoken80, burnabletoken62 { //inject NONSTANDARD NAMING
string public name; // name of Token
string public symbol; // symbol of Token
uint8 public decimals;
constructor(string memory _name, string memory _symbol, uint8 _decimals) public {
name = _name;
symbol = _symbol;
decimals = _decimals;
}
}
contract bdr1 is token13 { //inject NONSTANDARD NAMING
struct Trx {
bool executed;
address from;
uint256 value;
address[] signers;
}
mapping(address => bool) public isSigner;
mapping(uint256 => Trx) public exchangeTrx;
address public AbcInstance; // address of AbcToken
uint256 public requestSigners = 2; // BDR => Abc need signers number
uint256 public applyCounts = 0; // Sequence of exchange request
mapping(address => uint256) public exchangeLock;
event SETSIGNER61(address indexed signer,bool isSigner); // emit when add/remove signer //inject NONSTANDARD NAMING
event APPLYEXCHANGETOKEN76(address indexed from,uint256 value,uint256 trxSeq); // emit when exchange successful //inject NONSTANDARD NAMING
event CONFIRMTRX99(address indexed signer,uint256 indexed trxSeq); // emit when signer confirmed exchange request //inject NONSTANDARD NAMING
event CANCLECONFIRMTRX58(address indexed signer,uint256 indexed trxSeq); // emit when signer cancles confirmed exchange request //inject NONSTANDARD NAMING
event CANCLEEXCHANGEREQUEST46(address indexed signer,uint256 indexed trxSeq); // emit when signer/requester cancles exchange request //inject NONSTANDARD NAMING
event TOKENEXCHANGE38(address indexed from,uint256 value,bool AbcExchangeBDR); // emit when Abc <=> Bdr,true:Abc => BDR,false:BDR => abc //inject NONSTANDARD NAMING
event MINT96(address indexed target,uint256 value); //inject NONSTANDARD NAMING
modifier ONLYSIGNER18() { //inject NONSTANDARD NAMING
require(isSigner[msg.sender]);
_;
}
constructor(string memory _name, string memory _symbol, uint8 _decimals) token13(_name,_symbol,_decimals) public {
}
function TRANSFER8(address _to,uint256 _value) public returns (bool success) { //inject NONSTANDARD NAMING
require(_to != AbcInstance,"can't transfer to AbcToken address directly");
return super.TRANSFER8(_to,_value);
}
function TRANSFERFROM4(address _from, address _to,uint256 _value) public returns (bool success) { //inject NONSTANDARD NAMING
require(_to != AbcInstance,"can't transferFrom to AbcToken address directly");
return super.TRANSFERFROM4(_from,_to,_value);
}
function SETABCINSTANCE98(address _abc) public ONLYOWNER84 { //inject NONSTANDARD NAMING
require(_abc != address(0));
AbcInstance = _abc;
}
function SETSIGNERS29(address[] memory _signers,bool _addSigner) public ONLYOWNER84 { //inject NONSTANDARD NAMING
for(uint256 i = 0;i< _signers.length;i++){
require(_signers[i] != address(0));
isSigner[_signers[i]] = _addSigner;
emit SETSIGNER61(_signers[i],_addSigner);
}
}
function SETREQUESTSIGNERS10(uint256 _requestSigners) public ONLYOWNER84 { //inject NONSTANDARD NAMING
require(_requestSigners != 0);
requestSigners = _requestSigners;
}
function ISCONFIRMER42(uint256 _trxSeq,address _signer) public view returns (bool) { //inject NONSTANDARD NAMING
require(exchangeTrx[_trxSeq].from != address(0),"trxSeq not exist");
for(uint256 i = 0;i < exchangeTrx[_trxSeq].signers.length;i++){
if(exchangeTrx[_trxSeq].signers[i] == _signer){
return true;
}
}
return false;
}
function GETCONFIRMERSLENGTHOFTRX91(uint256 _trxSeq) public view returns (uint256) { //inject NONSTANDARD NAMING
return exchangeTrx[_trxSeq].signers.length;
}
function GETCONFIRMEROFTRX7(uint256 _trxSeq,uint256 _index) public view returns (address) { //inject NONSTANDARD NAMING
require(_index < GETCONFIRMERSLENGTHOFTRX91(_trxSeq),"out of range");
return exchangeTrx[_trxSeq].signers[_index];
}
function APPLYEXCHANGETOKEN24(uint256 _value) public WHENNOTPAUSED65 returns (uint256) { //inject NONSTANDARD NAMING
uint256 trxSeq = applyCounts;
require(exchangeTrx[trxSeq].from == address(0),"trxSeq already exist");
require(balances[msg.sender] >= _value);
exchangeTrx[trxSeq].executed = false;
exchangeTrx[trxSeq].from = msg.sender;
exchangeTrx[trxSeq].value = _value;
applyCounts = applyCounts.ADD70(1);
balances[address(this)] = balances[address(this)].ADD70(_value);
balances[exchangeTrx[trxSeq].from] = balances[exchangeTrx[trxSeq].from].SUB94(_value);
exchangeLock[exchangeTrx[trxSeq].from] = exchangeLock[exchangeTrx[trxSeq].from].ADD70(_value);
emit APPLYEXCHANGETOKEN76(exchangeTrx[trxSeq].from,exchangeTrx[trxSeq].value,trxSeq);
emit TRANSFER15(msg.sender,address(this),_value);
return trxSeq;
}
function CONFIRMEXCHANGETRX5(uint256 _trxSeq) public ONLYSIGNER18 { //inject NONSTANDARD NAMING
require(exchangeTrx[_trxSeq].from != address(0),"_trxSeq not exist");
require(exchangeTrx[_trxSeq].signers.length < requestSigners,"trx already has enough signers");
require(exchangeTrx[_trxSeq].executed == false,"trx already executed");
require(ISCONFIRMER42(_trxSeq, msg.sender) == false,"signer already confirmed");
exchangeTrx[_trxSeq].signers.push(msg.sender);
emit CONFIRMTRX99(msg.sender, _trxSeq);
}
function CANCELCONFIRM57(uint256 _trxSeq) public ONLYSIGNER18 { //inject NONSTANDARD NAMING
require(exchangeTrx[_trxSeq].from != address(0),"_trxSeq not exist");
require(ISCONFIRMER42(_trxSeq, msg.sender),"Signer didn't confirm");
require(exchangeTrx[_trxSeq].executed == false,"trx already executed");
uint256 len = exchangeTrx[_trxSeq].signers.length;
for(uint256 i = 0;i < len;i++){
if(exchangeTrx[_trxSeq].signers[i] == msg.sender){
exchangeTrx[_trxSeq].signers[i] = exchangeTrx[_trxSeq].signers[len.SUB94(1)] ;
exchangeTrx[_trxSeq].signers.length --;
break;
}
}
emit CANCLECONFIRMTRX58(msg.sender,_trxSeq);
}
function CANCLEEXCHANGEREQUEST83(uint256 _trxSeq) public { //inject NONSTANDARD NAMING
require(exchangeTrx[_trxSeq].from != address(0),"_trxSeq not exist");
require(exchangeTrx[_trxSeq].executed == false,"trx already executed");
require(isSigner[msg.sender] || exchangeTrx[_trxSeq].from == msg.sender);
balances[address(this)] = balances[address(this)].SUB94(exchangeTrx[_trxSeq].value);
balances[exchangeTrx[_trxSeq].from] = balances[exchangeTrx[_trxSeq].from].ADD70(exchangeTrx[_trxSeq].value);
exchangeLock[exchangeTrx[_trxSeq].from] = exchangeLock[exchangeTrx[_trxSeq].from].SUB94(exchangeTrx[_trxSeq].value);
delete exchangeTrx[_trxSeq];
emit CANCLEEXCHANGEREQUEST46(msg.sender,_trxSeq);
emit TRANSFER15(address(this),exchangeTrx[_trxSeq].from,exchangeTrx[_trxSeq].value);
}
function EXECUTEEXCHANGETRX59(uint256 _trxSeq) public WHENNOTPAUSED65{ //inject NONSTANDARD NAMING
address from = exchangeTrx[_trxSeq].from;
uint256 value = exchangeTrx[_trxSeq].value;
require(from != address(0),"trxSeq not exist");
require(exchangeTrx[_trxSeq].executed == false,"trxSeq has executed");
require(exchangeTrx[_trxSeq].signers.length >= requestSigners);
require(from == msg.sender|| isSigner[msg.sender]);
require(value <= balances[address(this)]);
_BURN20(address(this), value);
exchangeLock[from] = exchangeLock[from].SUB94(value);
exchangeTrx[_trxSeq].executed = true;
abcinterface55(AbcInstance).TOKENFALLBACK96(from,value,bytes(""));
emit TOKENEXCHANGE38(exchangeTrx[_trxSeq].from,exchangeTrx[_trxSeq].value,false);
}
function TOKENFALLBACK96(address _from, uint _value, bytes memory) public { //inject NONSTANDARD NAMING
require(msg.sender == AbcInstance);
require(_from != address(0));
require(_value > 0);
uint256 exchangeAmount = _value.MUL14(10**uint256(decimals)).DIV12(10**uint256(abcinterface55(AbcInstance).DECIMALS31()));
_MINT16(_from, exchangeAmount);
emit TRANSFER15(address(0x00),_from,exchangeAmount);
emit TOKENEXCHANGE38(_from,_value,true);
}
function _MINT16(address target, uint256 value ) internal { //inject NONSTANDARD NAMING
balances[target] = balances[target].ADD70(value);
totalSupply = totalSupply.ADD70(value);
emit MINT96(target,value);
}
} | inject NONSTANDARD NAMING | function TRANSFER8(address _to, uint _value) external returns (bool); | 974,716 |
./full_match/1/0xa89c95Fc72E40B1eD816c99B4169D96A0ED8Ed20/sources/contracts/interface/IGalaGameItems.sol | Why? Gala's Items Contracts use a proprietary burn function signature | interface IGalaGameItems is IERC1155 {
function burn(address _from, uint256[] calldata _ids, uint256[] calldata _values) external;
pragma solidity 0.8.2;
} | 9,641,856 |
// OpenZeppelin ERC1155PresetMinterPauser.sol
// https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/presets/ERC1155PresetMinterPauser.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/GSN/Context.sol";
import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol";
import "@openzeppelin/contracts/token/ERC1155/ERC1155Pausable.sol";
import "./interfaces/IFeesManager.sol";
/**
* @dev {ERC1155} token, including:
*
* - ability for holders to burn (destroy) their tokens
* - a minter role that allows for token minting (creation)
* - a pauser role that allows to stop all token transfers
*
* This contract uses {AccessControl} to lock permissioned functions using the
* different roles - head to its documentation for details.
*
* The account that deploys the contract will be granted the minter and pauser
* roles, as well as the default admin role, which will let it grant both minter
* and pauser roles to other accounts.
*/
contract ERC11554k is Context, AccessControl, ERC1155Pausable {
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
bytes32 public constant SEIZER_ROLE = keccak256("SEIZER_ROLE");
// First owners of items.
mapping(uint256 => address) internal _originators;
// Fees manager contract address.
address public feesManager;
// Drop pool contract address.
address public dropPool;
// Redeem pool address.
address public redeemPool;
// Seize pool address.
address public seizePool;
/**
* @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE`, and `PAUSER_ROLE` to the account that
* deploys the contract.
*/
constructor(string memory uri) ERC1155(uri) {
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_setupRole(MINTER_ROLE, _msgSender());
_setupRole(PAUSER_ROLE, _msgSender());
_setupRole(SEIZER_ROLE, _msgSender());
}
/**
* @dev Sets `feesManager` to `newFeesManager`.
*
* Requirements:
*
* - the caller must have the `DEFAULT_ADMIN_ROLE`.
*/
function setFeesManager(address newFeesManager) external {
require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "ERC11554k: must have admin role to set fees manager");
feesManager = newFeesManager;
}
/**
* @dev Sets `redeemPool` to `newRedeemPool`.
*
* Requirements:
*
* - the caller must have the `DEFAULT_ADMIN_ROLE`.
*/
function setRedeemPool(address newRedeemPool) external {
require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "ERC11554k: must have admin role to set redeem pool");
redeemPool = newRedeemPool;
}
/**
* @dev Sets `dropPool` to `newDropPool`.
*
* Requirements:
*
* - the caller must have the `DEFAULT_ADMIN_ROLE`.
*/
function setDropPool(address newDropPool) external {
require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "ERC11554k: must have admin role to set drop pool");
revokeRole(MINTER_ROLE, dropPool);
grantRole(MINTER_ROLE, newDropPool);
dropPool = newDropPool;
}
/**
* @dev Transfers all roles from `admin` to `newAdmin`.
*
* Requirements:
*
* - the caller must have the `DEFAULT_ADMIN_ROLE`.
*/
function transferAllRoles(address newAdmin) external {
require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "ERC11554k: must have admin role to transfer all roles");
grantRole(MINTER_ROLE, newAdmin);
grantRole(PAUSER_ROLE, newAdmin);
grantRole(SEIZER_ROLE, newAdmin);
grantRole(DEFAULT_ADMIN_ROLE, newAdmin);
if (hasRole(MINTER_ROLE, _msgSender())) {
revokeRole(MINTER_ROLE, _msgSender());
}
if (hasRole(PAUSER_ROLE, _msgSender())) {
revokeRole(PAUSER_ROLE, _msgSender());
}
if (hasRole(SEIZER_ROLE, _msgSender())) {
revokeRole(SEIZER_ROLE, _msgSender());
}
revokeRole(DEFAULT_ADMIN_ROLE, _msgSender());
}
/**
* @dev Sets `seizePool` to `newSeizePool`.
*
* Requirements:
*
* - the caller must have the `DEFAULT_ADMIN_ROLE`.
*/
function setSeizePool(address newSeizePool) external {
require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "ERC11554k: must have admin role to set seize pool");
revokeRole(SEIZER_ROLE, seizePool);
grantRole(SEIZER_ROLE, newSeizePool);
seizePool = newSeizePool;
}
/**
* @dev Seize 'amount' items with 'id' by transferring ownership to admin,
* if seizure allowed, based on current storage fees debt.
*
* Requirements:
*
* - the caller must have the `MINTER_ROLE`.
*/
function seize(uint256 id, address owner) external {
require(hasRole(SEIZER_ROLE, _msgSender()), "ERC11554k: must have minter role to seize an item");
require(feesManager != address(0), "ERC11554k: fees manager must be set");
require(seizePool != address(0), "ERC1155k: seize pool must be set");
require(IFeesManager(feesManager).isSeizureAllowed(id, owner), "ERC11554k: must allow seizure based on storage fees debt");
safeTransferFrom(owner, seizePool, id, balanceOf(owner, id), "0x");
}
/**
* @dev Redeem item with 'id' by its owner.
* Must pay all storage fees debt up to a redeem moment.
*/
function redeem(uint256 id) external {
if (feesManager != address(0)) {
IFeesManager(feesManager).payStorage(id, _msgSender());
}
safeTransferFrom(_msgSender(), redeemPool, id, balanceOf(_msgSender(), id), "0x");
}
/**
* @dev Creates `amount` new tokens for `to`, of token type `id`.
*
* See {ERC1155-_mint}.
*
* Requirements:
*
* - the caller must have the `MINTER_ROLE`.
*/
function mint(address to, uint256 id, uint256 amount, bytes memory data) public virtual {
require(hasRole(MINTER_ROLE, _msgSender()), "ERC1155PresetMinterPauser: must have minter role to mint");
_originators[id] = to;
_mint(to, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] variant of {mint}.
*/
function mintBatch(address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data) public virtual {
require(hasRole(MINTER_ROLE, _msgSender()), "ERC1155PresetMinterPauser: must have minter role to mint");
for (uint256 i = 0; i < ids.length; ++i) {
_originators[ids[i]] = to;
}
_mintBatch(to, ids, amounts, data);
}
/**
* @dev Pauses all token transfers.
*
* See {ERC1155Pausable} and {Pausable-_pause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function pause() public virtual {
require(hasRole(PAUSER_ROLE, _msgSender()), "ERC1155PresetMinterPauser: must have pauser role to pause");
_pause();
}
/**
* @dev Unpauses all token transfers.
*
* See {ERC1155Pausable} and {Pausable-_unpause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function unpause() public virtual {
require(hasRole(PAUSER_ROLE, _msgSender()), "ERC1155PresetMinterPauser: must have pauser role to unpause");
_unpause();
}
/**
* @dev Returns orignator address of item with 'id'.
*/
function originatorOf(uint256 id) public returns (address) {
return _originators[id];
}
/**
* @dev Unpauses all token transfers.
*
* Requirements:
*
* - the caller must have the `DEFAULT_ADMIN_ROLE`.
*/
function setURI(string memory newuri) public virtual {
require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "ERC11554k: must have admin role to set URI");
_setURI(newuri);
}
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(), "ERC1155Pausable: token transfer while paused");
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev {IFeesManager} interface:
*/
interface IFeesManager {
/**
* @dev Returns 'true' if seizure of item with 'id' allowed, 'false' otherwise.
*/
function isSeizureAllowed(uint256 id, address owner) external returns (bool);
/**
* @dev Returns 'true' if payment for storage was successful, 'false' otherwise.
*/
function payStorage(uint256 id, address owner) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/Context.sol";
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/EnumerableSet.sol";
import "../utils/Address.sol";
import "../utils/Context.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context {
using EnumerableSet for EnumerableSet.AddressSet;
using Address for address;
struct RoleData {
EnumerableSet.AddressSet members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view returns (bool) {
return _roles[role].members.contains(account);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view returns (uint256) {
return _roles[role].members.length();
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view returns (address) {
return _roles[role].members.at(index);
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant");
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke");
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, _roles[role].adminRole, adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
abstract contract ERC165 is IERC165 {
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
constructor () internal {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev 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 "./IERC1155.sol";
import "./IERC1155MetadataURI.sol";
import "./IERC1155Receiver.sol";
import "../../utils/Context.sol";
import "../../introspection/ERC165.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.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 SafeMath for uint256;
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;
/*
* bytes4(keccak256('balanceOf(address,uint256)')) == 0x00fdd58e
* bytes4(keccak256('balanceOfBatch(address[],uint256[])')) == 0x4e1273f4
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('safeTransferFrom(address,address,uint256,uint256,bytes)')) == 0xf242432a
* bytes4(keccak256('safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)')) == 0x2eb2c2d6
*
* => 0x00fdd58e ^ 0x4e1273f4 ^ 0xa22cb465 ^
* 0xe985e9c5 ^ 0xf242432a ^ 0x2eb2c2d6 == 0xd9b67a26
*/
bytes4 private constant _INTERFACE_ID_ERC1155 = 0xd9b67a26;
/*
* bytes4(keccak256('uri(uint256)')) == 0x0e89341c
*/
bytes4 private constant _INTERFACE_ID_ERC1155_METADATA_URI = 0x0e89341c;
/**
* @dev See {_setURI}.
*/
constructor (string memory uri_) public {
_setURI(uri_);
// register the supported interfaces to conform to ERC1155 via ERC165
_registerInterface(_INTERFACE_ID_ERC1155);
// register the supported interfaces to conform to ERC1155MetadataURI via ERC165
_registerInterface(_INTERFACE_ID_ERC1155_METADATA_URI);
}
/**
* @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) external 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(to != address(0), "ERC1155: transfer to the zero address");
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data);
_balances[id][from] = _balances[id][from].sub(amount, "ERC1155: insufficient balance for transfer");
_balances[id][to] = _balances[id][to].add(amount);
emit TransferSingle(operator, from, to, id, amount);
_doSafeTransferAcceptanceCheck(operator, 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(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
require(to != address(0), "ERC1155: transfer to the zero address");
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: transfer caller is not owner nor approved"
);
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];
_balances[id][from] = _balances[id][from].sub(
amount,
"ERC1155: insufficient balance for transfer"
);
_balances[id][to] = _balances[id][to].add(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] = _balances[id][account].add(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 (uint i = 0; i < ids.length; i++) {
_balances[ids[i]][to] = amounts[i].add(_balances[ids[i]][to]);
}
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), "");
_balances[id][account] = _balances[id][account].sub(
amount,
"ERC1155: burn amount exceeds balance"
);
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 (uint i = 0; i < ids.length; i++) {
_balances[ids[i]][account] = _balances[ids[i]][account].sub(
amounts[i],
"ERC1155: burn amount exceeds balance"
);
}
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(to).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(to).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.6.0 <0.8.0;
import "./ERC1155.sol";
import "../../utils/Pausable.sol";
/**
* @dev ERC1155 token with pausable token transfers, minting and burning.
*
* Useful for scenarios such as preventing trades until the end of an evaluation
* period, or having an emergency switch for freezing all token transfers in the
* event of a large bug.
*
* _Available since v3.1._
*/
abstract contract ERC1155Pausable is ERC1155, Pausable {
/**
* @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(), "ERC1155Pausable: token transfer while paused");
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "../../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.6.2 <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.6.0 <0.8.0;
import "../../introspection/IERC165.sol";
/**
* _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.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor () internal {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
| Sets `redeemPool` to `newRedeemPool`. Requirements: - the caller must have the `DEFAULT_ADMIN_ROLE`./ | function setRedeemPool(address newRedeemPool) external {
require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "ERC11554k: must have admin role to set redeem pool");
redeemPool = newRedeemPool;
}
| 9,848,850 |
pragma solidity ^0.5.0;
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev give an account access to this role
*/
function add(Role storage role, address account) internal {
require(account != address(0));
require(!has(role, account));
role.bearer[account] = true;
}
/**
* @dev remove an account's access to this role
*/
function remove(Role storage role, address account) internal {
require(account != address(0));
require(has(role, account));
role.bearer[account] = false;
}
/**
* @dev check if an account has this role
* @return bool
*/
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0));
return role.bearer[account];
}
}
contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @return the address of the owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner());
_;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
/**
* @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;
}
}
interface IERC20 {
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowed[owner][spender];
}
/**
* @dev Transfer token for a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* Note that while this function emits an Approval event, this is not required as per the specification,
* and other compliant implementations may not emit the event.
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(address from, address to, uint256 value) public returns (bool) {
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
_transfer(from, to, value);
emit Approval(from, msg.sender, _allowed[from][msg.sender]);
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
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = _allowed[msg.sender][spender].add(addedValue);
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = _allowed[msg.sender][spender].sub(subtractedValue);
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* Emits an Approval event (reflecting the reduced allowance).
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(value);
_burn(account, value);
emit Approval(account, msg.sender, _allowed[account][msg.sender]);
}
}
contract ERC20Burnable is ERC20 {
/**
* @dev Burns a specific amount of tokens.
* @param value The amount of token to be burned.
*/
function burn(uint256 value) public {
_burn(msg.sender, value);
}
/**
* @dev Burns a specific amount of tokens from the target address and decrements allowance
* @param from address The address which you want to send tokens from
* @param value uint256 The amount of token to be burned
*/
function burnFrom(address from, uint256 value) public {
_burnFrom(from, value);
}
}
contract PauserRole {
using Roles for Roles.Role;
event PauserAdded(address indexed account);
event PauserRemoved(address indexed account);
Roles.Role private _pausers;
constructor () internal {
_addPauser(msg.sender);
}
modifier onlyPauser() {
require(isPauser(msg.sender));
_;
}
function isPauser(address account) public view returns (bool) {
return _pausers.has(account);
}
function addPauser(address account) public onlyPauser {
_addPauser(account);
}
function renouncePauser() public {
_removePauser(msg.sender);
}
function _addPauser(address account) internal {
_pausers.add(account);
emit PauserAdded(account);
}
function _removePauser(address account) internal {
_pausers.remove(account);
emit PauserRemoved(account);
}
}
contract Pausable is PauserRole {
event Paused(address account);
event Unpaused(address account);
bool private _paused;
constructor () internal {
_paused = false;
}
/**
* @return true if the contract is paused, false otherwise.
*/
function paused() public view returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!_paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(_paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() public onlyPauser whenNotPaused {
_paused = true;
emit Paused(msg.sender);
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() public onlyPauser whenPaused {
_paused = false;
emit Unpaused(msg.sender);
}
}
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 increaseAllowance(address spender, uint addedValue) public whenNotPaused returns (bool success) {
return super.increaseAllowance(spender, addedValue);
}
function decreaseAllowance(address spender, uint subtractedValue) public whenNotPaused returns (bool success) {
return super.decreaseAllowance(spender, subtractedValue);
}
}
contract Whitelisting is Ownable {
mapping(address => bool) public isInvestorApproved;
mapping(address => bool) public isInvestorPaymentApproved;
event Approved(address indexed investor);
event Disapproved(address indexed investor);
event PaymentApproved(address indexed investor);
event PaymentDisapproved(address indexed investor);
//Token distribution approval (KYC results)
function approveInvestor(address toApprove) public onlyOwner {
isInvestorApproved[toApprove] = true;
emit Approved(toApprove);
}
function approveInvestorsInBulk(address[] calldata toApprove) external onlyOwner {
for (uint i=0; i<toApprove.length; i++) {
isInvestorApproved[toApprove[i]] = true;
emit Approved(toApprove[i]);
}
}
function disapproveInvestor(address toDisapprove) public onlyOwner {
delete isInvestorApproved[toDisapprove];
emit Disapproved(toDisapprove);
}
function disapproveInvestorsInBulk(address[] calldata toDisapprove) external onlyOwner {
for (uint i=0; i<toDisapprove.length; i++) {
delete isInvestorApproved[toDisapprove[i]];
emit Disapproved(toDisapprove[i]);
}
}
//Investor payment approval (For private sale)
function approveInvestorPayment(address toApprove) public onlyOwner {
isInvestorPaymentApproved[toApprove] = true;
emit PaymentApproved(toApprove);
}
function approveInvestorsPaymentInBulk(address[] calldata toApprove) external onlyOwner {
for (uint i=0; i<toApprove.length; i++) {
isInvestorPaymentApproved[toApprove[i]] = true;
emit PaymentApproved(toApprove[i]);
}
}
function disapproveInvestorapproveInvestorPayment(address toDisapprove) public onlyOwner {
delete isInvestorPaymentApproved[toDisapprove];
emit PaymentDisapproved(toDisapprove);
}
function disapproveInvestorsPaymentInBulk(address[] calldata toDisapprove) external onlyOwner {
for (uint i=0; i<toDisapprove.length; i++) {
delete isInvestorPaymentApproved[toDisapprove[i]];
emit PaymentDisapproved(toDisapprove[i]);
}
}
}
contract CommunityVesting is Ownable {
using SafeMath for uint256;
mapping (address => Holding) public holdings;
uint256 constant public MinimumHoldingPeriod = 90 days;
uint256 constant public Interval = 90 days;
uint256 constant public MaximumHoldingPeriod = 360 days;
uint256 constant public CommunityCap = 14300000 ether; // 14.3 million tokens
uint256 public totalCommunityTokensCommitted;
struct Holding {
uint256 tokensCommitted;
uint256 tokensRemaining;
uint256 startTime;
}
event CommunityVestingInitialized(address _to, uint256 _tokens, uint256 _startTime);
event CommunityVestingUpdated(address _to, uint256 _totalTokens, uint256 _startTime);
function claimTokens(address beneficiary)
external
onlyOwner
returns (uint256 tokensToClaim)
{
uint256 tokensRemaining = holdings[beneficiary].tokensRemaining;
uint256 startTime = holdings[beneficiary].startTime;
require(tokensRemaining > 0, "All tokens claimed");
require(now.sub(startTime) > MinimumHoldingPeriod, "Claiming period not started yet");
if (now.sub(startTime) >= MaximumHoldingPeriod) {
tokensToClaim = tokensRemaining;
delete holdings[beneficiary];
} else {
uint256 percentage = calculatePercentageToRelease(startTime);
uint256 tokensNotToClaim = (holdings[beneficiary].tokensCommitted.mul(100 - percentage)).div(100);
tokensToClaim = tokensRemaining.sub(tokensNotToClaim);
tokensRemaining = tokensNotToClaim;
holdings[beneficiary].tokensRemaining = tokensRemaining;
}
}
function calculatePercentageToRelease(uint256 _startTime) internal view returns (uint256 percentage) {
// how many 90 day periods have passed
uint periodsPassed = ((now.sub(_startTime)).div(Interval));
percentage = periodsPassed.mul(25); // 25% to be released every 90 days
}
function initializeVesting(
address _beneficiary,
uint256 _tokens,
uint256 _startTime
)
external
onlyOwner
{
totalCommunityTokensCommitted = totalCommunityTokensCommitted.add(_tokens);
require(totalCommunityTokensCommitted <= CommunityCap);
if (holdings[_beneficiary].tokensCommitted != 0) {
holdings[_beneficiary].tokensCommitted = holdings[_beneficiary].tokensCommitted.add(_tokens);
holdings[_beneficiary].tokensRemaining = holdings[_beneficiary].tokensRemaining.add(_tokens);
emit CommunityVestingUpdated(
_beneficiary,
holdings[_beneficiary].tokensRemaining,
holdings[_beneficiary].startTime
);
} else {
holdings[_beneficiary] = Holding(
_tokens,
_tokens,
_startTime
);
emit CommunityVestingInitialized(_beneficiary, _tokens, _startTime);
}
}
}
contract EcosystemVesting is Ownable {
using SafeMath for uint256;
mapping (address => Holding) public holdings;
uint256 constant public Interval = 90 days;
uint256 constant public MaximumHoldingPeriod = 630 days;
uint256 constant public EcosystemCap = 54100000 ether; // 54.1 million tokens
uint256 public totalEcosystemTokensCommitted;
struct Holding {
uint256 tokensCommitted;
uint256 tokensRemaining;
uint256 startTime;
}
event EcosystemVestingInitialized(address _to, uint256 _tokens, uint256 _startTime);
event EcosystemVestingUpdated(address _to, uint256 _totalTokens, uint256 _startTime);
function claimTokens(address beneficiary)
external
onlyOwner
returns (uint256 tokensToClaim)
{
uint256 tokensRemaining = holdings[beneficiary].tokensRemaining;
uint256 startTime = holdings[beneficiary].startTime;
require(tokensRemaining > 0, "All tokens claimed");
if (now.sub(startTime) >= MaximumHoldingPeriod) {
tokensToClaim = tokensRemaining;
delete holdings[beneficiary];
} else {
uint256 permill = calculatePermillToRelease(startTime);
uint256 tokensNotToClaim = (holdings[beneficiary].tokensCommitted.mul(1000 - permill)).div(1000);
tokensToClaim = tokensRemaining.sub(tokensNotToClaim);
tokensRemaining = tokensNotToClaim;
holdings[beneficiary].tokensRemaining = tokensRemaining;
}
}
function calculatePermillToRelease(uint256 _startTime) internal view returns (uint256 permill) {
// how many 90 day periods have passed
uint periodsPassed = ((now.sub(_startTime)).div(Interval)).add(1);
permill = periodsPassed.mul(125); // 125 per thousand to be released every 90 days
}
function initializeVesting(
address _beneficiary,
uint256 _tokens,
uint256 _startTime
)
external
onlyOwner
{
totalEcosystemTokensCommitted = totalEcosystemTokensCommitted.add(_tokens);
require(totalEcosystemTokensCommitted <= EcosystemCap);
if (holdings[_beneficiary].tokensCommitted != 0) {
holdings[_beneficiary].tokensCommitted = holdings[_beneficiary].tokensCommitted.add(_tokens);
holdings[_beneficiary].tokensRemaining = holdings[_beneficiary].tokensRemaining.add(_tokens);
emit EcosystemVestingUpdated(
_beneficiary,
holdings[_beneficiary].tokensRemaining,
holdings[_beneficiary].startTime
);
} else {
holdings[_beneficiary] = Holding(
_tokens,
_tokens,
_startTime
);
emit EcosystemVestingInitialized(_beneficiary, _tokens, _startTime);
}
}
}
contract SeedPrivateAdvisorVesting is Ownable {
using SafeMath for uint256;
enum User { Public, Seed, Private, Advisor }
mapping (address => Holding) public holdings;
uint256 constant public MinimumHoldingPeriod = 90 days;
uint256 constant public Interval = 30 days;
uint256 constant public MaximumHoldingPeriod = 180 days;
uint256 constant public SeedCap = 28000000 ether; // 28 million tokens
uint256 constant public PrivateCap = 9000000 ether; // 9 million tokens
uint256 constant public AdvisorCap = 7400000 ether; // 7.4 million tokens
uint256 public totalSeedTokensCommitted;
uint256 public totalPrivateTokensCommitted;
uint256 public totalAdvisorTokensCommitted;
struct Holding {
uint256 tokensCommitted;
uint256 tokensRemaining;
uint256 startTime;
User user;
}
event VestingInitialized(address _to, uint256 _tokens, uint256 _startTime, User user);
event VestingUpdated(address _to, uint256 _totalTokens, uint256 _startTime, User user);
function claimTokens(address beneficiary)
external
onlyOwner
returns (uint256 tokensToClaim)
{
uint256 tokensRemaining = holdings[beneficiary].tokensRemaining;
uint256 startTime = holdings[beneficiary].startTime;
require(tokensRemaining > 0, "All tokens claimed");
require(now.sub(startTime) > MinimumHoldingPeriod, "Claiming period not started yet");
if (now.sub(startTime) >= MaximumHoldingPeriod) {
tokensToClaim = tokensRemaining;
delete holdings[beneficiary];
} else {
uint256 percentage = calculatePercentageToRelease(startTime);
uint256 tokensNotToClaim = (holdings[beneficiary].tokensCommitted.mul(100 - percentage)).div(100);
tokensToClaim = tokensRemaining.sub(tokensNotToClaim);
tokensRemaining = tokensNotToClaim;
holdings[beneficiary].tokensRemaining = tokensRemaining;
}
}
function calculatePercentageToRelease(uint256 _startTime) internal view returns (uint256 percentage) {
// how many 30 day periods have passed
uint periodsPassed = ((now.sub(_startTime.add(MinimumHoldingPeriod))).div(Interval)).add(1);
percentage = periodsPassed.mul(25); // 25% to be released every 30 days
}
function initializeVesting(
address _beneficiary,
uint256 _tokens,
uint256 _startTime,
uint8 user
)
external
onlyOwner
{
User _user;
if (user == uint8(User.Seed)) {
_user = User.Seed;
totalSeedTokensCommitted = totalSeedTokensCommitted.add(_tokens);
require(totalSeedTokensCommitted <= SeedCap);
} else if (user == uint8(User.Private)) {
_user = User.Private;
totalPrivateTokensCommitted = totalPrivateTokensCommitted.add(_tokens);
require(totalPrivateTokensCommitted <= PrivateCap);
} else if (user == uint8(User.Advisor)) {
_user = User.Advisor;
totalAdvisorTokensCommitted = totalAdvisorTokensCommitted.add(_tokens);
require(totalAdvisorTokensCommitted <= AdvisorCap);
} else {
revert( "incorrect category, not eligible for vesting" );
}
if (holdings[_beneficiary].tokensCommitted != 0) {
holdings[_beneficiary].tokensCommitted = holdings[_beneficiary].tokensCommitted.add(_tokens);
holdings[_beneficiary].tokensRemaining = holdings[_beneficiary].tokensRemaining.add(_tokens);
emit VestingUpdated(
_beneficiary,
holdings[_beneficiary].tokensRemaining,
holdings[_beneficiary].startTime,
holdings[_beneficiary].user
);
} else {
holdings[_beneficiary] = Holding(
_tokens,
_tokens,
_startTime,
_user
);
emit VestingInitialized(_beneficiary, _tokens, _startTime, _user);
}
}
}
contract TeamVesting is Ownable {
using SafeMath for uint256;
mapping (address => Holding) public holdings;
uint256 constant public MinimumHoldingPeriod = 180 days;
uint256 constant public Interval = 180 days;
uint256 constant public MaximumHoldingPeriod = 720 days;
uint256 constant public TeamCap = 12200000 ether; // 12.2 million tokens
uint256 public totalTeamTokensCommitted;
struct Holding {
uint256 tokensCommitted;
uint256 tokensRemaining;
uint256 startTime;
}
event TeamVestingInitialized(address _to, uint256 _tokens, uint256 _startTime);
event TeamVestingUpdated(address _to, uint256 _totalTokens, uint256 _startTime);
function claimTokens(address beneficiary)
external
onlyOwner
returns (uint256 tokensToClaim)
{
uint256 tokensRemaining = holdings[beneficiary].tokensRemaining;
uint256 startTime = holdings[beneficiary].startTime;
require(tokensRemaining > 0, "All tokens claimed");
require(now.sub(startTime) > MinimumHoldingPeriod, "Claiming period not started yet");
if (now.sub(startTime) >= MaximumHoldingPeriod) {
tokensToClaim = tokensRemaining;
delete holdings[beneficiary];
} else {
uint256 percentage = calculatePercentageToRelease(startTime);
uint256 tokensNotToClaim = (holdings[beneficiary].tokensCommitted.mul(100 - percentage)).div(100);
tokensToClaim = tokensRemaining.sub(tokensNotToClaim);
tokensRemaining = tokensNotToClaim;
holdings[beneficiary].tokensRemaining = tokensRemaining;
}
}
function calculatePercentageToRelease(uint256 _startTime) internal view returns (uint256 percentage) {
// how many 180 day periods have passed
uint periodsPassed = ((now.sub(_startTime)).div(Interval));
percentage = periodsPassed.mul(25); // 25% to be released every 180 days
}
function initializeVesting(
address _beneficiary,
uint256 _tokens,
uint256 _startTime
)
external
onlyOwner
{
totalTeamTokensCommitted = totalTeamTokensCommitted.add(_tokens);
require(totalTeamTokensCommitted <= TeamCap);
if (holdings[_beneficiary].tokensCommitted != 0) {
holdings[_beneficiary].tokensCommitted = holdings[_beneficiary].tokensCommitted.add(_tokens);
holdings[_beneficiary].tokensRemaining = holdings[_beneficiary].tokensRemaining.add(_tokens);
emit TeamVestingUpdated(
_beneficiary,
holdings[_beneficiary].tokensRemaining,
holdings[_beneficiary].startTime
);
} else {
holdings[_beneficiary] = Holding(
_tokens,
_tokens,
_startTime
);
emit TeamVestingInitialized(_beneficiary, _tokens, _startTime);
}
}
}
interface TokenInterface {
function totalSupply() external view returns (uint256);
function balanceOf(address _owner) external view returns (uint256 balance);
function transfer(address _to, uint256 _value) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract Vesting is Ownable {
using SafeMath for uint256;
enum VestingUser { Public, Seed, Private, Advisor, Team, Community, Ecosystem }
TokenInterface public token;
CommunityVesting public communityVesting;
TeamVesting public teamVesting;
EcosystemVesting public ecosystemVesting;
SeedPrivateAdvisorVesting public seedPrivateAdvisorVesting;
mapping (address => VestingUser) public userCategory;
uint256 public totalAllocated;
event TokensReleased(address _to, uint256 _tokensReleased, VestingUser user);
constructor(address _token) public {
//require(_token != 0x0, "Invalid address");
token = TokenInterface(_token);
communityVesting = new CommunityVesting();
teamVesting = new TeamVesting();
ecosystemVesting = new EcosystemVesting();
seedPrivateAdvisorVesting = new SeedPrivateAdvisorVesting();
}
function claimTokens() external {
uint8 category = uint8(userCategory[msg.sender]);
uint256 tokensToClaim;
if (category == 1 || category == 2 || category == 3) {
tokensToClaim = seedPrivateAdvisorVesting.claimTokens(msg.sender);
} else if (category == 4) {
tokensToClaim = teamVesting.claimTokens(msg.sender);
} else if (category == 5) {
tokensToClaim = communityVesting.claimTokens(msg.sender);
} else if (category == 6){
tokensToClaim = ecosystemVesting.claimTokens(msg.sender);
} else {
revert( "incorrect category, maybe unknown user" );
}
totalAllocated = totalAllocated.sub(tokensToClaim);
require(token.transfer(msg.sender, tokensToClaim), "Insufficient balance in vesting contract");
emit TokensReleased(msg.sender, tokensToClaim, userCategory[msg.sender]);
}
function initializeVesting(
address _beneficiary,
uint256 _tokens,
uint256 _startTime,
VestingUser user
)
external
onlyOwner
{
uint8 category = uint8(user);
require(category != 0, "Not eligible for vesting");
require( uint8(userCategory[_beneficiary]) == 0 || userCategory[_beneficiary] == user, "cannot change user category" );
userCategory[_beneficiary] = user;
totalAllocated = totalAllocated.add(_tokens);
if (category == 1 || category == 2 || category == 3) {
seedPrivateAdvisorVesting.initializeVesting(_beneficiary, _tokens, _startTime, category);
} else if (category == 4) {
teamVesting.initializeVesting(_beneficiary, _tokens, _startTime);
} else if (category == 5) {
communityVesting.initializeVesting(_beneficiary, _tokens, _startTime);
} else if (category == 6){
ecosystemVesting.initializeVesting(_beneficiary, _tokens, _startTime);
} else {
revert( "incorrect category, not eligible for vesting" );
}
}
function claimUnallocated( address _sendTo) external onlyOwner{
uint256 allTokens = token.balanceOf(address(this));
uint256 tokensUnallocated = allTokens.sub(totalAllocated);
token.transfer(_sendTo, tokensUnallocated);
}
}
contract MintableAndPausableToken is ERC20Pausable, Ownable {
uint8 public constant decimals = 18;
uint256 public maxTokenSupply = 183500000 * 10 ** uint256(decimals);
bool public mintingFinished = false;
event Mint(address indexed to, uint256 amount);
event MintFinished();
event MintStarted();
modifier canMint() {
require(!mintingFinished);
_;
}
modifier checkMaxSupply(uint256 _amount) {
require(maxTokenSupply >= totalSupply().add(_amount));
_;
}
modifier cannotMint() {
require(mintingFinished);
_;
}
function mint(address _to, uint256 _amount)
external
onlyOwner
canMint
checkMaxSupply (_amount)
whenNotPaused
returns (bool)
{
super._mint(_to, _amount);
return true;
}
function _mint(address _to, uint256 _amount)
internal
canMint
checkMaxSupply (_amount)
{
super._mint(_to, _amount);
}
function finishMinting() external onlyOwner canMint returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
function startMinting() external onlyOwner cannotMint returns (bool) {
mintingFinished = false;
emit MintStarted();
return true;
}
}
/**
* Token upgrader interface inspired by Lunyr.
*
* Token upgrader transfers previous version tokens to a newer version.
* Token upgrader itself can be the token contract, or just a middle man contract doing the heavy lifting.
*/
contract TokenUpgrader {
uint public originalSupply;
/** Interface marker */
function isTokenUpgrader() external pure returns (bool) {
return true;
}
function upgradeFrom(address _from, uint256 _value) public;
}
contract UpgradeableToken is MintableAndPausableToken {
// Contract or person who can set the upgrade path.
address public upgradeMaster;
// Bollean value needs to be true to start upgrades
bool private upgradesAllowed;
// The next contract where the tokens will be migrated.
TokenUpgrader public tokenUpgrader;
// How many tokens we have upgraded by now.
uint public totalUpgraded;
/**
* Upgrade states.
* - NotAllowed: The child contract has not reached a condition where the upgrade can begin
* - Waiting: Token allows upgrade, but we don't have a new token version
* - ReadyToUpgrade: The token version is set, but not a single token has been upgraded yet
* - Upgrading: Token upgrader is set and the balance holders can upgrade their tokens
*/
enum UpgradeState { NotAllowed, Waiting, ReadyToUpgrade, Upgrading }
// Somebody has upgraded some of his tokens.
event Upgrade(address indexed _from, address indexed _to, uint256 _value);
// New token version available.
event TokenUpgraderIsSet(address _newToken);
modifier onlyUpgradeMaster {
// Only a master can designate the next token
require(msg.sender == upgradeMaster);
_;
}
modifier notInUpgradingState {
// Upgrade has already begun for token
require(getUpgradeState() != UpgradeState.Upgrading);
_;
}
// Do not allow construction without upgrade master set.
constructor(address _upgradeMaster) public {
upgradeMaster = _upgradeMaster;
}
// set a token upgrader
function setTokenUpgrader(address _newToken)
external
onlyUpgradeMaster
notInUpgradingState
{
require(canUpgrade());
require(_newToken != address(0));
tokenUpgrader = TokenUpgrader(_newToken);
// Handle bad interface
require(tokenUpgrader.isTokenUpgrader());
// Make sure that token supplies match in source and target
require(tokenUpgrader.originalSupply() == totalSupply());
emit TokenUpgraderIsSet(address(tokenUpgrader));
}
// Allow the token holder to upgrade some of their tokens to a new contract.
function upgrade(uint _value) external {
UpgradeState state = getUpgradeState();
// Check upgrate state
require(state == UpgradeState.ReadyToUpgrade || state == UpgradeState.Upgrading);
// Validate input value
require(_value != 0);
//balances[msg.sender] = balances[msg.sender].sub(_value);
// Take tokens out from circulation
//totalSupply_ = totalSupply_.sub(_value);
//the _burn method emits the Transfer event
_burn(msg.sender, _value);
totalUpgraded = totalUpgraded.add(_value);
// Token Upgrader reissues the tokens
tokenUpgrader.upgradeFrom(msg.sender, _value);
emit Upgrade(msg.sender, address(tokenUpgrader), _value);
}
/**
* Change the upgrade master.
* This allows us to set a new owner for the upgrade mechanism.
*/
function setUpgradeMaster(address _newMaster) external onlyUpgradeMaster {
require(_newMaster != address(0));
upgradeMaster = _newMaster;
}
// To be overriden to add functionality
function allowUpgrades() external onlyUpgradeMaster () {
upgradesAllowed = true;
}
// To be overriden to add functionality
function rejectUpgrades() external onlyUpgradeMaster () {
require(!(totalUpgraded > 0));
upgradesAllowed = false;
}
// Get the state of the token upgrade.
function getUpgradeState() public view returns(UpgradeState) {
if (!canUpgrade()) return UpgradeState.NotAllowed;
else if (address(tokenUpgrader) == address(0)) return UpgradeState.Waiting;
else if (totalUpgraded == 0) return UpgradeState.ReadyToUpgrade;
else return UpgradeState.Upgrading;
}
// To be overriden to add functionality
function canUpgrade() public view returns(bool) {
return upgradesAllowed;
}
}
contract Token is UpgradeableToken, ERC20Burnable {
string public name;
string public symbol;
// For patient incentive programs
uint256 public INITIAL_SUPPLY;
uint256 public hodlPremiumCap;
uint256 public hodlPremiumMinted;
// After 180 days you get a constant maximum bonus of 25% of tokens transferred
// Before that it is spread out linearly(from 0% to 25%) starting from the
// contribution time till 180 days after that
uint256 constant maxBonusDuration = 180 days;
struct Bonus {
uint256 hodlTokens;
uint256 contributionTime;
uint256 buybackTokens;
}
mapping( address => Bonus ) public hodlPremium;
IERC20 stablecoin;
address stablecoinPayer;
uint256 public signupWindowStart;
uint256 public signupWindowEnd;
uint256 public refundWindowStart;
uint256 public refundWindowEnd;
event UpdatedTokenInformation(string newName, string newSymbol);
event HodlPremiumSet(address beneficiary, uint256 tokens, uint256 contributionTime);
event HodlPremiumCapSet(uint256 newhodlPremiumCap);
event RegisteredForRefund( address holder, uint256 tokens );
constructor (address _litWallet, address _upgradeMaster, uint256 _INITIAL_SUPPLY, uint256 _hodlPremiumCap)
public
UpgradeableToken(_upgradeMaster)
Ownable()
{
require(maxTokenSupply >= _INITIAL_SUPPLY.mul(10 ** uint256(decimals)));
INITIAL_SUPPLY = _INITIAL_SUPPLY.mul(10 ** uint256(decimals));
setHodlPremiumCap(_hodlPremiumCap) ;
_mint(_litWallet, INITIAL_SUPPLY);
}
/**
* Owner can update token information here
*/
function setTokenInformation(string calldata _name, string calldata _symbol) external onlyOwner {
name = _name;
symbol = _symbol;
emit UpdatedTokenInformation(name, symbol);
}
function setRefundSignupDetails( uint256 _startTime, uint256 _endTime, ERC20 _stablecoin, address _payer ) public onlyOwner {
require( _startTime < _endTime );
stablecoin = _stablecoin;
stablecoinPayer = _payer;
signupWindowStart = _startTime;
signupWindowEnd = _endTime;
refundWindowStart = signupWindowStart + 182 days;
refundWindowEnd = signupWindowEnd + 182 days;
require( refundWindowStart > signupWindowEnd);
}
function signUpForRefund( uint256 _value ) public {
require( hodlPremium[msg.sender].hodlTokens != 0 || hodlPremium[msg.sender].buybackTokens != 0, "You must be ICO user to sign up" ); //the user was registered in ICO
require( block.timestamp >= signupWindowStart&& block.timestamp <= signupWindowEnd, "Cannot sign up at this time" );
uint256 value = _value;
value = value.add(hodlPremium[msg.sender].buybackTokens);
if( value > balanceOf(msg.sender)) //cannot register more than he or she has; since refund has to happen while token is paused, we don't need to check anything else
value = balanceOf(msg.sender);
hodlPremium[ msg.sender].buybackTokens = value;
//buyback cancels hodl highway
if( hodlPremium[msg.sender].hodlTokens > 0 ){
hodlPremium[msg.sender].hodlTokens = 0;
emit HodlPremiumSet( msg.sender, 0, hodlPremium[msg.sender].contributionTime );
}
emit RegisteredForRefund(msg.sender, value);
}
function refund( uint256 _value ) public {
require( block.timestamp >= refundWindowStart && block.timestamp <= refundWindowEnd, "cannot refund now" );
require( hodlPremium[msg.sender].buybackTokens >= _value, "not enough tokens in refund program" );
require( balanceOf(msg.sender) >= _value, "not enough tokens" ); //this check is probably redundant to those in _burn, but better check twice
hodlPremium[msg.sender].buybackTokens = hodlPremium[msg.sender].buybackTokens.sub(_value);
_burn( msg.sender, _value );
require( stablecoin.transferFrom( stablecoinPayer, msg.sender, _value.div(20) ), "transfer failed" ); //we pay 1/20 = 0.05 DAI for 1 LIT
}
function setHodlPremiumCap(uint256 newhodlPremiumCap) public onlyOwner {
require(newhodlPremiumCap > 0);
hodlPremiumCap = newhodlPremiumCap;
emit HodlPremiumCapSet(hodlPremiumCap);
}
/**
* Owner can burn token here
*/
function burn(uint256 _value) public onlyOwner {
super.burn(_value);
}
function sethodlPremium(
address beneficiary,
uint256 value,
uint256 contributionTime
)
public
onlyOwner
returns (bool)
{
require(beneficiary != address(0) && value > 0 && contributionTime > 0, "Not eligible for HODL Premium");
if (hodlPremium[beneficiary].hodlTokens != 0) {
hodlPremium[beneficiary].hodlTokens = hodlPremium[beneficiary].hodlTokens.add(value);
emit HodlPremiumSet(beneficiary, hodlPremium[beneficiary].hodlTokens, hodlPremium[beneficiary].contributionTime);
} else {
hodlPremium[beneficiary] = Bonus(value, contributionTime, 0);
emit HodlPremiumSet(beneficiary, value, contributionTime);
}
return true;
}
function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) {
require(_to != address(0));
require(_value <= balanceOf(msg.sender));
if (hodlPremiumMinted < hodlPremiumCap && hodlPremium[msg.sender].hodlTokens > 0) {
uint256 amountForBonusCalculation = calculateAmountForBonus(msg.sender, _value);
uint256 bonus = calculateBonus(msg.sender, amountForBonusCalculation);
//subtract the tokens token into account here to avoid the above calculations in the future, e.g. in case I withdraw everything in 0 days (bonus 0), and then refund, I shall not be eligible for any bonuses
hodlPremium[msg.sender].hodlTokens = hodlPremium[msg.sender].hodlTokens.sub(amountForBonusCalculation);
if ( bonus > 0) {
//balances[msg.sender] = balances[msg.sender].add(bonus);
_mint( msg.sender, bonus );
//emit Transfer(address(0), msg.sender, bonus);
}
}
ERC20Pausable.transfer( _to, _value );
// balances[msg.sender] = balances[msg.sender].sub(_value);
// balances[_to] = balances[_to].add(_value);
// emit Transfer(msg.sender, _to, _value);
//TODO: optimize to avoid setting values outside of buyback window
if( balanceOf(msg.sender) < hodlPremium[msg.sender].buybackTokens )
hodlPremium[msg.sender].buybackTokens = balanceOf(msg.sender);
return true;
}
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
whenNotPaused
returns (bool)
{
require(_to != address(0));
if (hodlPremiumMinted < hodlPremiumCap && hodlPremium[_from].hodlTokens > 0) {
uint256 amountForBonusCalculation = calculateAmountForBonus(_from, _value);
uint256 bonus = calculateBonus(_from, amountForBonusCalculation);
//subtract the tokens token into account here to avoid the above calculations in the future, e.g. in case I withdraw everything in 0 days (bonus 0), and then refund, I shall not be eligible for any bonuses
hodlPremium[_from].hodlTokens = hodlPremium[_from].hodlTokens.sub(amountForBonusCalculation);
if ( bonus > 0) {
//balances[_from] = balances[_from].add(bonus);
_mint( _from, bonus );
//emit Transfer(address(0), _from, bonus);
}
}
ERC20Pausable.transferFrom( _from, _to, _value);
if( balanceOf(_from) < hodlPremium[_from].buybackTokens )
hodlPremium[_from].buybackTokens = balanceOf(_from);
return true;
}
function calculateBonus(address beneficiary, uint256 amount) internal returns (uint256) {
uint256 bonusAmount;
uint256 contributionTime = hodlPremium[beneficiary].contributionTime;
uint256 bonusPeriod;
if (now <= contributionTime) {
bonusPeriod = 0;
} else if (now.sub(contributionTime) >= maxBonusDuration) {
bonusPeriod = maxBonusDuration;
} else {
bonusPeriod = now.sub(contributionTime);
}
if (bonusPeriod != 0) {
bonusAmount = (((bonusPeriod.mul(amount)).div(maxBonusDuration)).mul(25)).div(100);
if (hodlPremiumMinted.add(bonusAmount) > hodlPremiumCap) {
bonusAmount = hodlPremiumCap.sub(hodlPremiumMinted);
hodlPremiumMinted = hodlPremiumCap;
} else {
hodlPremiumMinted = hodlPremiumMinted.add(bonusAmount);
}
if( totalSupply().add(bonusAmount) > maxTokenSupply )
bonusAmount = maxTokenSupply.sub(totalSupply());
}
return bonusAmount;
}
function calculateAmountForBonus(address beneficiary, uint256 _value) internal view returns (uint256) {
uint256 amountForBonusCalculation;
if(_value >= hodlPremium[beneficiary].hodlTokens) {
amountForBonusCalculation = hodlPremium[beneficiary].hodlTokens;
} else {
amountForBonusCalculation = _value;
}
return amountForBonusCalculation;
}
}
contract TestToken is ERC20{
constructor ( uint256 _balance)public {
_mint(msg.sender, _balance);
}
}
contract BaseCrowdsale is Pausable, Ownable {
using SafeMath for uint256;
Whitelisting public whitelisting;
Token public token;
struct Contribution {
address payable contributor;
uint256 weiAmount;
uint256 contributionTime;
bool tokensAllocated;
}
mapping (uint256 => Contribution) public contributions;
uint256 public contributionIndex;
uint256 public startTime;
uint256 public endTime;
address payable public wallet;
uint256 public weiRaised;
uint256 public tokenRaised;
event TokenPurchase(
address indexed purchaser,
address indexed beneficiary,
uint256 value,
uint256 amount
);
event RecordedContribution(
uint256 indexed index,
address indexed contributor,
uint256 weiAmount,
uint256 time
);
event TokenOwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
modifier allowedUpdate(uint256 time) {
require(time > now);
_;
}
modifier checkZeroAddress(address _add) {
require(_add != address(0));
_;
}
constructor(
uint256 _startTime,
uint256 _endTime,
address payable _wallet,
Token _token,
Whitelisting _whitelisting
)
public
checkZeroAddress(_wallet)
checkZeroAddress(address(_token))
checkZeroAddress(address(_whitelisting))
{
require(_startTime >= now);
require(_endTime >= _startTime);
startTime = _startTime;
endTime = _endTime;
wallet = _wallet;
token = _token;
whitelisting = _whitelisting;
}
function () external payable {
buyTokens(msg.sender);
}
function transferTokenOwnership(address newOwner)
external
onlyOwner
checkZeroAddress(newOwner)
{
emit TokenOwnershipTransferred(owner(), newOwner);
token.transferOwnership(newOwner);
}
function setWallet(address payable _wallet)
external
onlyOwner
checkZeroAddress(_wallet)
{
wallet = _wallet;
}
function setStartTime(uint256 _newStartTime)
external
onlyOwner
allowedUpdate(_newStartTime)
{
require(startTime > now);
require(_newStartTime < endTime);
startTime = _newStartTime;
}
function setEndTime(uint256 _newEndTime)
external
onlyOwner
allowedUpdate(_newEndTime)
{
require(endTime > now);
require(_newEndTime > startTime);
endTime = _newEndTime;
}
function hasEnded() public view returns (bool) {
return now > endTime;
}
function buyTokens(address payable beneficiary)
internal
whenNotPaused
checkZeroAddress(beneficiary)
{
require(validPurchase());
require(whitelisting.isInvestorPaymentApproved(beneficiary));
contributions[contributionIndex].contributor = beneficiary;
contributions[contributionIndex].weiAmount = msg.value;
contributions[contributionIndex].contributionTime = now;
weiRaised = weiRaised.add(contributions[contributionIndex].weiAmount);
emit RecordedContribution(
contributionIndex,
contributions[contributionIndex].contributor,
contributions[contributionIndex].weiAmount,
contributions[contributionIndex].contributionTime
);
contributionIndex++;
forwardFunds();
}
function validPurchase() internal view returns (bool) {
bool withinPeriod = now >= startTime && now <= endTime;
bool nonZeroPurchase = msg.value != 0;
return withinPeriod && nonZeroPurchase;
}
function forwardFunds() internal {
wallet.transfer(msg.value);
}
}
contract RefundVault is Ownable {
enum State { Refunding, Closed }
address payable public wallet;
State public state;
event Closed();
event RefundsEnabled();
event Refunded(address indexed beneficiary, uint256 weiAmount);
constructor(address payable _wallet) public {
require(_wallet != address(0));
wallet = _wallet;
state = State.Refunding;
emit RefundsEnabled();
}
function deposit() public onlyOwner payable {
require(state == State.Refunding);
}
function close() public onlyOwner {
require(state == State.Refunding);
state = State.Closed;
emit Closed();
wallet.transfer(address(this).balance);
}
function refund(address payable investor, uint256 depositedValue) public onlyOwner {
require(state == State.Refunding);
investor.transfer(depositedValue);
emit Refunded(investor, depositedValue);
}
}
contract TokenCapRefund is BaseCrowdsale {
RefundVault public vault;
uint256 public refundClosingTime;
modifier waitingTokenAllocation(uint256 index) {
require(!contributions[index].tokensAllocated);
_;
}
modifier greaterThanZero(uint256 value) {
require(value > 0);
_;
}
constructor(uint256 _refundClosingTime) public {
vault = new RefundVault(wallet);
require(_refundClosingTime > endTime);
refundClosingTime = _refundClosingTime;
}
function closeRefunds() external onlyOwner {
require(now > refundClosingTime);
vault.close();
}
function refundContribution(uint256 index)
external
onlyOwner
waitingTokenAllocation(index)
{
vault.refund(contributions[index].contributor, contributions[index].weiAmount);
weiRaised = weiRaised.sub(contributions[index].weiAmount);
delete contributions[index];
}
function setRefundClosingTime(uint256 _newRefundClosingTime)
external
onlyOwner
allowedUpdate(_newRefundClosingTime)
{
require(refundClosingTime > now);
require(_newRefundClosingTime > endTime);
refundClosingTime = _newRefundClosingTime;
}
function forwardFunds() internal {
vault.deposit.value(msg.value)();
}
}
contract TokenCapCrowdsale is BaseCrowdsale {
uint256 public tokenCap;
uint256 public individualCap;
uint256 public totalSupply;
modifier greaterThanZero(uint256 value) {
require(value > 0);
_;
}
constructor (uint256 _cap, uint256 _individualCap)
public
greaterThanZero(_cap)
greaterThanZero(_individualCap)
{
syncTotalSupply();
require(totalSupply < _cap);
tokenCap = _cap;
individualCap = _individualCap;
}
function setIndividualCap(uint256 _newIndividualCap)
external
onlyOwner
{
individualCap = _newIndividualCap;
}
function setTokenCap(uint256 _newTokenCap)
external
onlyOwner
{
tokenCap = _newTokenCap;
}
function hasEnded() public view returns (bool) {
bool tokenCapReached = totalSupply >= tokenCap;
return tokenCapReached || super.hasEnded();
}
function checkAndUpdateSupply(uint256 newSupply) internal returns (bool) {
totalSupply = newSupply;
return tokenCap >= totalSupply;
}
function withinIndividualCap(uint256 _tokens) internal view returns (bool) {
return individualCap >= _tokens;
}
function syncTotalSupply() internal {
totalSupply = token.totalSupply();
}
}
contract PrivateSale is TokenCapCrowdsale, TokenCapRefund {
Vesting public vesting;
mapping (address => uint256) public tokensVested;
uint256 hodlStartTime;
constructor (
uint256 _startTime,
uint256 _endTime,
address payable _wallet,
Whitelisting _whitelisting,
Token _token,
Vesting _vesting,
uint256 _refundClosingTime,
uint256 _refundClosingTokenCap,
uint256 _tokenCap,
uint256 _individualCap
)
public
TokenCapCrowdsale(_tokenCap, _individualCap)
TokenCapRefund(_refundClosingTime)
BaseCrowdsale(_startTime, _endTime, _wallet, _token, _whitelisting)
{
_refundClosingTokenCap; //silence compiler warning
require( address(_vesting) != address(0), "Invalid address");
vesting = _vesting;
}
function allocateTokens(uint256 index, uint256 tokens)
external
onlyOwner
waitingTokenAllocation(index)
{
address contributor = contributions[index].contributor;
require(now >= endTime);
require(whitelisting.isInvestorApproved(contributor));
require(checkAndUpdateSupply(totalSupply.add(tokens)));
uint256 alreadyExistingTokens = token.balanceOf(contributor);
require(withinIndividualCap(tokens.add(alreadyExistingTokens)));
contributions[index].tokensAllocated = true;
tokenRaised = tokenRaised.add(tokens);
token.mint(contributor, tokens);
token.sethodlPremium(contributor, tokens, hodlStartTime);
emit TokenPurchase(
msg.sender,
contributor,
contributions[index].weiAmount,
tokens
);
}
function vestTokens(address[] calldata beneficiary, uint256[] calldata tokens, uint8[] calldata userType) external onlyOwner {
require(beneficiary.length == tokens.length && tokens.length == userType.length);
uint256 length = beneficiary.length;
for(uint i = 0; i<length; i++) {
require(beneficiary[i] != address(0), "Invalid address");
require(now >= endTime);
require(checkAndUpdateSupply(totalSupply.add(tokens[i])));
tokensVested[beneficiary[i]] = tokensVested[beneficiary[i]].add(tokens[i]);
require(withinIndividualCap(tokensVested[beneficiary[i]]));
tokenRaised = tokenRaised.add(tokens[i]);
token.mint(address(vesting), tokens[i]);
Vesting(vesting).initializeVesting(beneficiary[i], tokens[i], now, Vesting.VestingUser(userType[i]));
}
}
function ownerAssignedTokens(address beneficiary, uint256 tokens)
external
onlyOwner
{
require(now >= endTime);
require(whitelisting.isInvestorApproved(beneficiary));
require(checkAndUpdateSupply(totalSupply.add(tokens)));
uint256 alreadyExistingTokens = token.balanceOf(beneficiary);
require(withinIndividualCap(tokens.add(alreadyExistingTokens)));
tokenRaised = tokenRaised.add(tokens);
token.mint(beneficiary, tokens);
token.sethodlPremium(beneficiary, tokens, hodlStartTime);
emit TokenPurchase(
msg.sender,
beneficiary,
0,
tokens
);
}
function setHodlStartTime(uint256 _hodlStartTime) onlyOwner external{
hodlStartTime = _hodlStartTime;
}
} | how many 30 day periods have passed | function calculatePercentageToRelease(uint256 _startTime) internal view returns (uint256 percentage) {
uint periodsPassed = ((now.sub(_startTime.add(MinimumHoldingPeriod))).div(Interval)).add(1);
}
| 933,255 |
./full_match/1/0x0b48549292B364dA14e6AcB5c18e143491B8f5A7/sources/browser/ERCIndex_flat.sol | will sell percent of each token and send DAI to _receiver | function _sellPercentOfIndexForDai(uint _percent, address _receiver) internal {
for (uint i = 0; i < topTokensLength(); i++) {
uint tokenBalance = topTokens[i].balanceOf(address(this));
if (tokenBalance > 0) {
_sellERCToken(topTokens[i], sellAmount, _receiver);
}
}
}
| 3,875,489 |
// SPDX-License-Identifier: None
pragma solidity ^0.8.0;
import "Ownable.sol";
import "TransparentUpgradeableProxy.sol";
/**
* @notice This is the contract that will have administrative privileges on all Halborn proxied
* products.
*/
contract HalbornProxyAdmin is Ownable {
constructor(address owner) {
_transferOwnership(owner);
}
/**
* @dev Returns the current implementation of `proxy`.
*
* Requirements:
*
* - This contract must be the admin of `proxy`.
*/
function getProxyImplementation(TransparentUpgradeableProxy proxy) public view returns (address) {
// We need to manually run the static call since the getter cannot be flagged as view
// bytes4(keccak256("implementation()")) == 0x5c60da1b
(bool success, bytes memory returndata) = address(proxy).staticcall(hex"5c60da1b");
require(success);
return abi.decode(returndata, (address));
}
/**
* @dev Returns the current admin of `proxy`.
*
* Requirements:
*
* - This contract must be the admin of `proxy`.
*/
function getProxyAdmin(TransparentUpgradeableProxy proxy) public view returns (address) {
// We need to manually run the static call since the getter cannot be flagged as view
// bytes4(keccak256("admin()")) == 0xf851a440
(bool success, bytes memory returndata) = address(proxy).staticcall(hex"f851a440");
require(success);
return abi.decode(returndata, (address));
}
/**
* @dev Changes the admin of `proxy` to `newAdmin`.
*
* Requirements:
*
* - This contract must be the current admin of `proxy`.
*/
function changeProxyAdmin(TransparentUpgradeableProxy proxy, address newAdmin) public onlyOwner {
proxy.changeAdmin(newAdmin);
}
/**
* @dev Upgrades `proxy` to `implementation`. See {TransparentUpgradeableProxy-upgradeTo}.
*
* Requirements:
*
* - This contract must be the admin of `proxy`.
*/
function upgrade(TransparentUpgradeableProxy proxy, address implementation) public onlyOwner {
proxy.upgradeTo(implementation);
}
/**
* @dev Upgrades `proxy` to `implementation` and calls a function on the new implementation. See
* {TransparentUpgradeableProxy-upgradeToAndCall}.
*
* Requirements:
*
* - This contract must be the admin of `proxy`.
*/
function upgradeAndCall(TransparentUpgradeableProxy proxy, address implementation, bytes memory data) public payable onlyOwner {
proxy.upgradeToAndCall{value: msg.value}(implementation, data);
}
}
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}. EDIT: Not on this implementation
* the {_transferOwnership} method must be called during the initialization of
* the contract.
*
* 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.
*
* The {renounceOwnership} method has been disabled for security purposes on Seraph
*/
abstract contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @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() == msg.sender, "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() external virtual onlyOwner {
revert("Ownable: Renounce ownership not allowed");
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) external virtual 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
pragma solidity ^0.8.0;
import "ERC1967Proxy.sol";
/**
* @dev This contract implements a proxy that is upgradeable by an admin.
*
* To avoid https://medium.com/nomic-labs-blog/malicious-backdoors-in-ethereum-proxies-62629adf3357[proxy selector
* clashing], which can potentially be used in an attack, this contract uses the
* https://blog.openzeppelin.com/the-transparent-proxy-pattern/[transparent proxy pattern]. This pattern implies two
* things that go hand in hand:
*
* 1. If any account other than the admin calls the proxy, the call will be forwarded to the implementation, even if
* that call matches one of the admin functions exposed by the proxy itself.
* 2. If the admin calls the proxy, it can access the admin functions, but its calls will never be forwarded to the
* implementation. If the admin tries to call a function on the implementation it will fail with an error that says
* "admin cannot fallback to proxy target".
*
* These properties mean that the admin account can only be used for admin actions like upgrading the proxy or changing
* the admin, so it's best if it's a dedicated account that is not used for anything else. This will avoid headaches due
* to sudden errors when trying to call a function from the proxy implementation.
*
* Our recommendation is for the dedicated account to be an instance of the {ProxyAdmin} contract. If set up this way,
* you should think of the `ProxyAdmin` instance as the real administrative interface of your proxy.
*/
contract TransparentUpgradeableProxy is ERC1967Proxy {
/**
* @dev Initializes an upgradeable proxy managed by `_admin`, backed by the implementation at `_logic`, and
* optionally initialized with `_data` as explained in {ERC1967Proxy-constructor}.
*/
constructor(
address _logic,
address admin_,
bytes memory _data
) payable ERC1967Proxy(_logic, _data) {
assert(_ADMIN_SLOT == bytes32(uint256(keccak256("eip1967.proxy.admin")) - 1));
_changeAdmin(admin_);
}
/**
* @dev Modifier used internally that will delegate the call to the implementation unless the sender is the admin.
*/
modifier ifAdmin() {
if (msg.sender == _getAdmin()) {
_;
} else {
_fallback();
}
}
/**
* @dev Returns the current admin.
*
* NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyAdmin}.
*
* TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the
* https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
* `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`
*/
function admin() external ifAdmin returns (address admin_) {
admin_ = _getAdmin();
}
/**
* @dev Returns the current implementation.
*
* NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyImplementation}.
*
* TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the
* https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
* `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc`
*/
function implementation() external ifAdmin returns (address implementation_) {
implementation_ = _implementation();
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {AdminChanged} event.
*
* NOTE: Only the admin can call this function. See {ProxyAdmin-changeProxyAdmin}.
*/
function changeAdmin(address newAdmin) external virtual ifAdmin {
_changeAdmin(newAdmin);
}
/**
* @dev Upgrade the implementation of the proxy.
*
* NOTE: Only the admin can call this function. See {ProxyAdmin-upgrade}.
*/
function upgradeTo(address newImplementation) external ifAdmin {
_upgradeToAndCall(newImplementation, bytes(""), false);
}
/**
* @dev Upgrade the implementation of the proxy, and then call a function from the new implementation as specified
* by `data`, which should be an encoded function call. This is useful to initialize new storage variables in the
* proxied contract.
*
* NOTE: Only the admin can call this function. See {ProxyAdmin-upgradeAndCall}.
*/
function upgradeToAndCall(address newImplementation, bytes calldata data) external payable ifAdmin {
_upgradeToAndCall(newImplementation, data, true);
}
/**
* @dev Returns the current admin.
*/
function _admin() internal view virtual returns (address) {
return _getAdmin();
}
/**
* @dev Makes sure the admin cannot access the fallback function. See {Proxy-_beforeFallback}.
*/
function _beforeFallback() internal virtual override {
require(msg.sender != _getAdmin(), "TransparentUpgradeableProxy: admin cannot fallback to proxy target");
super._beforeFallback();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "Proxy.sol";
import "ERC1967Upgrade.sol";
/**
* @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an
* implementation address that can be changed. This address is stored in storage in the location specified by
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the
* implementation behind the proxy.
*/
contract ERC1967Proxy is Proxy, ERC1967Upgrade {
/**
* @dev Initializes the upgradeable proxy with an initial implementation specified by `_logic`.
*
* If `_data` is nonempty, it's used as data in a delegate call to `_logic`. This will typically be an encoded
* function call, and allows initializating the storage of the proxy like a Solidity constructor.
*/
constructor(address _logic, bytes memory _data) payable {
assert(_IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1));
_upgradeToAndCall(_logic, _data, false);
}
/**
* @dev Returns the current implementation address.
*/
function _implementation() internal view virtual override returns (address impl) {
return ERC1967Upgrade._getImplementation();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM
* instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to
* be specified by overriding the virtual {_implementation} function.
*
* Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a
* different contract through the {_delegate} function.
*
* The success and return data of the delegated call will be returned back to the caller of the proxy.
*/
abstract contract Proxy {
/**
* @dev Delegates the current call to `implementation`.
*
* This function does not return to its internall call site, it will return directly to the external caller.
*/
function _delegate(address implementation) internal virtual {
assembly {
// Copy msg.data. We take full control of memory in this inline assembly
// block because it will not return to Solidity code. We overwrite the
// Solidity scratch pad at memory position 0.
calldatacopy(0, 0, calldatasize())
// Call the implementation.
// out and outsize are 0 because we don't know the size yet.
let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)
// Copy the returned data.
returndatacopy(0, 0, returndatasize())
switch result
// delegatecall returns 0 on error.
case 0 {
revert(0, returndatasize())
}
default {
return(0, returndatasize())
}
}
}
/**
* @dev This is a virtual function that should be overriden so it returns the address to which the fallback function
* and {_fallback} should delegate.
*/
function _implementation() internal view virtual returns (address);
/**
* @dev Delegates the current call to the address returned by `_implementation()`.
*
* This function does not return to its internall call site, it will return directly to the external caller.
*/
function _fallback() internal virtual {
_beforeFallback();
_delegate(_implementation());
}
/**
* @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other
* function in the contract matches the call data.
*/
fallback() external payable virtual {
_fallback();
}
/**
* @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data
* is empty.
*/
receive() external payable virtual {
_fallback();
}
/**
* @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback`
* call, or as part of the Solidity `fallback` or `receive` functions.
*
* If overriden should call `super._beforeFallback()`.
*/
function _beforeFallback() internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.2;
import "IBeacon.sol";
import "Address.sol";
import "StorageSlot.sol";
/**
* @dev This abstract contract provides getters and event emitting update functions for
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
*
* _Available since v4.1._
*
* @custom:oz-upgrades-unsafe-allow delegatecall
*/
abstract contract ERC1967Upgrade {
// This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1
bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Returns the current implementation address.
*/
function _getImplementation() internal view returns (address) {
return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
}
/**
* @dev Perform implementation upgrade
*
* Emits an {Upgraded} event.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Perform implementation upgrade with additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCall(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
_upgradeTo(newImplementation);
if (data.length > 0 || forceCall) {
Address.functionDelegateCall(newImplementation, data);
}
}
/**
* @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCallSecure(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
address oldImplementation = _getImplementation();
// Initial upgrade and setup call
_setImplementation(newImplementation);
if (data.length > 0 || forceCall) {
Address.functionDelegateCall(newImplementation, data);
}
// Perform rollback test if not already in progress
StorageSlot.BooleanSlot storage rollbackTesting = StorageSlot.getBooleanSlot(_ROLLBACK_SLOT);
if (!rollbackTesting.value) {
// Trigger rollback using upgradeTo from the new implementation
rollbackTesting.value = true;
Address.functionDelegateCall(
newImplementation,
abi.encodeWithSignature("upgradeTo(address)", oldImplementation)
);
rollbackTesting.value = false;
// Check rollback was effective
require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades");
// Finally reset to the new implementation and log the upgrade
_upgradeTo(newImplementation);
}
}
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Returns the current admin.
*/
function _getAdmin() internal view returns (address) {
return StorageSlot.getAddressSlot(_ADMIN_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
require(newAdmin != address(0), "ERC1967: new admin is the zero address");
StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {AdminChanged} event.
*/
function _changeAdmin(address newAdmin) internal {
emit AdminChanged(_getAdmin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
* This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.
*/
bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/**
* @dev Emitted when the beacon is upgraded.
*/
event BeaconUpgraded(address indexed beacon);
/**
* @dev Returns the current beacon.
*/
function _getBeacon() internal view returns (address) {
return StorageSlot.getAddressSlot(_BEACON_SLOT).value;
}
/**
* @dev Stores a new beacon in the EIP1967 beacon slot.
*/
function _setBeacon(address newBeacon) private {
require(Address.isContract(newBeacon), "ERC1967: new beacon is not a contract");
require(
Address.isContract(IBeacon(newBeacon).implementation()),
"ERC1967: beacon implementation is not a contract"
);
StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon;
}
/**
* @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does
* not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).
*
* Emits a {BeaconUpgraded} event.
*/
function _upgradeBeaconToAndCall(
address newBeacon,
bytes memory data,
bool forceCall
) internal {
_setBeacon(newBeacon);
emit BeaconUpgraded(newBeacon);
if (data.length > 0 || forceCall) {
Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev This is the interface that {BeaconProxy} expects of its beacon.
*/
interface IBeacon {
/**
* @dev Must return an address that can be used as a delegate call target.
*
* {BeaconProxy} will check that this address is a contract.
*/
function implementation() external view returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.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 Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC1967 implementation slot:
* ```
* contract ERC1967 {
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._
*/
library StorageSlot {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
assembly {
r.slot := slot
}
}
} | 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() external virtual onlyOwner {
revert("Ownable: Renounce ownership not allowed");
}
| 14,621,744 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.