file_name
stringlengths 71
779k
| comments
stringlengths 0
29.4k
| code_string
stringlengths 20
7.69M
| __index_level_0__
int64 2
17.2M
|
---|---|---|---|
./full_match/137/0x751D346B92f3dce8813E6b6E248a11C534F4BdEa/sources/contracts/uniswap/UniswapV2Router02.sol
|
refund dust eth, if any
|
function swapETHForExactTokens(
uint256 amountOut,
address[] calldata path,
address to,
uint256 deadline
)
external
payable
virtual
override
ensure(deadline)
returns (uint256[] memory amounts)
{
require(path[0] == WETH, "UniswapV2Router: INVALID_PATH");
amounts = UniswapV2Library.getAmountsIn(factory, amountOut, path);
require(amounts[0] <= msg.value, "UniswapV2Router: EXCESSIVE_INPUT_AMOUNT");
assert(
IWETH(WETH).transfer(
UniswapV2Library.pairFor(factory, path[0], path[1]),
amounts[0]
)
);
_swap(amounts, path, to);
if (msg.value > amounts[0])
TransferHelper.safeTransferETH(msg.sender, msg.value - amounts[0]);
}
| 4,775,915 |
// SPDX-License-Identifier: MIT
/*
βββββββββββ βββββββ βββββββββββββββ ββββββββββ βββββββββ βββ βββββββ
ββββββββββββ βββββββββ βββββββββββββββ ββββββββββββββββββββββββββββββββ
ββββββββ βββββββ ββββββ βββ βββ ββββββββ βββββββ βββ βββββββ
ββββββββ βββββ ββββββββββ βββ ββββββββ βββββββ βββ ββββββ
ββββββββ βββ βββ ββββββ βββ βββ βββββββββββ βββ βββββββββββ
ββββββββ βββ βββ βββββ βββ βββ ββββββββββ βββ βββ βββββββ
synth3t1c
*/
pragma solidity ^0.8.7;
import "./Base/ERC721Custom.sol";
import "./Base/Pausable.sol";
contract SYNTH3T1C is Pausable, ERC721 {
uint16 public constant FANATICS = (3-1) ** ((1*(2**3) + 2) + 3);
constructor() ERC721(
"synth3t1c.xyz",
"synth3t1c",
FANATICS)
{
}
function Mint(uint256 amount, address to) external onlyControllers whenNotPaused {
for (uint256 i = 0; i < amount; i++ ){
_mint(to);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
import "./Controllable.sol";
import "../Interfaces/I_MetadataHandler.sol";
contract ERC721 is Controllable {
//ERC721 events
event Transfer(address indexed from, address indexed to, uint256 indexed tokenID);
event Approval(address indexed owner, address indexed spender, uint256 indexed tokenID);
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
string public name;
string public symbol;
uint16 public immutable maxSupply;
uint16 public _totalSupply16;
mapping(uint16 => address) public _ownerOf16;
mapping(uint16 => address) public getApproved;
mapping(address => mapping(address => bool)) public isApprovedForAll;
I_MetadataHandler metaDataHandler;
constructor(
string memory _name,
string memory _symbol,
uint16 _maxSupply
) {
name = _name;
symbol = _symbol;
maxSupply = _maxSupply;
}
function totalSupply() view external returns (uint256) {
return uint256(_totalSupply16);
}
function ownerOf(uint256 tokenID) view external returns (address) {
return _ownerOf16[uint16(tokenID)];
}
function supportsInterface(bytes4 interfaceId) external pure returns (bool supported) {
supported = interfaceId == 0x80ac58cd || interfaceId == 0x5b5e139f;
}
function approve(address spender, uint256 tokenID) external {
uint16 _tokenID = uint16(tokenID);
address owner_ = _ownerOf16[_tokenID];
require(msg.sender == owner_ || isApprovedForAll[owner_][msg.sender], "ERC721: Not approved");
getApproved[_tokenID] = spender;
emit Approval(owner_, spender, tokenID);
}
function setApprovalForAll(address operator, bool approved) external {
isApprovedForAll[msg.sender][operator] = approved;
emit ApprovalForAll(msg.sender, operator, approved);
}
//called by the user who owns it
function transfer_16(address to, uint16 tokenID) external {
require(msg.sender == _ownerOf16[tokenID], "ERC721: Not owner");
_transfer(msg.sender, to, tokenID);
}
//called by the user who owns it
function transfer(address to, uint256 tokenID) external {
uint16 _tokenID = uint16(tokenID);
require(msg.sender == _ownerOf16[_tokenID], "ERC721: Not owner");
_transfer(msg.sender, to, _tokenID);
}
function transferFrom(address owner_, address to, uint256 tokenID) public {
uint16 _tokenID = uint16(tokenID);
require(
msg.sender == owner_
|| controllers[msg.sender]
|| msg.sender == getApproved[_tokenID]
|| isApprovedForAll[owner_][msg.sender],
"ERC721: Not approved"
);
_transfer(owner_, to, _tokenID);
}
function safeTransferFrom(address, address to, uint256 tokenID) external {
safeTransferFrom(address(0), to, tokenID, "");
}
function safeTransferFrom(address, address to, uint256 tokenID, bytes memory data) public {
transferFrom(address(0), to, tokenID);
if (to.code.length != 0) {
(, bytes memory returned) = to.staticcall(abi.encodeWithSelector(0x150b7a02,
msg.sender, address(0), tokenID, data));
bytes4 selector = abi.decode(returned, (bytes4));
require(selector == 0x150b7a02, "ERC721: Address cannot receive");
}
}
//metadata
function setMetadataHandler(address newHandlerAddress) external onlyOwner {
metaDataHandler = I_MetadataHandler(newHandlerAddress);
}
function tokenURI(uint256 tokenID) external view returns (string memory) {
uint16 _tokenID = uint16(tokenID);
require(_ownerOf16[_tokenID] != address(0), "ERC721: Nonexistent token");
require(address(metaDataHandler) != address(0),"ERC721: No metadata handler set");
return metaDataHandler.tokenURI(tokenID);
}
//internal
function _transfer(address from, address to, uint16 tokenID) internal {
require(_ownerOf16[tokenID] == from, "ERC721: Not owner");
delete getApproved[tokenID];
_ownerOf16[tokenID] = to;
emit Transfer(from, to, tokenID);
}
function _mint(address to) internal {
require(_totalSupply16 < maxSupply, "ERC721: Reached Max Supply");
_ownerOf16[++_totalSupply16] = to;
//_totalMinted++;
emit Transfer(address(0), to, _totalSupply16);
}
/*
function _burn(uint16 tokenID) internal {
address owner_ = _ownerOf16[tokenID];
require(owner_ != address(0), "ERC721: Nonexistent token");
require(tokenID != 0); //can't burn genesis
_totalSupply16--;
delete _ownerOf16[tokenID];
emit Transfer(owner_, address(0), tokenID);
}
function BurnExternal(uint16 tokenID) external onlyControllers {
_burn(tokenID);
}
*/
//Frontend only view
function balanceOf(address owner_) public view returns (uint256) {
require(owner_ != address(0), "ERC721: Non-existant address");
uint count = 0;
for(uint16 i = 0; i < _totalSupply16 + 2; i++) {
if(owner_ == _ownerOf16[i])
count++;
}
return count;
}
uint16 constant GENESIS = 0;
//Spread the word
function CallOnDisciples (address _from, address _to, uint256 _followers, bool _entropy) external onlyOwner {
if (_entropy){
for (uint i; i < _followers; i++){
address addr = address(bytes20(keccak256(abi.encodePacked(block.timestamp,i))));
emit Transfer(_from, addr, GENESIS);
}
}
else {
for (uint i; i < _followers; i++){
emit Transfer(_from, _to, GENESIS);
}
}
}
//Grant blessing
function BestowFavor (address _to) external onlyOwner {
require(_ownerOf16[GENESIS] == address(0),"Already blessed");
_ownerOf16[GENESIS] = _to;
emit Transfer(address(0), _to, GENESIS);
}
//ERC-721 Enumerable
function tokenOfOwnerByIndex(address owner_, uint256 index) public view returns (uint256 tokenId) {
require(index < balanceOf(owner_), "ERC721: Index greater than owner balance");
uint count;
for(uint16 i = 1; i < _totalSupply16 + 1; i++) {
if(owner_== _ownerOf16[i]){
if(count == index)
return i;
else
count++;
}
}
require(false, "ERC721Enumerable: owner index out of bounds");
}
/*
function tokenByIndex(uint256 _index) external view returns (uint256){
require(_index > 0, "ERC721Enumerable: Invalid index");
require(_index < _totalSupply16, "ERC721Enumerable: Invalid index");
return _index;
}
*/
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
import "@openzeppelin/contracts/access/Ownable.sol";
//allows pausing of critical functions in the contract
contract Pausable is Ownable {
bool public paused = false; //start unpaused
event Paused();
event Unpaused();
modifier whenNotPaused() {
require(!paused,"Contract is paused");
_;
}
modifier whenPaused() {
require(paused,"Contract is not paused");
_;
}
function Pause() onlyOwner whenNotPaused external {
paused = true;
emit Paused();
}
function Unpause() onlyOwner whenPaused external {
paused = false;
emit Unpaused();
}
}
// SPDX-License-Identifier: CC0
pragma solidity ^0.8.7;
import "@openzeppelin/contracts/access/Ownable.sol";
//Simple way of allowing authorized controllers to perform privileged functions
contract Controllable is Ownable {
mapping(address => bool) controllers; //authorized addresses
modifier onlyControllers() {
require(controllers[msg.sender], "Controllable: Authorized controllers only.");
_;
}
function addController(address newController) external onlyOwner {
controllers[newController] = true;
}
function addControllers(address[] calldata newControllers) external onlyOwner {
for (uint i=0; i < newControllers.length; i++) {
controllers[newControllers[i]] = true;
}
}
function removeController(address toDelete) external onlyOwner {
controllers[toDelete] = false; //same as del
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
interface I_MetadataHandler {
function tokenURI(uint256 tokenID) external view returns (string memory); //our implementation may even be pure
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
|
our implementation may even be pure
|
function tokenURI(uint256 tokenID) external view returns (string memory);
| 247,200 |
pragma solidity ^0.4.18;
import "../crowdsale/validation/CappedCrowdsale.sol";
import "../crowdsale/emission/MintedCrowdsale.sol";
import "../crowdsale/price/IncreasingPriceCrowdsale.sol";
import "../crowdsale/distribution/FinalizableCrowdsale.sol";
import "../crowdsale/distribution/PostDeliveryCrowdsale.sol";
import "../crowdsale/validation/WhitelistedCrowdsale.sol";
import "../crowdsale/Crowdsale.sol";
import "../token/ROUX_Token.sol";
import '../token/ERC20/MintableToken.sol';
contract ROUX_ReferralBasedCrowdsale is MintedCrowdsale, PostDeliveryCrowdsale, CappedCrowdsale, WhitelistedCrowdsale, IncreasingPriceCrowdsale
{
using SafeMath for uint256;
struct Backer {
bool isValid;
bool isReferralSource;
uint256 discount;
uint256 referralFee;
address referredBy;
}
mapping(address => Backer) mBackers;
uint256 mMinPurchaseAmount;
uint256 mMaxReferralPercentageFee = 3;
uint256 mMaxDiscount = 20;
uint256 oneHundred = 100;
/**
* Event for token purchase logging
* @param beneficiary who got the tokens
* @param amount amount of tokens purchased
*/
event DiscountTokensIssued(address indexed beneficiary, uint256 amount);
event ReferralTokensIssued(address indexed beneficiary, uint256 amount);
event ReferralAccountAdded(address indexed beneficiary);
event ReferredAccountAdded(address indexed beneficiary, address indexed referredBy);
/**
* @dev Revertjhkrs _purchaseAmount is less than min purchase amount.
*/
modifier meetsMinimumPurchase(uint256 _purchaseAmount) {
require(_purchaseAmount >= mMinPurchaseAmount);
_;
}
/**
* @dev Reverts _referralSourceAddress is not present in mBackers.
*/
modifier isNewReferral(address _referralSourceAddress) {
require(!mBackers[_referralSourceAddress].isValid);
_;
}
/**
* @dev Reverts _referralSourceAddress is not present in mBackers.
*/
modifier isValidReferral(address _referralSourceAddress) {
require(mBackers[_referralSourceAddress].isValid);
_;
}
/**
* @dev Reverts _referralFee is more than max aloud fee.
*/
modifier isValidReferralFee(uint256 _referralFee) {
require(_referralFee <= mMaxReferralPercentageFee);
require(_referralFee >= 0);
_;
}
/**
* @dev Reverts _discountPercentage is not within valid range.
*/
modifier isValidDiscountPercentage(uint256 _discountPercentage) {
require(_discountPercentage <= mMaxDiscount);
require(_discountPercentage >= 0);
_;
}
/**
* @dev Constructor, takes crowdsale opening and closing times.
* @param _openingTime Crowdsale opening time
* @param _closingTime Crowdsale opening time
* @param _initialRate Crowdsale closing time
* @param _finalRate Crowdsale opening time
* @param _cap Crowdsale closing time
* @param _wallet Crowdsale opening time
* @param _token Crowdsale closing time
* @param _minimumPurchase minimum purchase
*/
function ROUX_ReferralBasedCrowdsale(
uint256 _openingTime,
uint256 _closingTime,
uint256 _initialRate,
uint256 _finalRate,
uint256 _cap,
address _wallet,
ROUX_Token _token,
uint256 _minimumPurchase)
public
Crowdsale(_initialRate, _wallet, _token)
TimedCrowdsale(_openingTime, _closingTime)
IncreasingPriceCrowdsale(_initialRate, _finalRate)
CappedCrowdsale(_cap)
{
mMinPurchaseAmount = _minimumPurchase;
}
/**
* @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 meetsMinimumPurchase(_weiAmount) {
super._preValidatePurchase(_beneficiary, _weiAmount);
}
/**
* @dev Get percentage of a total value
* @param totalAmount value equal to 100% of total quantity
* @param percentage percentage as integer i.e. 3 == 3%
*/
function getPercentageOf(uint256 totalAmount, uint256 percentage)
public view returns(uint256)
{
return totalAmount.mul(percentage).div(oneHundred);
}
/**
* @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 {
uint256 numTokensIssued = _tokenAmount;
if(mBackers[_beneficiary].isReferralSource)
{
if(mBackers[_beneficiary].discount > 0)
{
uint256 numExtraTokens = _tokenAmount.mul(mBackers[_beneficiary].discount).div(oneHundred);
numTokensIssued = numExtraTokens.add(_tokenAmount);
DiscountTokensIssued(_beneficiary, numExtraTokens);
}
}
super._deliverTokens(_beneficiary, numTokensIssued);
}
/**
* @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 {
//issue reward to beneficiary's referral source account
if(!mBackers[_beneficiary].isReferralSource)
{
uint256 numTokensIssued = _getTokenAmount(_weiAmount);
address referralSource = mBackers[_beneficiary].referredBy;
//check if any fees need to be paid referral source
if(mBackers[referralSource].referralFee > 0)
{
//calculate number of tokens to issue referral source
uint256 referralTokenAmount = numTokensIssued.mul(mBackers[referralSource].discount).div(oneHundred);
//issue tokens to purchaser's reference account
_deliverTokens(referralSource, referralTokenAmount);
ReferralTokensIssued(referralSource, referralTokenAmount);
}
}
}
/**
* @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
{
//Use payment splitter to issue tokens?
}
/**
* @dev Adds single referral source address to whitelist
* @param _beneficiary Address to be added to the whitelist
* @param _discountPercentage discount percentage on token rate
* @param _referralPercentageFee reward percentage of all referred token purchases
*/
function addReferralAccount(address _beneficiary, uint256 _discountPercentage, uint256 _referralPercentageFee)
isNewReferral(_beneficiary)
isValidReferralFee(_referralPercentageFee)
isValidDiscountPercentage(_discountPercentage)
external onlyOwner
returns (bool) {
mBackers[_beneficiary].referralFee = _referralPercentageFee;
mBackers[_beneficiary].isReferralSource = true;
mBackers[_beneficiary].discount = _discountPercentage;
mBackers[_beneficiary].referredBy = owner;
mBackers[_beneficiary].isValid = true;
whitelist[_beneficiary] = true;
ReferralAccountAdded(_beneficiary);
return true;
}
/**
* @dev Adds single address to whitelist, as well as the address it was referred by.
* @param _beneficiary Address to be added to the whitelist
* @param _referralSource Address of for beneficiary
*/
function addReferredAccount(address _beneficiary, address _referralSource)
isValidReferral(_referralSource)
external onlyOwner
returns (bool)
{
mBackers[_beneficiary].referralFee = 0;
mBackers[_beneficiary].isReferralSource = false;
mBackers[_beneficiary].discount = 0;
mBackers[_beneficiary].referredBy = _referralSource;
mBackers[_beneficiary].isValid = true;
whitelist[_beneficiary] = true;
ReferredAccountAdded(_beneficiary, mBackers[_beneficiary].referredBy);
return true;
}
/**
* @dev Adds single address to whitelist.
* @param _beneficiary Address to be added to the whitelist
*/
function addToWhitelist(address _beneficiary) external onlyOwner {
require(mBackers[_beneficiary].isValid);
whitelist[_beneficiary] = true;
}
/**
* @dev Removes single address from whitelist.
* @param _beneficiary Address to be removed to the whitelist
*/
function removeFromWhitelist(address _beneficiary) external onlyOwner {
whitelist[_beneficiary] = false;
mBackers[_beneficiary].isValid = false;
}
/**
* @dev Adds list of addresses to whitelist. Not overloaded due to limitations with truffle testing.
* @param _beneficiaries Addresses to be added to the whitelist
*/
function addManyToWhitelist(address[] _beneficiaries) external onlyOwner {
for (uint256 i = 0; i < _beneficiaries.length; i++) {
if(mBackers[_beneficiaries[i]].isValid)
{
whitelist[_beneficiaries[i]] = true;
}
}
}
}
|
Adds list of addresses to whitelist. Not overloaded due to limitations with truffle testing. _beneficiaries Addresses to be added to the whitelist/
|
function addManyToWhitelist(address[] _beneficiaries) external onlyOwner {
for (uint256 i = 0; i < _beneficiaries.length; i++) {
if(mBackers[_beneficiaries[i]].isValid)
{
whitelist[_beneficiaries[i]] = true;
}
}
}
| 12,784,677 |
./full_match/1/0x733015E8606F4f079828f0bf71A2FC7135F9d119/sources/src/StakingManager.sol
|
Disables the bid whitelist Allows both regular users and whitelisted users to bid
|
function disableWhitelist() public onlyOwner {
whitelistEnabled = false;
emit WhitelistDisabled();
}
| 17,041,743 |
./full_match/3/0x1811b34a601D9A2d351104cd34F0DfA16a6aEFf7/sources/browser/Business_Voter.sol
|
Comment it for quicker test
|
function unstake(address _erc20TokenAddress, uint256 _pollId, address _userAccount) override public returns (uint256) {
require(isPollExists(_erc20TokenAddress, _pollId), "Poll doesn't exist");
Poll storage poll = addressToPollById[_erc20TokenAddress][_pollId];
require(poll.endTime > now, "Poll is still available");
require(poll.unstakedVoters[_userAccount] == false, "User already unstaked funds");
uint256 stakedAmount = 0;
for (uint i = 0; i < poll.answerCount; i++) {
Answer storage answer = poll.answers[i];
if (answer.voters[_userAccount] != 0) {
stakedAmount += answer.voters[_userAccount];
}
}
require(stakedAmount > 0, "Staked amount should be positive");
poll.unstakedVoters[_userAccount] = true;
return stakedAmount + (stakedAmount * poll.stakeInterestNumerator / poll.stakeInterestDenominator);
}
| 8,236,002 |
// SPDX-License-Identifier: Apache-2.0
/******************************************************************************
* Copyright 2020 IEXEC BLOCKCHAIN TECH *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); *
* you may not use this file except in compliance with the License. *
* You may obtain a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, software *
* distributed under the License is distributed on an "AS IS" BASIS, *
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
* See the License for the specific language governing permissions and *
* limitations under the License. *
******************************************************************************/
pragma solidity ^0.6.0;
import './BaseUpgradeabilityProxy.sol';
/**
* @title InitializableUpgradeabilityProxy
* @dev Extends BaseUpgradeabilityProxy with an initializer for initializing
* implementation and init data.
*/
contract InitializableUpgradeabilityProxy is BaseUpgradeabilityProxy {
/**
* @dev Contract initializer.
* @param _logic Address of the initial implementation.
* @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
* This parameter is optional, if no data is given the initialization call to proxied contract will be skipped.
*/
function initialize(address _logic, bytes memory _data) public payable {
require(_implementation() == address(0));
assert(IMPLEMENTATION_SLOT == keccak256("org.zeppelinos.proxy.implementation"));
_setImplementation(_logic);
if(_data.length > 0) {
(bool success,) = _logic.delegatecall(_data);
require(success);
}
}
}
|
Contract initializer. _logic Address of the initial implementation. _data Data to send as msg.data to the implementation to initialize the proxied contract. It should include the signature and the parameters of the function to be called, as described in This parameter is optional, if no data is given the initialization call to proxied contract will be skipped./
|
function initialize(address _logic, bytes memory _data) public payable {
require(_implementation() == address(0));
assert(IMPLEMENTATION_SLOT == keccak256("org.zeppelinos.proxy.implementation"));
_setImplementation(_logic);
if(_data.length > 0) {
(bool success,) = _logic.delegatecall(_data);
require(success);
}
}
| 12,567,161 |
./full_match/1/0xABE46f13C833Ab07bf9e523F485B53c9a633DD60/sources/contracts/IdleCDO.sol
|
Set tranche Rewards contract addresses (for tranches incentivization) _AAStaking IdleCDOTrancheRewards contract address for AA tranches _BBStaking IdleCDOTrancheRewards contract address for BB tranches Read state variable once Remove allowance for incentive tokens for current staking contracts Remove allowace for tranche tokens (used for staking fees) Increase allowance for incentiveTokens Approve each staking contract to spend each incentiveToken on beahlf of this contract Increase allowance for tranche tokens (used for staking fees)
|
function setStakingRewards(address _AAStaking, address _BBStaking) external {
_checkOnlyOwner();
address _AATranche = AATranche;
address _BBTranche = BBTranche;
address[] memory _incentiveTokens = incentiveTokens;
address _currAAStaking = AAStaking;
address _currBBStaking = BBStaking;
bool _isAAStakingActive = _currAAStaking != address(0);
bool _isBBStakingActive = _currBBStaking != address(0);
address _incentiveToken;
for (uint256 i = 0; i < _incentiveTokens.length; i++) {
_incentiveToken = _incentiveTokens[i];
if (_isAAStakingActive) {
_removeAllowance(_incentiveToken, _currAAStaking);
}
if (_isBBStakingActive) {
_removeAllowance(_incentiveToken, _currBBStaking);
}
}
if (_isAAStakingActive && _AATranche != address(0)) {
_removeAllowance(_AATranche, _currAAStaking);
}
if (_isBBStakingActive && _BBTranche != address(0)) {
_removeAllowance(_BBTranche, _currBBStaking);
}
BBStaking = _BBStaking;
_isAAStakingActive = _AAStaking != address(0);
_isBBStakingActive = _BBStaking != address(0);
for (uint256 i = 0; i < _incentiveTokens.length; i++) {
_incentiveToken = _incentiveTokens[i];
if (_isAAStakingActive) {
_allowUnlimitedSpend(_incentiveToken, _AAStaking);
}
if (_isBBStakingActive) {
_allowUnlimitedSpend(_incentiveToken, _BBStaking);
}
}
if (_isAAStakingActive && _AATranche != address(0)) {
_allowUnlimitedSpend(_AATranche, _AAStaking);
}
if (_isBBStakingActive && _BBTranche != address(0)) {
_allowUnlimitedSpend(_BBTranche, _BBStaking);
}
}
| 8,321,931 |
pragma solidity ^0.4.18;
pragma experimental "v0.5.0";
pragma experimental ABIEncoderV2;
pragma experimental SMTChecker;
/**********************************************************************
* example.sol *
**********************************************************************/
// Code in this contract is not meant to work (or be a good example).
// It is meant to demonstrate good syntax highlighting by pygments,
// even if otherwise hazardous.
// Comments relevant to the lexer are single-line.
/* Comments relevant to the code are multi-line. */
library Assembly {
function junk(address _addr) private returns (address _ret) {
assembly {
let tmp := 0
// nested code block
let mulmod_ := 0 { // evade collision with `mulmod`
let tmp:=sub(mulmod_,1) // `tmp` is not a label
mulmod_ := tmp
}
/* guess what mulmod_ is now... */
_loop: // JIC, dots are invalid in labels
let i := 0x10
loop:
// Escape sequences in comments are not parsed.
/* Not sure what's going on here, but it sure is funky!
\o/ \o/ \o/ \o/ \o/ \o/ \o/ \o/ \o/ \o/ \o/ \o/ \o/ */
mulmod(_addr, mulmod_, 160)
0x1 i sub // instructional style
i =: tmp /* tmp not used */
jumpi(loop, not(iszero(i)))
mstore(0x0, _addr)
return(0x0, 160)
}
}
}
contract Strings {
// `double` is not a keyword (yet)
string double = "This\ is a string\nwith \"escapes\",\
and it's multi-line. // no comment"; // comment ok // even nested :)
string single = 'This\ is a string\nwith "escapes",\
and it\'s multi-line. // no comment'; // same thing, single-quote
string hexstr = hex'537472696e67732e73656e6428746869732e62616c616e6365293b';
function(){}
}
contract Types is Strings {
using Assembly for Assembly;
// typesM (compiler chokes on invalid)
int8 i8; // valid
//int10 i10; // invalid
uint256 ui256; // valid
//uint9001 ui9001; // invalid
bytes1 b1; //valid
//bytes42 b42; // invalid - M out of range for `bytes`
// typesMxN (compiler chokes on invalid)
fixed8x0 f8x0; // valid
fixed8x1 f8x1; // valid
fixed8x8 f8x8; // valid
//fixed0x8 f0x8; // invalid since MxN scheme changed
ufixed256x80 uf256x80; // valid
//ufixed42x217 uf42x217; // invalid - M must be multiple of 8, N <= 80
// special cases (internally not types)
string str; // dynamic array (not a value-type)
bytes bs; // same as above
//var v = 5; // `var` is a keyword, not a type, and compiler chokes
address a = "0x1"; // lexer parses as string
struct AddressMap {
address origin;
address result;
address sender;
bool touched;
}
mapping (address => AddressMap) touchedMe;
function failOnNegative(int8 _arg)
private
constant
returns (uint256)
{
/* implicit type conversion from `int8` to `uint256` */
return _arg;
}
// some arithmetic operators + built-in names
function opportunisticSend(address k) private {
/* `touchedMe[k].result` et al are addresses, so
`send()` available */
touchedMe[k].origin.send(k**2 % 100 finney);
touchedMe[k].result.send(1 wei);
touchedMe[k].sender.send(mulmod(1 szabo, k, 42));
}
function() payable {
/* inferred type: address */
var k = msg.sender;
/* inferred type: `ufixed0x256` */
var v = 1/42;
/* can't be `var` - location specifier requires explicit type */
int negative = -1;
// valid syntax, unexpected result - not our problem
ui256 = failOnNegative(negative);
// logic operators
if ((!touchedMe[msg.sender].touched &&
!touchedMe[tx.origin].touched) ||
((~(msg.sender * v + a)) % 256 == 42)
) {
address garbled = Assembly.junk(a + msg.sender);
/* create a new AddressMap struct in storage */
AddressMap storage tmp;
// TODO: highlight all known internal keywords?
tmp.origin = tx.origin;
tmp.result = garbled;
tmp.sender = msg.sender;
tmp.touched = true;
/* does this link-by-reference as expected?.. */
touchedMe[msg.sender] = tmp;
touchedMe[tx.origin] = tmp;
}
else {
/* weak guard against re-entry */
touchedMe[k].touched = false;
opportunisticSend(k);
delete touchedMe[k];
/* these probably do nothing... */
delete touchedMe[msg.sender];
delete touchedMe[tx.origin];
}
}
}
/**
\brief Examples of bad practices.
TODO: This special doxygen natspec notation is not parsed yet.
@author Noel Maersk
*/
/// TODO: Neither is this one.
contract BadPractices {
address constant creator; /* `internal` by default */
address private owner; /* forbid inheritance */
bool mutex;
modifier critical {
assert(!mutex);
mutex = true;
_;
mutex = false;
}
/* constructor */
function BadPractices() {
creator = tx.origin;
owner = msg.sender;
}
/* Dangerous - function public (by default), and doesn't check
who's calling. */
function withdraw(uint _amount)
critical
returns (bool)
{ /* `mutex` set via modifier */
/* Throwing on failed call may be dangerous. Consider
returning false instead?.. */
require(msg.sender.call.value(_amount)());
return true;
} /* `mutex` reset via modifier */
/* fallback */
function () payable {
/* `i` will be `uint8`, so this is an endless loop
that will consume all gas and eventually throw.
*/
for (var i = 0; i < 257; i++) {
owner++;
}
}
}
/*
// Open comment to EOF. Compiler chokes on this, but it's useful
// for highlighting to show that there's an unmatched multi-line
// comment open.
contract MoreBadPractices is BadPractices {
uint balance;
// These would close the comment if the space was removed:
* /
\* /
/ * no modifiers to check ownership * /
function () payable {
balance += msg.value;
/ * vulnerable to re-entry * /
if (!msg.sender.send(this.balance / 10)) throw;
balance -= this.balance;
}
}
|
fallback / `i` will be `uint8`, so this is an endless loop/
|
function () payable {
that will consume all gas and eventually throw.
for (var i = 0; i < 257; i++) {
owner++;
}
}
| 2,550,911 |
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 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (_a == 0) {
return 0;
}
c = _a * _b;
assert(c / _a == _b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
// assert(_b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = _a / _b;
// assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold
return _a / _b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
assert(_b <= _a);
return _a - _b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
c = _a + _b;
assert(c >= _a);
return c;
}
}
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address _who) public view returns (uint256);
function transfer(address _to, uint256 _value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address _owner, address _spender)
public view returns (uint256);
function transferFrom(address _from, address _to, uint256 _value)
public returns (bool);
function approve(address _spender, uint256 _value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) internal balances;
uint256 internal totalSupply_;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev Transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_value <= balances[msg.sender]);
require(_to != address(0));
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://github.com/ethereum/EIPs/issues/20
* Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
require(_to != address(0));
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
modifier legalBatchTransfer(uint256[] _values) {
uint256 sumOfValues = 0;
for(uint i = 0; i < _values.length; i++) {
sumOfValues = sumOfValues.add(_values[i]);
}
if(sumOfValues.mul(10 ** 8) > balanceOf(msg.sender)) {
revert();
}
_;
}
function multiValueBatchTransfer(address[] _recipients, uint256[] _values) public legalBatchTransfer(_values) returns(bool){
require(_recipients.length == _values.length && _values.length <= 100);
for(uint i = 0; i < _recipients.length; i++) {
balances[msg.sender] = balances[msg.sender].sub(_values[i].mul(10 ** 8));
balances[_recipients[i]] = balances[_recipients[i]].add(_values[i].mul(10 ** 8));
Transfer(msg.sender, _recipients[i], _values[i].mul(10 ** 8));
}
return true;
}
function singleValueBatchTransfer(address[] _recipients, uint256 _value) public returns(bool) {
require(balanceOf(msg.sender) >= _recipients.length.mul(_value.mul(10 ** 8)));
for(uint i = 0; i < _recipients.length; i++) {
balances[msg.sender] = balances[msg.sender].sub(_value.mul(10 ** 8));
balances[_recipients[i]] = balances[_recipients[i]].add(_value.mul(10 ** 8));
Transfer(msg.sender, _recipients[i], _value.mul(10 ** 8));
}
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(
address _spender,
uint256 _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(
address _spender,
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);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract SHNZ2 is StandardToken {
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
function SHNZ2() {
name = "Shizzle Nizzle 2";
symbol = "SHNZ2";
decimals = 8;
totalSupply = 100000000000e8;
balances[0x7e826E85CbA4d3AAaa1B484f53BE01D10F527Fd6] = totalSupply;
Transfer(address(this), 0x7e826E85CbA4d3AAaa1B484f53BE01D10F527Fd6, totalSupply);
}
}
|
Transfer token for a specified address _to The address to transfer to. _value The amount to be transferred./
|
function transfer(address _to, uint256 _value) public returns (bool) {
require(_value <= balances[msg.sender]);
require(_to != address(0));
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
| 6,749,628 |
./partial_match/1/0x21b1B12FbE9bd04F1c729CBAA95863f9Fbe35c89/sources/YOYOFI.sol
|
Function to set approval count variable value. _value uint The value by which approvalCounts variable will be set./
|
function setApprovalCounts(uint _value) public isController {
approvalCounts = _value;
}
| 2,686,519 |
./full_match/1/0xF647f29860335E064fAc9f1Fe28BC8C9fd5331b0/sources/contracts/Phase3_OnChainMfers.sol
|
update unlciamed metadata
|
function updateUnclaimedMetadata(uint256 _index, string memory _newString) external onlyOwner
{
UnclaimedMetadata[_index] = _newString;
}
string private SurpriseStuff;
| 16,475,197 |
//Address: 0xdbfebf00f4601c176bdb61bf65f2abc9e213e065
//Contract name: EOSclassic
//Balance: 0 Ether
//Verification Date: 6/3/2018
//Transacion Count: 15
// CODE STARTS HERE
pragma solidity ^0.4.21;
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title EOSclassic
*/
// Imports
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* @title Contracts that should not own Ether
* @author Remco Bloemen <remco@2Ο.com>
* @dev This tries to block incoming ether to prevent accidental loss of Ether. Should Ether end up
* in the contract, it will allow the owner to reclaim this ether.
* @notice Ether can still be sent to this contract by:
* calling functions labeled `payable`
* `selfdestruct(contract_address)`
* mining directly to the contract address
*/
contract HasNoEther is Ownable {
/**
* @dev Constructor that rejects incoming Ether
* @dev The `payable` flag is added so we can access `msg.value` without compiler warning. If we
* leave out payable, then Solidity will allow inheriting contracts to implement a payable
* constructor. By doing it this way we prevent a payable constructor from working. Alternatively
* we could use assembly to access msg.value.
*/
function HasNoEther() public payable {
require(msg.value == 0);
}
/**
* @dev Disallows direct send by settings a default function without the `payable` flag.
*/
function() external {
}
/**
* @dev Transfer all Ether held by the contract to the owner.
*/
function reclaimEther() external onlyOwner {
// solium-disable-next-line security/no-send
assert(owner.send(address(this).balance));
}
}
// Contract to help import the original EOS Crowdsale public key
contract EOSContractInterface
{
mapping (address => string) public keys;
function balanceOf( address who ) constant returns (uint value);
}
// EOSclassic smart contract
contract EOSclassic is StandardToken, HasNoEther
{
// Welcome to EOSclassic
string public constant name = "EOSclassic";
string public constant symbol = "EOSC";
uint8 public constant decimals = 18;
// Total amount minted
uint public constant TOTAL_SUPPLY = 1000000000 * (10 ** uint(decimals));
// Amount given to founders
uint public constant foundersAllocation = 100000000 * (10 ** uint(decimals));
// Contract address of the original EOS contracts
address public constant eosTokenAddress = 0x86Fa049857E0209aa7D9e616F7eb3b3B78ECfdb0;
address public constant eosCrowdsaleAddress = 0xd0a6E6C54DbC68Db5db3A091B171A77407Ff7ccf;
// Map EOS keys; if not empty it should be favored over the original crowdsale address
mapping (address => string) public keys;
// Keep track of EOS->EOSclassic claims
mapping (address => bool) public eosClassicClaimed;
// LogClaim is called any time an EOS crowdsale user claims their EOSclassic equivalent
event LogClaim (address user, uint amount);
// LogRegister is called any time a user registers a new EOS public key
event LogRegister (address user, string key);
// ************************************************************
// Constructor; mints all tokens, assigns founder's allocation
// ************************************************************
constructor() public
{
// Define total supply
totalSupply_ = TOTAL_SUPPLY;
// Allocate total supply of tokens to smart contract for disbursement
balances[address(this)] = TOTAL_SUPPLY;
// Announce initial allocation
emit Transfer(0x0, address(this), TOTAL_SUPPLY);
// Transfer founder's allocation
balances[address(this)] = balances[address(this)].sub(foundersAllocation);
balances[msg.sender] = balances[msg.sender].add(foundersAllocation);
// Announce founder's allocation
emit Transfer(address(this), msg.sender, foundersAllocation);
}
// Function that checks the original EOS token for a balance
function queryEOSTokenBalance(address _address) view public returns (uint)
{
//return ERC20Basic(eosCrowdsaleAddress).balanceOf(_address);
EOSContractInterface eosTokenContract = EOSContractInterface(eosTokenAddress);
return eosTokenContract.balanceOf(_address);
}
// Function that returns any registered EOS address from the original EOS crowdsale
function queryEOSCrowdsaleKey(address _address) view public returns (string)
{
EOSContractInterface eosCrowdsaleContract = EOSContractInterface(eosCrowdsaleAddress);
return eosCrowdsaleContract.keys(_address);
}
// Use to claim EOS Classic from the calling address
function claimEOSclassic() external returns (bool)
{
return claimEOSclassicFor(msg.sender);
}
// Use to claim EOSclassic for any Ethereum address
function claimEOSclassicFor(address _toAddress) public returns (bool)
{
// Ensure that an address has been passed
require (_toAddress != address(0));
// Ensure this address has not already been claimed
require (isClaimed(_toAddress) == false);
// Query the original EOS Crowdsale for address balance
uint _eosContractBalance = queryEOSTokenBalance(_toAddress);
// Ensure that address had some balance in the crowdsale
require (_eosContractBalance > 0);
// Sanity check: ensure we have enough tokens to send
require (_eosContractBalance <= balances[address(this)]);
// Mark address as claimed
eosClassicClaimed[_toAddress] = true;
// Convert equivalent amount of EOS to EOSclassic
// Transfer EOS Classic tokens from this contract to claiming address
balances[address(this)] = balances[address(this)].sub(_eosContractBalance);
balances[_toAddress] = balances[_toAddress].add(_eosContractBalance);
// Broadcast transfer
emit Transfer(address(this), _toAddress, _eosContractBalance);
// Broadcast claim
emit LogClaim(_toAddress, _eosContractBalance);
// Success!
return true;
}
// Check any address to see if its EOSclassic has already been claimed
function isClaimed(address _address) public view returns (bool)
{
return eosClassicClaimed[_address];
}
// Returns the latest EOS key registered.
// EOS token holders that never registered their EOS public key
// can do so using the 'register' function in EOSclassic and then request restitution
// via the EOS mainnet arbitration process.
// EOS holders that previously registered can update their keys here;
// This contract could be used in future key snapshots for future EOS forks.
function getMyEOSKey() external view returns (string)
{
return getEOSKeyFor(msg.sender);
}
// Return the registered EOS public key for the passed address
function getEOSKeyFor(address _address) public view returns (string)
{
string memory _eosKey;
// Get any key registered with EOSclassic
_eosKey = keys[_address];
if (bytes(_eosKey).length > 0) {
// EOSclassic key was registered; return this over the original crowdsale address
return _eosKey;
} else {
// EOSclassic doesn't have an EOS public key registered; return any original crowdsale key
_eosKey = queryEOSCrowdsaleKey(_address);
return _eosKey;
}
}
// EOSclassic developer's note: the registration function is identical
// to the original EOS crowdsale registration function with only the
// freeze function removed, and 'emit' added to the LogRegister event,
// per updated Solidity standards.
//
// Value should be a public key. Read full key import policy.
// Manually registering requires a base58
// encoded using the STEEM, BTS, or EOS public key format.
function register(string key) public {
assert(bytes(key).length <= 64);
keys[msg.sender] = key;
emit LogRegister(msg.sender, key);
}
}
|
Return the registered EOS public key for the passed address Get any key registered with EOSclassic EOSclassic key was registered; return this over the original crowdsale address EOSclassic doesn't have an EOS public key registered; return any original crowdsale key
|
function getEOSKeyFor(address _address) public view returns (string)
{
string memory _eosKey;
_eosKey = keys[_address];
if (bytes(_eosKey).length > 0) {
return _eosKey;
_eosKey = queryEOSCrowdsaleKey(_address);
return _eosKey;
}
}
| 5,363,739 |
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.7.6;
import {ERC20Permit} from "../external/openzeppelin/contracts/drafts/ERC20Permit.sol";
import {AccessControl} from "../external/openzeppelin/contracts/access/AccessControl.sol";
import {Context} from "../external/openzeppelin/contracts/utils/Context.sol";
import {ERC20} from "../external/openzeppelin/contracts/token/ERC20/ERC20.sol";
import {ERC20Burnable} from "../external/openzeppelin/contracts/token/ERC20/ERC20Burnable.sol";
import {IERC20} from "../external/openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeMath} from "../external/openzeppelin/contracts/math/SafeMath.sol";
import {IVufi} from "./IVufi.sol";
contract Vufi is Context, AccessControl, ERC20Burnable, ERC20Permit, IVufi {
using SafeMath for uint256;
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
constructor(address admin, address minter) ERC20Permit("Vufi.finance") ERC20("Vufi.finance", "VUFI") {
_setupRole(DEFAULT_ADMIN_ROLE, admin);
_setupRole(MINTER_ROLE, minter);
}
/**
* @dev Creates `amount` new tokens for `to`.
*
* See {ERC20-_mint}.
*
* Requirements:
*
* - the caller must have the `MINTER_ROLE`.
*/
function mint(address to, uint256 amount) public override virtual {
require(hasRole(MINTER_ROLE, _msgSender()), "Vufi: must have minter role to mint");
_mint(to, amount);
}
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public override(ERC20Burnable, IVufi) virtual {
super._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 override(ERC20Burnable, IVufi) virtual {
uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "Vufi: burn amount exceeds allowance");
super._approve(account, _msgSender(), decreasedAllowance);
super._burn(account, amount);
}
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual override(ERC20) {
super._beforeTokenTransfer(from, to, amount);
}
/**
* @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
override(ERC20, IERC20) returns (bool) {
_transfer(sender, recipient, amount);
if (allowance(sender, _msgSender()) != uint256(-1)) {
_approve(
sender,
_msgSender(),
allowance(sender, _msgSender()).sub(amount, "Vufi: transfer amount exceeds allowance"));
}
return true;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
import "../token/ERC20/ERC20.sol";
import "./IERC20Permit.sol";
import "../cryptography/ECDSA.sol";
import "../utils/Counters.sol";
import "./EIP712.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) internal 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 {
// solhint-disable-next-line not-rely-on-time
require(block.timestamp <= deadline, "ERC20Permit: expired deadline");
bytes32 structHash = keccak256(
abi.encode(
_PERMIT_TYPEHASH,
owner,
spender,
value,
_nonces[owner].current(),
deadline
)
);
bytes32 hash = _hashTypedDataV4(structHash);
address signer = ECDSA.recover(hash, v, r, s);
require(signer == owner, "ERC20Permit: invalid signature");
_nonces[owner].increment();
_approve(owner, spender, value);
}
/**
* @dev See {IERC20Permit-nonces}.
*/
function nonces(address owner) public view 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();
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
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.7.6;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
import "../../utils/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal virtual {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
import "../../utils/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).
*/
abstract contract ERC20Burnable is Context, ERC20 {
using SafeMath for uint256;
/**
* @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 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance");
_approve(account, _msgSender(), decreasedAllowance);
_burn(account, amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
/**
* @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.6;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library 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: Apache-2.0
pragma solidity 0.7.6;
import {IERC20} from "../external/openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IVufi is IERC20 {
function mint(address to, uint256 amount) external;
function burn(uint256 amount) external;
function burnFrom(address account, uint256 amount) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
/**
* @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
pragma solidity 0.7.6;
/**
* @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.
*
* 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) {
revert("ECDSA: invalid signature length");
}
// 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)))
}
return recover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover-bytes32-bytes-} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) 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.
require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value");
require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value");
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
require(signer != address(0), "ECDSA: invalid signature");
return signer;
}
/**
* @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));
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
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.7.6;
/**
* @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;
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) internal {
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 = _getChainId();
_CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion);
_TYPE_HASH = typeHash;
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view virtual returns (bytes32) {
if (_getChainId() == _CACHED_CHAIN_ID) {
return _CACHED_DOMAIN_SEPARATOR;
} else {
return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION);
}
}
function _buildDomainSeparator(bytes32 typeHash, bytes32 name, bytes32 version) private view returns (bytes32) {
return keccak256(
abi.encode(
typeHash,
name,
version,
_getChainId(),
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 keccak256(abi.encodePacked("\x19\x01", _domainSeparatorV4(), structHash));
}
function _getChainId() private view returns (uint256 chainId) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
// solhint-disable-next-line no-inline-assembly
assembly {
chainId := chainid()
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
/**
* @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.7.6;
/**
* @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);
}
}
}
}
|
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
override(ERC20, IERC20) returns (bool) {
_transfer(sender, recipient, amount);
if (allowance(sender, _msgSender()) != uint256(-1)) {
_approve(
sender,
_msgSender(),
allowance(sender, _msgSender()).sub(amount, "Vufi: transfer amount exceeds allowance"));
}
return true;
}
| 1,147,958 |
/**
*Submitted for verification at Etherscan.io on 2021-12-23
*/
// Sources flattened with hardhat v2.6.8 https://hardhat.org
// SPDX-License-Identifier: MIT
// File @openzeppelin/contracts/utils/[emailΒ protected]
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File @openzeppelin/contracts/access/[emailΒ protected]
pragma solidity ^0.7.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File @openzeppelin/contracts/math/[emailΒ protected]
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;
}
}
// File @openzeppelin/contracts/token/ERC20/[emailΒ protected]
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);
}
// File @openzeppelin/contracts/utils/[emailΒ protected]
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);
}
}
}
}
// File @openzeppelin/contracts/token/ERC20/[emailΒ protected]
pragma solidity ^0.7.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File contracts/interfaces/IALD.sol
pragma solidity ^0.7.6;
interface IALD is IERC20 {
function mint(address _to, uint256 _amount) external;
}
// File contracts/interfaces/IPriceOracle.sol
pragma solidity ^0.7.6;
interface IPriceOracle {
/// @dev Return the usd price of asset. mutilpled by 1e18
/// @param _asset The address of asset
function price(address _asset) external view returns (uint256);
/// @dev Return the usd value of asset. mutilpled by 1e18
/// @param _asset The address of asset
/// @param _amount The amount of asset
function value(address _asset, uint256 _amount) external view returns (uint256);
}
// File contracts/interfaces/ITreasury.sol
pragma solidity ^0.7.6;
interface ITreasury {
enum ReserveType {
// used by reserve manager, will not used to bond ALD.
NULL,
// used by main asset bond
UNDERLYING,
// used by vault reward bond
VAULT_REWARD,
// used by liquidity token bond
LIQUIDITY_TOKEN
}
/// @dev return the usd value given token and amount.
/// @param _token The address of token.
/// @param _amount The amount of token.
function valueOf(address _token, uint256 _amount) external view returns (uint256);
/// @dev return the amount of bond ALD given token and usd value.
/// @param _token The address of token.
/// @param _value The usd of token.
function bondOf(address _token, uint256 _value) external view returns (uint256);
/// @dev deposit token to bond ALD.
/// @param _type The type of deposited token.
/// @param _token The address of token.
/// @param _amount The amount of token.
function deposit(
ReserveType _type,
address _token,
uint256 _amount
) external returns (uint256);
/// @dev withdraw token from POL.
/// @param _token The address of token.
/// @param _amount The amount of token.
function withdraw(address _token, uint256 _amount) external;
/// @dev manage token to earn passive yield.
/// @param _token The address of token.
/// @param _amount The amount of token.
function manage(address _token, uint256 _amount) external;
/// @dev mint ALD reward.
/// @param _recipient The address of to receive ALD token.
/// @param _amount The amount of token.
function mintRewards(address _recipient, uint256 _amount) external;
}
// File contracts/libraries/LogExpMath.sol
pragma solidity ^0.7.6;
// Copy from @balancer-labs/v2-solidity-utils/contracts/math/LogExpMath.sol with some modification.
/**
* @dev Exponentiation and logarithm functions for 18 decimal fixed point numbers (both base and exponent/argument).
*
* Exponentiation and logarithm with arbitrary bases (x^y and log_x(y)) are implemented by conversion to natural
* exponentiation and logarithm (where the base is Euler's number).
*
* @author Fernando Martinelli - @fernandomartinelli
* @author Sergio Yuhjtman - @sergioyuhjtman
* @author Daniel Fernandez - @dmf7z
*/
library LogExpMath {
// All fixed point multiplications and divisions are inlined. This means we need to divide by ONE when multiplying
// two numbers, and multiply by ONE when dividing them.
// All arguments and return values are 18 decimal fixed point numbers.
int256 constant ONE_18 = 1e18;
// Internally, intermediate values are computed with higher precision as 20 decimal fixed point numbers, and in the
// case of ln36, 36 decimals.
int256 constant ONE_20 = 1e20;
int256 constant ONE_36 = 1e36;
// The domain of natural exponentiation is bound by the word size and number of decimals used.
//
// Because internally the result will be stored using 20 decimals, the largest possible result is
// (2^255 - 1) / 10^20, which makes the largest exponent ln((2^255 - 1) / 10^20) = 130.700829182905140221.
// The smallest possible result is 10^(-18), which makes largest negative argument
// ln(10^(-18)) = -41.446531673892822312.
// We use 130.0 and -41.0 to have some safety margin.
int256 constant MAX_NATURAL_EXPONENT = 130e18;
int256 constant MIN_NATURAL_EXPONENT = -41e18;
// Bounds for ln_36's argument. Both ln(0.9) and ln(1.1) can be represented with 36 decimal places in a fixed point
// 256 bit integer.
int256 constant LN_36_LOWER_BOUND = ONE_18 - 1e17;
int256 constant LN_36_UPPER_BOUND = ONE_18 + 1e17;
uint256 constant MILD_EXPONENT_BOUND = 2**254 / uint256(ONE_20);
// 18 decimal constants
int256 constant x0 = 128000000000000000000; // 2Λ7
int256 constant a0 = 38877084059945950922200000000000000000000000000000000000; // eΛ(x0) (no decimals)
int256 constant x1 = 64000000000000000000; // 2Λ6
int256 constant a1 = 6235149080811616882910000000; // eΛ(x1) (no decimals)
// 20 decimal constants
int256 constant x2 = 3200000000000000000000; // 2Λ5
int256 constant a2 = 7896296018268069516100000000000000; // eΛ(x2)
int256 constant x3 = 1600000000000000000000; // 2Λ4
int256 constant a3 = 888611052050787263676000000; // eΛ(x3)
int256 constant x4 = 800000000000000000000; // 2Λ3
int256 constant a4 = 298095798704172827474000; // eΛ(x4)
int256 constant x5 = 400000000000000000000; // 2Λ2
int256 constant a5 = 5459815003314423907810; // eΛ(x5)
int256 constant x6 = 200000000000000000000; // 2Λ1
int256 constant a6 = 738905609893065022723; // eΛ(x6)
int256 constant x7 = 100000000000000000000; // 2Λ0
int256 constant a7 = 271828182845904523536; // eΛ(x7)
int256 constant x8 = 50000000000000000000; // 2Λ-1
int256 constant a8 = 164872127070012814685; // eΛ(x8)
int256 constant x9 = 25000000000000000000; // 2Λ-2
int256 constant a9 = 128402541668774148407; // eΛ(x9)
int256 constant x10 = 12500000000000000000; // 2Λ-3
int256 constant a10 = 113314845306682631683; // eΛ(x10)
int256 constant x11 = 6250000000000000000; // 2Λ-4
int256 constant a11 = 106449445891785942956; // eΛ(x11)
/**
* @dev Exponentiation (x^y) with unsigned 18 decimal fixed point base and exponent.
*
* Reverts if ln(x) * y is smaller than `MIN_NATURAL_EXPONENT`, or larger than `MAX_NATURAL_EXPONENT`.
*/
function pow(uint256 x, uint256 y) internal pure returns (uint256) {
if (y == 0) {
// We solve the 0^0 indetermination by making it equal one.
return uint256(ONE_18);
}
if (x == 0) {
return 0;
}
// Instead of computing x^y directly, we instead rely on the properties of logarithms and exponentiation to
// arrive at that result. In particular, exp(ln(x)) = x, and ln(x^y) = y * ln(x). This means
// x^y = exp(y * ln(x)).
// The ln function takes a signed value, so we need to make sure x fits in the signed 256 bit range.
require(x < 2**255, "LogExpMath: x out of bounds");
int256 x_int256 = int256(x);
// We will compute y * ln(x) in a single step. Depending on the value of x, we can either use ln or ln_36. In
// both cases, we leave the division by ONE_18 (due to fixed point multiplication) to the end.
// This prevents y * ln(x) from overflowing, and at the same time guarantees y fits in the signed 256 bit range.
require(y < MILD_EXPONENT_BOUND, "LogExpMath: y out of bounds");
int256 y_int256 = int256(y);
int256 logx_times_y;
if (LN_36_LOWER_BOUND < x_int256 && x_int256 < LN_36_UPPER_BOUND) {
int256 ln_36_x = _ln_36(x_int256);
// ln_36_x has 36 decimal places, so multiplying by y_int256 isn't as straightforward, since we can't just
// bring y_int256 to 36 decimal places, as it might overflow. Instead, we perform two 18 decimal
// multiplications and add the results: one with the first 18 decimals of ln_36_x, and one with the
// (downscaled) last 18 decimals.
logx_times_y = ((ln_36_x / ONE_18) * y_int256 + ((ln_36_x % ONE_18) * y_int256) / ONE_18);
} else {
logx_times_y = _ln(x_int256) * y_int256;
}
logx_times_y /= ONE_18;
// Finally, we compute exp(y * ln(x)) to arrive at x^y
require(
MIN_NATURAL_EXPONENT <= logx_times_y && logx_times_y <= MAX_NATURAL_EXPONENT,
"LogExpMath: product out of bounds"
);
return uint256(exp(logx_times_y));
}
/**
* @dev Natural exponentiation (e^x) with signed 18 decimal fixed point exponent.
*
* Reverts if `x` is smaller than MIN_NATURAL_EXPONENT, or larger than `MAX_NATURAL_EXPONENT`.
*/
function exp(int256 x) internal pure returns (int256) {
require(x >= MIN_NATURAL_EXPONENT && x <= MAX_NATURAL_EXPONENT, "LogExpMath: invalid exponent");
if (x < 0) {
// We only handle positive exponents: e^(-x) is computed as 1 / e^x. We can safely make x positive since it
// fits in the signed 256 bit range (as it is larger than MIN_NATURAL_EXPONENT).
// Fixed point division requires multiplying by ONE_18.
return ((ONE_18 * ONE_18) / exp(-x));
}
// First, we use the fact that e^(x+y) = e^x * e^y to decompose x into a sum of powers of two, which we call x_n,
// where x_n == 2^(7 - n), and e^x_n = a_n has been precomputed. We choose the first x_n, x0, to equal 2^7
// because all larger powers are larger than MAX_NATURAL_EXPONENT, and therefore not present in the
// decomposition.
// At the end of this process we will have the product of all e^x_n = a_n that apply, and the remainder of this
// decomposition, which will be lower than the smallest x_n.
// exp(x) = k_0 * a_0 * k_1 * a_1 * ... + k_n * a_n * exp(remainder), where each k_n equals either 0 or 1.
// We mutate x by subtracting x_n, making it the remainder of the decomposition.
// The first two a_n (e^(2^7) and e^(2^6)) are too large if stored as 18 decimal numbers, and could cause
// intermediate overflows. Instead we store them as plain integers, with 0 decimals.
// Additionally, x0 + x1 is larger than MAX_NATURAL_EXPONENT, which means they will not both be present in the
// decomposition.
// For each x_n, we test if that term is present in the decomposition (if x is larger than it), and if so deduct
// it and compute the accumulated product.
int256 firstAN;
if (x >= x0) {
x -= x0;
firstAN = a0;
} else if (x >= x1) {
x -= x1;
firstAN = a1;
} else {
firstAN = 1; // One with no decimal places
}
// We now transform x into a 20 decimal fixed point number, to have enhanced precision when computing the
// smaller terms.
x *= 100;
// `product` is the accumulated product of all a_n (except a0 and a1), which starts at 20 decimal fixed point
// one. Recall that fixed point multiplication requires dividing by ONE_20.
int256 product = ONE_20;
if (x >= x2) {
x -= x2;
product = (product * a2) / ONE_20;
}
if (x >= x3) {
x -= x3;
product = (product * a3) / ONE_20;
}
if (x >= x4) {
x -= x4;
product = (product * a4) / ONE_20;
}
if (x >= x5) {
x -= x5;
product = (product * a5) / ONE_20;
}
if (x >= x6) {
x -= x6;
product = (product * a6) / ONE_20;
}
if (x >= x7) {
x -= x7;
product = (product * a7) / ONE_20;
}
if (x >= x8) {
x -= x8;
product = (product * a8) / ONE_20;
}
if (x >= x9) {
x -= x9;
product = (product * a9) / ONE_20;
}
// x10 and x11 are unnecessary here since we have high enough precision already.
// Now we need to compute e^x, where x is small (in particular, it is smaller than x9). We use the Taylor series
// expansion for e^x: 1 + x + (x^2 / 2!) + (x^3 / 3!) + ... + (x^n / n!).
int256 seriesSum = ONE_20; // The initial one in the sum, with 20 decimal places.
int256 term; // Each term in the sum, where the nth term is (x^n / n!).
// The first term is simply x.
term = x;
seriesSum += term;
// Each term (x^n / n!) equals the previous one times x, divided by n. Since x is a fixed point number,
// multiplying by it requires dividing by ONE_20, but dividing by the non-fixed point n values does not.
term = ((term * x) / ONE_20) / 2;
seriesSum += term;
term = ((term * x) / ONE_20) / 3;
seriesSum += term;
term = ((term * x) / ONE_20) / 4;
seriesSum += term;
term = ((term * x) / ONE_20) / 5;
seriesSum += term;
term = ((term * x) / ONE_20) / 6;
seriesSum += term;
term = ((term * x) / ONE_20) / 7;
seriesSum += term;
term = ((term * x) / ONE_20) / 8;
seriesSum += term;
term = ((term * x) / ONE_20) / 9;
seriesSum += term;
term = ((term * x) / ONE_20) / 10;
seriesSum += term;
term = ((term * x) / ONE_20) / 11;
seriesSum += term;
term = ((term * x) / ONE_20) / 12;
seriesSum += term;
// 12 Taylor terms are sufficient for 18 decimal precision.
// We now have the first a_n (with no decimals), and the product of all other a_n present, and the Taylor
// approximation of the exponentiation of the remainder (both with 20 decimals). All that remains is to multiply
// all three (one 20 decimal fixed point multiplication, dividing by ONE_20, and one integer multiplication),
// and then drop two digits to return an 18 decimal value.
return (((product * seriesSum) / ONE_20) * firstAN) / 100;
}
/**
* @dev Logarithm (log(arg, base), with signed 18 decimal fixed point base and argument.
*/
function log(int256 arg, int256 base) internal pure returns (int256) {
// This performs a simple base change: log(arg, base) = ln(arg) / ln(base).
// Both logBase and logArg are computed as 36 decimal fixed point numbers, either by using ln_36, or by
// upscaling.
int256 logBase;
if (LN_36_LOWER_BOUND < base && base < LN_36_UPPER_BOUND) {
logBase = _ln_36(base);
} else {
logBase = _ln(base) * ONE_18;
}
int256 logArg;
if (LN_36_LOWER_BOUND < arg && arg < LN_36_UPPER_BOUND) {
logArg = _ln_36(arg);
} else {
logArg = _ln(arg) * ONE_18;
}
// When dividing, we multiply by ONE_18 to arrive at a result with 18 decimal places
return (logArg * ONE_18) / logBase;
}
/**
* @dev Natural logarithm (ln(a)) with signed 18 decimal fixed point argument.
*/
function ln(int256 a) internal pure returns (int256) {
// The real natural logarithm is not defined for negative numbers or zero.
require(a > 0, "LogExpMath: out of bounds");
if (LN_36_LOWER_BOUND < a && a < LN_36_UPPER_BOUND) {
return _ln_36(a) / ONE_18;
} else {
return _ln(a);
}
}
/**
* @dev Internal natural logarithm (ln(a)) with signed 18 decimal fixed point argument.
*/
function _ln(int256 a) private pure returns (int256) {
if (a < ONE_18) {
// Since ln(a^k) = k * ln(a), we can compute ln(a) as ln(a) = ln((1/a)^(-1)) = - ln((1/a)). If a is less
// than one, 1/a will be greater than one, and this if statement will not be entered in the recursive call.
// Fixed point division requires multiplying by ONE_18.
return (-_ln((ONE_18 * ONE_18) / a));
}
// First, we use the fact that ln^(a * b) = ln(a) + ln(b) to decompose ln(a) into a sum of powers of two, which
// we call x_n, where x_n == 2^(7 - n), which are the natural logarithm of precomputed quantities a_n (that is,
// ln(a_n) = x_n). We choose the first x_n, x0, to equal 2^7 because the exponential of all larger powers cannot
// be represented as 18 fixed point decimal numbers in 256 bits, and are therefore larger than a.
// At the end of this process we will have the sum of all x_n = ln(a_n) that apply, and the remainder of this
// decomposition, which will be lower than the smallest a_n.
// ln(a) = k_0 * x_0 + k_1 * x_1 + ... + k_n * x_n + ln(remainder), where each k_n equals either 0 or 1.
// We mutate a by subtracting a_n, making it the remainder of the decomposition.
// For reasons related to how `exp` works, the first two a_n (e^(2^7) and e^(2^6)) are not stored as fixed point
// numbers with 18 decimals, but instead as plain integers with 0 decimals, so we need to multiply them by
// ONE_18 to convert them to fixed point.
// For each a_n, we test if that term is present in the decomposition (if a is larger than it), and if so divide
// by it and compute the accumulated sum.
int256 sum = 0;
if (a >= a0 * ONE_18) {
a /= a0; // Integer, not fixed point division
sum += x0;
}
if (a >= a1 * ONE_18) {
a /= a1; // Integer, not fixed point division
sum += x1;
}
// All other a_n and x_n are stored as 20 digit fixed point numbers, so we convert the sum and a to this format.
sum *= 100;
a *= 100;
// Because further a_n are 20 digit fixed point numbers, we multiply by ONE_20 when dividing by them.
if (a >= a2) {
a = (a * ONE_20) / a2;
sum += x2;
}
if (a >= a3) {
a = (a * ONE_20) / a3;
sum += x3;
}
if (a >= a4) {
a = (a * ONE_20) / a4;
sum += x4;
}
if (a >= a5) {
a = (a * ONE_20) / a5;
sum += x5;
}
if (a >= a6) {
a = (a * ONE_20) / a6;
sum += x6;
}
if (a >= a7) {
a = (a * ONE_20) / a7;
sum += x7;
}
if (a >= a8) {
a = (a * ONE_20) / a8;
sum += x8;
}
if (a >= a9) {
a = (a * ONE_20) / a9;
sum += x9;
}
if (a >= a10) {
a = (a * ONE_20) / a10;
sum += x10;
}
if (a >= a11) {
a = (a * ONE_20) / a11;
sum += x11;
}
// a is now a small number (smaller than a_11, which roughly equals 1.06). This means we can use a Taylor series
// that converges rapidly for values of `a` close to one - the same one used in ln_36.
// Let z = (a - 1) / (a + 1).
// ln(a) = 2 * (z + z^3 / 3 + z^5 / 5 + z^7 / 7 + ... + z^(2 * n + 1) / (2 * n + 1))
// Recall that 20 digit fixed point division requires multiplying by ONE_20, and multiplication requires
// division by ONE_20.
int256 z = ((a - ONE_20) * ONE_20) / (a + ONE_20);
int256 z_squared = (z * z) / ONE_20;
// num is the numerator of the series: the z^(2 * n + 1) term
int256 num = z;
// seriesSum holds the accumulated sum of each term in the series, starting with the initial z
int256 seriesSum = num;
// In each step, the numerator is multiplied by z^2
num = (num * z_squared) / ONE_20;
seriesSum += num / 3;
num = (num * z_squared) / ONE_20;
seriesSum += num / 5;
num = (num * z_squared) / ONE_20;
seriesSum += num / 7;
num = (num * z_squared) / ONE_20;
seriesSum += num / 9;
num = (num * z_squared) / ONE_20;
seriesSum += num / 11;
// 6 Taylor terms are sufficient for 36 decimal precision.
// Finally, we multiply by 2 (non fixed point) to compute ln(remainder)
seriesSum *= 2;
// We now have the sum of all x_n present, and the Taylor approximation of the logarithm of the remainder (both
// with 20 decimals). All that remains is to sum these two, and then drop two digits to return a 18 decimal
// value.
return (sum + seriesSum) / 100;
}
/**
* @dev Intrnal high precision (36 decimal places) natural logarithm (ln(x)) with signed 18 decimal fixed point argument,
* for x close to one.
*
* Should only be used if x is between LN_36_LOWER_BOUND and LN_36_UPPER_BOUND.
*/
function _ln_36(int256 x) private pure returns (int256) {
// Since ln(1) = 0, a value of x close to one will yield a very small result, which makes using 36 digits
// worthwhile.
// First, we transform x to a 36 digit fixed point value.
x *= ONE_18;
// We will use the following Taylor expansion, which converges very rapidly. Let z = (x - 1) / (x + 1).
// ln(x) = 2 * (z + z^3 / 3 + z^5 / 5 + z^7 / 7 + ... + z^(2 * n + 1) / (2 * n + 1))
// Recall that 36 digit fixed point division requires multiplying by ONE_36, and multiplication requires
// division by ONE_36.
int256 z = ((x - ONE_36) * ONE_36) / (x + ONE_36);
int256 z_squared = (z * z) / ONE_36;
// num is the numerator of the series: the z^(2 * n + 1) term
int256 num = z;
// seriesSum holds the accumulated sum of each term in the series, starting with the initial z
int256 seriesSum = num;
// In each step, the numerator is multiplied by z^2
num = (num * z_squared) / ONE_36;
seriesSum += num / 3;
num = (num * z_squared) / ONE_36;
seriesSum += num / 5;
num = (num * z_squared) / ONE_36;
seriesSum += num / 7;
num = (num * z_squared) / ONE_36;
seriesSum += num / 9;
num = (num * z_squared) / ONE_36;
seriesSum += num / 11;
num = (num * z_squared) / ONE_36;
seriesSum += num / 13;
num = (num * z_squared) / ONE_36;
seriesSum += num / 15;
// 8 Taylor terms are sufficient for 36 decimal precision.
// All that remains is multiplying by 2 (non fixed point).
return seriesSum * 2;
}
}
// File contracts/Treasury.sol
pragma solidity ^0.7.6;
contract Treasury is Ownable, ITreasury {
using SafeMath for uint256;
using SafeERC20 for IERC20;
event Deposit(address indexed token, uint256 amount, uint256 value);
event Withdrawal(address indexed token, uint256 amount);
event ReservesManaged(address indexed token, address indexed manager, uint256 amount);
event ReservesUpdated(ReserveType indexed _type, uint256 totalReserves);
event RewardsMinted(address indexed caller, address indexed recipient, uint256 amount);
event UpdateReserveToken(address indexed token, bool isAdd);
event UpdateLiquidityToken(address indexed token, bool isAdd);
event UpdateReserveDepositor(address indexed depositor, bool isAdd);
event UpdateReserveManager(address indexed manager, bool isAdd);
event UpdateRewardManager(address indexed manager, bool isAdd);
event UpdatePolSpender(address indexed spender, bool isAdd);
event UpdateDiscount(address indexed token, uint256 discount);
event UpdatePriceOracle(address indexed token, address oracle);
event UpdatePolPercentage(address indexed token, uint256 percentage);
event UpdateContributorPercentage(uint256 percentage);
event UpdateLiabilityRatio(uint256 liabilityRatio);
uint256 private constant PRECISION = 1e18;
// The address of governor.
address public governor;
// The address of ALD token
address public immutable ald;
// The address of ALD DAO
address public immutable aldDAO;
// A list of reserve tokens. Push only, beware false-positives.
address[] public reserveTokens;
// Record whether an address is reserve token or not.
mapping(address => bool) public isReserveToken;
// A list of liquidity tokens. Push only, beware false-positives.
address[] public liquidityTokens;
// Record whether an address is liquidity token or not.
mapping(address => bool) public isLiquidityToken;
// A list of reserve depositors. Push only, beware false-positives.
address[] public reserveDepositors;
// Record whether an address is reserve depositor or not.
mapping(address => bool) public isReserveDepositor;
// Mapping from token address to price oracle address.
mapping(address => address) public priceOracle;
// A list of reserve managers. Push only, beware false-positives.
address[] public reserveManagers;
// Record whether an address is reserve manager or not.
mapping(address => bool) public isReserveManager;
// A list of reward managers. Push only, beware false-positives.
address[] public rewardManagers;
// Record whether an address is reward manager or not.
mapping(address => bool) public isRewardManager;
// Mapping from token address to discount factor. Multiplied by 1e18
mapping(address => uint256) public discount;
// A list of pol spenders. Push only, beware false-positives.
address[] public polSpenders;
// Record whether an address is pol spender or not.
mapping(address => bool) public isPolSpender;
// Mapping from token address to reserve amount belong to POL.
mapping(address => uint256) public polReserves;
// Mapping from token address to percentage of profit to POL. Multiplied by 1e18
mapping(address => uint256) public percentagePOL;
// The percentage of ALD to contributors. Multiplied by 1e18
uint256 public percentageContributor;
// The liability ratio used to calcalate ald price. Multiplied by 1e18
uint256 public liabilityRatio;
// The USD value of all reserves from main asset. Multiplied by 1e18
uint256 public totalReserveUnderlying;
// The USD value of all reserves from vault reward. Multiplied by 1e18
uint256 public totalReserveVaultReward;
// The USD value of all reserves from liquidity token. Multiplied by 1e18
uint256 public totalReserveLiquidityToken;
modifier onlyGovernor() {
require(msg.sender == governor || msg.sender == owner(), "Treasury: only governor");
_;
}
/// @param _ald The address of ALD token
/// @param _aldDAO The address of ALD DAO
constructor(address _ald, address _aldDAO) {
require(_ald != address(0), "Treasury: zero ald address");
require(_aldDAO != address(0), "Treasury: zero aldDAO address");
ald = _ald;
aldDAO = _aldDAO;
percentageContributor = 5e16; // 5%
liabilityRatio = 1e17; // 0.1
}
/********************************** View Functions **********************************/
/// @dev return the ALD bond price. mutipliled by 1e18
function aldBondPrice() public view returns (uint256) {
uint256 _totalReserve = totalReserveUnderlying.add(totalReserveVaultReward).add(totalReserveLiquidityToken);
uint256 _aldSupply = IERC20(ald).totalSupply();
return _totalReserve.mul(1e36).div(_aldSupply).div(liabilityRatio);
}
/// @dev return the amount of bond ALD given token and usd value, without discount.
/// @param _value The usd of token.
function bondOfWithoutDiscount(uint256 _value) public view returns (uint256) {
uint256 _aldSupply = IERC20(ald).totalSupply();
uint256 _totalReserve = totalReserveUnderlying.add(totalReserveVaultReward).add(totalReserveLiquidityToken);
uint256 x = _totalReserve.add(_value).mul(PRECISION).div(_totalReserve);
uint256 bond = LogExpMath.pow(x, liabilityRatio).sub(PRECISION).mul(_aldSupply).div(PRECISION);
return bond;
}
/// @dev return the usd value given token and amount.
/// @param _token The address of token.
/// @param _amount The amount of token.
function valueOf(address _token, uint256 _amount) public view override returns (uint256) {
return IPriceOracle(priceOracle[_token]).value(_token, _amount);
}
/// @dev return the amount of bond ALD given token and usd value.
/// @param _token The address of token.
/// @param _value The usd of token.
function bondOf(address _token, uint256 _value) public view override returns (uint256) {
return bondOfWithoutDiscount(_value).mul(discount[_token]).div(PRECISION);
}
/********************************** Mutated Functions **********************************/
/// @dev deposit token to bond ALD.
/// @param _type The type of deposited token.
/// @param _token The address of token.
/// @param _amount The amount of token.
function deposit(
ReserveType _type,
address _token,
uint256 _amount
) external override returns (uint256) {
require(isReserveToken[_token] || isLiquidityToken[_token], "Treasury: not accepted");
require(isReserveDepositor[msg.sender], "Treasury: not approved depositor");
IERC20(_token).safeTransferFrom(msg.sender, address(this), _amount);
uint256 _value = valueOf(_token, _amount);
uint256 _bond;
if (_type != ReserveType.NULL) {
// a portion of token should used as POL
uint256 _percentagePOL = percentagePOL[_token];
if (_percentagePOL > 0) {
polReserves[_token] = polReserves[_token].add(_amount.mul(_percentagePOL).div(PRECISION));
}
// mint bond ald to sender
_bond = bondOf(_token, _value);
IALD(ald).mint(msg.sender, _bond);
// mint extra ALD to ald DAO
uint256 _percentageContributor = percentageContributor;
if (percentageContributor > 0) {
IALD(ald).mint(aldDAO, _bond.mul(_percentageContributor).div(PRECISION - _percentageContributor));
}
// update reserves
if (_type == ReserveType.LIQUIDITY_TOKEN) {
totalReserveLiquidityToken = totalReserveLiquidityToken.add(_value);
emit ReservesUpdated(_type, totalReserveLiquidityToken);
} else if (_type == ReserveType.UNDERLYING) {
totalReserveUnderlying = totalReserveUnderlying.add(_value);
emit ReservesUpdated(_type, totalReserveUnderlying);
} else if (_type == ReserveType.VAULT_REWARD) {
totalReserveVaultReward = totalReserveVaultReward.add(_value);
emit ReservesUpdated(_type, totalReserveVaultReward);
} else {
revert("Treasury: invalid reserve type");
}
}
emit Deposit(_token, _amount, _value);
return _bond;
}
/// @dev withdraw token from POL.
/// @param _token The address of token.
/// @param _amount The amount of token.
function withdraw(address _token, uint256 _amount) external override {
require(isReserveToken[_token], "Treasury: not accepted");
require(isPolSpender[msg.sender], "Treasury: not approved spender");
require(_amount <= polReserves[_token], "Treasury: exceed pol reserve");
polReserves[_token] = polReserves[_token] - _amount;
IERC20(_token).safeTransfer(msg.sender, _amount);
emit Withdrawal(_token, _amount);
}
/// @dev manage token to earn passive yield.
/// @param _token The address of token.
/// @param _amount The amount of token.
function manage(address _token, uint256 _amount) external override {
require(isReserveToken[_token] || isLiquidityToken[_token], "Treasury: not accepted");
require(isReserveManager[msg.sender], "Treasury: not approved manager");
IERC20(_token).safeTransfer(msg.sender, _amount);
emit ReservesManaged(_token, msg.sender, _amount);
}
/// @dev mint ALD reward.
/// @param _recipient The address of to receive ALD token.
/// @param _amount The amount of token.
function mintRewards(address _recipient, uint256 _amount) external override {
require(isRewardManager[msg.sender], "Treasury: not approved manager");
IALD(ald).mint(_recipient, _amount);
emit RewardsMinted(msg.sender, _recipient, _amount);
}
/********************************** Restricted Functions **********************************/
function updateGovernor(address _governor) external onlyOwner {
governor = _governor;
}
/// @dev update reserve token
/// @param _token The address of token.
/// @param _isAdd Whether it is add or remove token.
function updateReserveToken(address _token, bool _isAdd) external onlyOwner {
_addOrRemoveAddress(reserveTokens, isReserveToken, _token, _isAdd);
emit UpdateReserveToken(_token, _isAdd);
}
/// @dev update liquidity token
/// @param _token The address of token.
/// @param _isAdd Whether it is add or remove token.
function updateLiquidityToken(address _token, bool _isAdd) external onlyOwner {
_addOrRemoveAddress(liquidityTokens, isLiquidityToken, _token, _isAdd);
emit UpdateLiquidityToken(_token, _isAdd);
}
/// @dev update reserve depositor
/// @param _depositor The address of depositor.
/// @param _isAdd Whether it is add or remove token.
function updateReserveDepositor(address _depositor, bool _isAdd) external onlyOwner {
_addOrRemoveAddress(reserveDepositors, isReserveDepositor, _depositor, _isAdd);
emit UpdateReserveDepositor(_depositor, _isAdd);
}
/// @dev update price oracle for token.
/// @param _token The address of token.
/// @param _oracle The address of price oracle.
function updatePriceOracle(address _token, address _oracle) external onlyOwner {
require(_oracle != address(0), "Treasury: zero address");
priceOracle[_token] = _oracle;
emit UpdatePriceOracle(_token, _oracle);
}
/// @dev update reserve manager.
/// @param _manager The address of manager.
/// @param _isAdd Whether it is add or remove token.
function updateReserveManager(address _manager, bool _isAdd) external onlyOwner {
_addOrRemoveAddress(reserveManagers, isReserveManager, _manager, _isAdd);
emit UpdateReserveManager(_manager, _isAdd);
}
/// @dev update reward manager.
/// @param _manager The address of manager.
/// @param _isAdd Whether it is add or remove token.
function updateRewardManager(address _manager, bool _isAdd) external onlyOwner {
_addOrRemoveAddress(rewardManagers, isRewardManager, _manager, _isAdd);
emit UpdateRewardManager(_manager, _isAdd);
}
/// @dev update discount factor for token.
/// @param _token The address of token.
/// @param _discount The discount factor. multipled by 1e18
function updateDiscount(address _token, uint256 _discount) external onlyGovernor {
discount[_token] = _discount;
emit UpdateDiscount(_token, _discount);
}
/// @dev update POL spender.
/// @param _spender The address of spender.
/// @param _isAdd Whether it is add or remove token.
function updatePolSpenders(address _spender, bool _isAdd) external onlyOwner {
_addOrRemoveAddress(polSpenders, isPolSpender, _spender, _isAdd);
emit UpdatePolSpender(_spender, _isAdd);
}
/// @dev update POL percentage for token.
/// @param _token The address of token.
/// @param _percentage The POL percentage. multipled by 1e18
function updatePercentagePOL(address _token, uint256 _percentage) external onlyOwner {
require(_percentage <= PRECISION, "Treasury: percentage too large");
percentagePOL[_token] = _percentage;
emit UpdatePolPercentage(_token, _percentage);
}
/// @dev update contributor percentage.
/// @param _percentage The contributor percentage. multipled by 1e18
function updatePercentageContributor(uint256 _percentage) external onlyOwner {
require(_percentage <= PRECISION, "Treasury: percentage too large");
percentageContributor = _percentage;
emit UpdateContributorPercentage(_percentage);
}
/// @dev update protocol liability ratio
/// @param _liabilityRatio The liability ratio. multipled by 1e18
function updateLiabilityRatio(uint256 _liabilityRatio) external onlyOwner {
liabilityRatio = _liabilityRatio;
emit UpdateLiabilityRatio(_liabilityRatio);
}
/// @dev update protocol reserves
/// @param _totalReserveUnderlying The underlying reserve.
/// @param _totalReserveVaultReward The vault reward reserve.
/// @param _totalReserveLiquidityToken The liquidity token reserve.
function updateReserves(
uint256 _totalReserveUnderlying,
uint256 _totalReserveVaultReward,
uint256 _totalReserveLiquidityToken
) external onlyGovernor {
totalReserveUnderlying = _totalReserveUnderlying;
totalReserveVaultReward = _totalReserveVaultReward;
totalReserveLiquidityToken = _totalReserveLiquidityToken;
emit ReservesUpdated(ReserveType.UNDERLYING, _totalReserveUnderlying);
emit ReservesUpdated(ReserveType.VAULT_REWARD, _totalReserveVaultReward);
emit ReservesUpdated(ReserveType.LIQUIDITY_TOKEN, _totalReserveLiquidityToken);
}
/********************************** Internal Functions **********************************/
function _containAddress(address[] storage _list, address _item) internal view returns (bool) {
for (uint256 i = 0; i < _list.length; i++) {
if (_list[i] == _item) {
return true;
}
}
return false;
}
function _addOrRemoveAddress(
address[] storage _list,
mapping(address => bool) storage _status,
address _item,
bool _isAdd
) internal {
require(_item != address(0), "Treasury: zero address");
if (_isAdd) {
require(!_status[_item], "Treasury: already set");
if (!_containAddress(_list, _item)) {
_list.push(_item);
}
_status[_item] = true;
} else {
require(_status[_item], "Treasury: already unset");
_status[_item] = false;
}
}
}
|
mint ALD reward. _recipient The address of to receive ALD token. _amount The amount of token.
|
function mintRewards(address _recipient, uint256 _amount) external override {
require(isRewardManager[msg.sender], "Treasury: not approved manager");
IALD(ald).mint(_recipient, _amount);
emit RewardsMinted(msg.sender, _recipient, _amount);
}
| 2,108,269 |
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
library Lib_RingBuffer {
using Lib_RingBuffer for RingBuffer;
/***********
* Structs *
***********/
struct Buffer {
uint256 length;
mapping (uint256 => bytes32) buf;
}
struct RingBuffer {
bytes32 contextA;
bytes32 contextB;
Buffer bufferA;
Buffer bufferB;
uint256 nextOverwritableIndex;
}
struct RingBufferContext {
// contextA
uint40 globalIndex;
bytes27 extraData;
// contextB
uint64 currBufferIndex;
uint40 prevResetIndex;
uint40 currResetIndex;
}
/*************
* Constants *
*************/
uint256 constant MIN_CAPACITY = 16;
/**********************
* Internal Functions *
**********************/
/**
* Pushes a single element to the buffer.
* @param _self Buffer to access.
* @param _value Value to push to the buffer.
* @param _extraData Optional global extra data.
*/
function push(
RingBuffer storage _self,
bytes32 _value,
bytes27 _extraData
)
internal
{
RingBufferContext memory ctx = _self.getContext();
Buffer storage currBuffer = _self.getBuffer(ctx.currBufferIndex);
// Set a minimum capacity.
if (currBuffer.length == 0) {
currBuffer.length = MIN_CAPACITY;
}
// Check if we need to expand the buffer.
if (ctx.globalIndex - ctx.currResetIndex >= currBuffer.length) {
if (ctx.currResetIndex < _self.nextOverwritableIndex) {
// We're going to overwrite the inactive buffer.
// Bump the buffer index, reset the delete offset, and set our reset indices.
ctx.currBufferIndex++;
ctx.prevResetIndex = ctx.currResetIndex;
ctx.currResetIndex = ctx.globalIndex;
// Swap over to the next buffer.
currBuffer = _self.getBuffer(ctx.currBufferIndex);
} else {
// We're not overwriting yet, double the length of the current buffer.
currBuffer.length *= 2;
}
}
// Index to write to is the difference of the global and reset indices.
uint256 writeHead = ctx.globalIndex - ctx.currResetIndex;
currBuffer.buf[writeHead] = _value;
// Bump the global index and insert our extra data, then save the context.
ctx.globalIndex++;
ctx.extraData = _extraData;
_self.setContext(ctx);
}
/**
* Pushes a single element to the buffer.
* @param _self Buffer to access.
* @param _value Value to push to the buffer.
*/
function push(
RingBuffer storage _self,
bytes32 _value
)
internal
{
RingBufferContext memory ctx = _self.getContext();
_self.push(
_value,
ctx.extraData
);
}
/**
* Pushes a two elements to the buffer.
* @param _self Buffer to access.
* @param _valueA First value to push to the buffer.
* @param _valueA Second value to push to the buffer.
* @param _extraData Optional global extra data.
*/
function push2(
RingBuffer storage _self,
bytes32 _valueA,
bytes32 _valueB,
bytes27 _extraData
)
internal
{
_self.push(_valueA, _extraData);
_self.push(_valueB, _extraData);
}
/**
* Pushes a two elements to the buffer.
* @param _self Buffer to access.
* @param _valueA First value to push to the buffer.
* @param _valueA Second value to push to the buffer.
*/
function push2(
RingBuffer storage _self,
bytes32 _valueA,
bytes32 _valueB
)
internal
{
RingBufferContext memory ctx = _self.getContext();
_self.push2(
_valueA,
_valueB,
ctx.extraData
);
}
/**
* Retrieves an element from the buffer.
* @param _self Buffer to access.
* @param _index Element index to retrieve.
* @return Value of the element at the given index.
*/
function get(
RingBuffer storage _self,
uint256 _index
)
internal
view
returns (
bytes32
)
{
RingBufferContext memory ctx = _self.getContext();
require(
_index < ctx.globalIndex,
"Index out of bounds."
);
Buffer storage currBuffer = _self.getBuffer(ctx.currBufferIndex);
Buffer storage prevBuffer = _self.getBuffer(ctx.currBufferIndex + 1);
if (_index >= ctx.currResetIndex) {
// We're trying to load an element from the current buffer.
// Relative index is just the difference from the reset index.
uint256 relativeIndex = _index - ctx.currResetIndex;
// Shouldn't happen but why not check.
require(
relativeIndex < currBuffer.length,
"Index out of bounds."
);
return currBuffer.buf[relativeIndex];
} else {
// We're trying to load an element from the previous buffer.
// Relative index is the difference from the reset index in the other direction.
uint256 relativeIndex = ctx.currResetIndex - _index;
// Condition only fails in the case that we deleted and flipped buffers.
require(
ctx.currResetIndex > ctx.prevResetIndex,
"Index out of bounds."
);
// Make sure we're not trying to read beyond the array.
require(
relativeIndex <= prevBuffer.length,
"Index out of bounds."
);
return prevBuffer.buf[prevBuffer.length - relativeIndex];
}
}
/**
* Deletes all elements after (and including) a given index.
* @param _self Buffer to access.
* @param _index Index of the element to delete from (inclusive).
* @param _extraData Optional global extra data.
*/
function deleteElementsAfterInclusive(
RingBuffer storage _self,
uint40 _index,
bytes27 _extraData
)
internal
{
RingBufferContext memory ctx = _self.getContext();
require(
_index < ctx.globalIndex && _index >= ctx.prevResetIndex,
"Index out of bounds."
);
Buffer storage currBuffer = _self.getBuffer(ctx.currBufferIndex);
Buffer storage prevBuffer = _self.getBuffer(ctx.currBufferIndex + 1);
if (_index < ctx.currResetIndex) {
// We're switching back to the previous buffer.
// Reduce the buffer index, set the current reset index back to match the previous one.
// We use the equality of these two values to prevent reading beyond this buffer.
ctx.currBufferIndex--;
ctx.currResetIndex = ctx.prevResetIndex;
}
// Set our global index and extra data, save the context.
ctx.globalIndex = _index;
ctx.extraData = _extraData;
_self.setContext(ctx);
}
/**
* Deletes all elements after (and including) a given index.
* @param _self Buffer to access.
* @param _index Index of the element to delete from (inclusive).
*/
function deleteElementsAfterInclusive(
RingBuffer storage _self,
uint40 _index
)
internal
{
RingBufferContext memory ctx = _self.getContext();
_self.deleteElementsAfterInclusive(
_index,
ctx.extraData
);
}
/**
* Retrieves the current global index.
* @param _self Buffer to access.
* @return Current global index.
*/
function getLength(
RingBuffer storage _self
)
internal
view
returns (
uint40
)
{
RingBufferContext memory ctx = _self.getContext();
return ctx.globalIndex;
}
/**
* Changes current global extra data.
* @param _self Buffer to access.
* @param _extraData New global extra data.
*/
function setExtraData(
RingBuffer storage _self,
bytes27 _extraData
)
internal
{
RingBufferContext memory ctx = _self.getContext();
ctx.extraData = _extraData;
_self.setContext(ctx);
}
/**
* Retrieves the current global extra data.
* @param _self Buffer to access.
* @return Current global extra data.
*/
function getExtraData(
RingBuffer storage _self
)
internal
view
returns (
bytes27
)
{
RingBufferContext memory ctx = _self.getContext();
return ctx.extraData;
}
/**
* Sets the current ring buffer context.
* @param _self Buffer to access.
* @param _ctx Current ring buffer context.
*/
function setContext(
RingBuffer storage _self,
RingBufferContext memory _ctx
)
internal
returns (
bytes32
)
{
bytes32 contextA;
bytes32 contextB;
uint40 globalIndex = _ctx.globalIndex;
bytes27 extraData = _ctx.extraData;
assembly {
contextA := globalIndex
contextA := or(contextA, extraData)
}
uint64 currBufferIndex = _ctx.currBufferIndex;
uint40 prevResetIndex = _ctx.prevResetIndex;
uint40 currResetIndex = _ctx.currResetIndex;
assembly {
contextB := currBufferIndex
contextB := or(contextB, shl(64, prevResetIndex))
contextB := or(contextB, shl(104, currResetIndex))
}
if (_self.contextA != contextA) {
_self.contextA = contextA;
}
if (_self.contextB != contextB) {
_self.contextB = contextB;
}
}
/**
* Retrieves the current ring buffer context.
* @param _self Buffer to access.
* @return Current ring buffer context.
*/
function getContext(
RingBuffer storage _self
)
internal
view
returns (
RingBufferContext memory
)
{
bytes32 contextA = _self.contextA;
bytes32 contextB = _self.contextB;
uint40 globalIndex;
bytes27 extraData;
assembly {
globalIndex := and(contextA, 0x000000000000000000000000000000000000000000000000000000FFFFFFFFFF)
extraData := and(contextA, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000000000)
}
uint64 currBufferIndex;
uint40 prevResetIndex;
uint40 currResetIndex;
assembly {
currBufferIndex := and(contextB, 0x000000000000000000000000000000000000000000000000FFFFFFFFFFFFFFFF)
prevResetIndex := shr(64, and(contextB, 0x00000000000000000000000000000000000000FFFFFFFFFF0000000000000000))
currResetIndex := shr(104, and(contextB, 0x0000000000000000000000000000FFFFFFFFFF00000000000000000000000000))
}
return RingBufferContext({
globalIndex: globalIndex,
extraData: extraData,
currBufferIndex: currBufferIndex,
prevResetIndex: prevResetIndex,
currResetIndex: currResetIndex
});
}
/**
* Retrieves the a buffer from the ring buffer by index.
* @param _self Buffer to access.
* @param _which Index of the sub buffer to access.
* @return Sub buffer for the index.
*/
function getBuffer(
RingBuffer storage _self,
uint256 _which
)
internal
view
returns (
Buffer storage
)
{
return _which % 2 == 0 ? _self.bufferA : _self.bufferB;
}
}
|
Pushes a single element to the buffer. _self Buffer to access. _value Value to push to the buffer./
|
function push(
RingBuffer storage _self,
bytes32 _value
)
internal
{
RingBufferContext memory ctx = _self.getContext();
_self.push(
_value,
ctx.extraData
);
}
| 6,403,437 |
pragma solidity 0.4.19;
/**
* Owned Contract
*
* This is a contract trait to inherit from. Contracts that inherit from Owned
* are able to modify functions to be only callable by the owner of the
* contract.
*
* By default it is impossible to change the owner of the contract.
*/
contract Owned {
/**
* Contract owner.
*
* This value is set at contract creation time.
*/
address owner;
/**
* Contract constructor.
*
* This sets the owner of the Owned contract at the time of contract
* creation.
*/
function Owned() public {
owner = msg.sender;
}
/**
* Modify method to only allow the owner to call it.
*/
modifier onlyOwner {
require(msg.sender == owner);
_;
}
}
/**
* Aethia Omega Egg Sale Contract.
*
* Every day, for a period of five (5) days, starting February 12th 12:00:00
* UTC, this contract is allowed to sell a maximum of one-hundred-and-twenty
* (120) omega Ethergotchi eggs, for a total of six-hundred (600) eggs.
*
* These one-hundred-and-twenty eggs are divided over the twelve (12) time slots
* of two (2) hours that make up each day. Every two hours, ten (10) omega
* Ethergotchi eggs are available for 0.09 ether (excluding the gas cost of a
* transaction).
*
* Any omega eggs that remain at the end of a time slot are not transferred to
* the next time slot.
*/
contract OmegaEggSale is Owned {
/**
* The start date of the omega egg sale in seconds since the UNIX epoch.
*
* This value is equivalent to February 12th, 12:00:00 UTC, on a 24 hour
* clock.
*/
uint256 constant START_DATE = 1518436800;
/**
* The end date of the omega egg sale in seconds since the UNIX epoch.
*
* This value is equivalent to February 17th, 12:00:00 UTC, on a 24 hour
* clock.
*/
uint256 constant END_DATE = 1518868800;
/**
* The amount of seconds within a single time slot.
*
* This is set to a total of two hours:
* 2 x 60 x 60 = 7200 seconds
*/
uint16 constant SLOT_DURATION_IN_SECONDS = 7200;
/**
* The number of remaining eggs in each time slot.
*
* This is initially set to ten for each time slot.
*/
mapping (uint8 => uint8) remainingEggs;
/**
* Omega egg owners.
*
* This is a mapping containing all owners of omega eggs. While this does
* not prevent people from using multiple addresses to buy multiple omega
* eggs, it does increase the difficulty slightly.
*/
mapping (address => bool) eggOwners;
/**
* Omega egg sale event.
*
* For audit and logging purposes, all omega egg sales are logged by
* acquirer and acquisition date.
*/
event LogOmegaEggSale(address indexed _acquirer, uint256 indexed _date);
/**
* Contract constructor
*
* This generates all omega egg time slots and the amount of available
* omega eggs within each time slot. The generation is done by calculating
* the total amount of seconds within the sale period together with the
* amount of seconds within each time slot, and dividing the former by the
* latter for the number of time slots.
*
* Each time slot is then assigned ten omega eggs.
*/
function OmegaEggSale() Owned() public {
uint256 secondsInSalePeriod = END_DATE - START_DATE;
uint8 timeSlotCount = uint8(
secondsInSalePeriod / SLOT_DURATION_IN_SECONDS
);
for (uint8 i = 0; i < timeSlotCount; i++) {
remainingEggs[i] = 10;
}
}
/**
* Buy omega egg from the OmegaEggSale contract.
*
* The cost of an omega egg is 0.09 ether. This contract accepts any amount
* equal or above 0.09 ether to buy an omega egg. In the case of higher
* amounts being sent, the contract will refund the difference.
*
* To successully buy an omega egg, five conditions have to be met:
* 1. The `buyOmegaEgg` method must be called.
* 2. A value of 0.09 or more ether must accompany the transaction.
* 3. The transaction occurs in between February 12th 12:00:00 UTC and
* February 17th 12:00:00 UTC.
* 4. The time slot in which the transaction occurs has omega eggs
* available.
* 5. The sender must not already have bought an omega egg.
*/
function buyOmegaEgg() payable external {
require(msg.value >= 0.09 ether);
require(START_DATE <= now && now < END_DATE);
require(eggOwners[msg.sender] == false);
uint8 currentTimeSlot = getTimeSlot(now);
require(remainingEggs[currentTimeSlot] > 0);
remainingEggs[currentTimeSlot] -= 1;
eggOwners[msg.sender] = true;
LogOmegaEggSale(msg.sender, now);
// Send back any remaining value
if (msg.value > 0.09 ether) {
msg.sender.transfer(msg.value - 0.09 ether);
}
}
/**
* Fallback payable method.
*
* This is in the case someone calls the contract without specifying the
* correct method to call. This method will ensure the failure of a
* transaction that was wrongfully executed.
*/
function () payable external {
revert();
}
/**
* Return number of eggs remaining in given time slot.
*
* If the time slot is not valid (e.g. the time slot does not exist
* according to the this contract), the number of remaining eggs will
* default to zero (0).
*
* This method is intended for external viewing purposes.
*
* Parameters
* ----------
* _timeSlot : uint8
* The time slot to return the number of remaining eggs for.
*
* Returns
* -------
* uint8
* The number of eggs still available within the contract for given
* time slot.
*/
function eggsInTimeSlot(uint8 _timeSlot) view external returns (uint8) {
return remainingEggs[_timeSlot];
}
/**
* Return true if `_buyer` has bought an omega egg, otherwise false.
*
* This method is intended for external viewing purposes.
*
* Parameters
* ----------
* _buyer : address
* The Ethereum wallet address of the buyer.
*
* Returns
* -------
* bool
* True if `_buyer` has bought an egg, otherwise false.
*/
function hasBoughtEgg(address _buyer) view external returns (bool) {
return eggOwners[_buyer] == true;
}
/**
* Withdraw all funds from contract.
*
* This method can only be called after the OmegaEggSale contract has run
* its course.
*/
function withdraw() onlyOwner external {
require(now >= END_DATE);
owner.transfer(this.balance);
}
/**
* Calculate the time slot corresponding to the given UNIX timestamp.
*
* The time slot is calculated by subtracting the current date and time in
* seconds from the contract's starting date and time in seconds. The result
* is then divided by the number of seconds within a time slot, and rounded
* down to get the correct time slot.
*
* Parameters
* ----------
* _timestamp : uint256
* The timestamp to calculate a timeslot for. This is the amount of
* seconds elapsed since the UNIX epoch.
*
* Returns
* -------
* uint8
* The OmegaEggSale time slot corresponding to the given timestamp.
* This can be a non-existent time slot, if the timestamp is further
* in the future than `END_DATE`.
*/
function getTimeSlot(uint256 _timestamp) private pure returns (uint8) {
uint256 secondsSinceSaleStart = _timestamp - START_DATE;
return uint8(secondsSinceSaleStart / SLOT_DURATION_IN_SECONDS);
}
}
|
Buy omega egg from the OmegaEggSale contract. The cost of an omega egg is 0.09 ether. This contract accepts any amount equal or above 0.09 ether to buy an omega egg. In the case of higher amounts being sent, the contract will refund the difference. To successully buy an omega egg, five conditions have to be met: 1. The `buyOmegaEgg` method must be called. 2. A value of 0.09 or more ether must accompany the transaction. 3. The transaction occurs in between February 12th 12:00:00 UTC and February 17th 12:00:00 UTC. 4. The time slot in which the transaction occurs has omega eggs available. 5. The sender must not already have bought an omega egg./ Send back any remaining value
|
function buyOmegaEgg() payable external {
require(msg.value >= 0.09 ether);
require(START_DATE <= now && now < END_DATE);
require(eggOwners[msg.sender] == false);
uint8 currentTimeSlot = getTimeSlot(now);
require(remainingEggs[currentTimeSlot] > 0);
remainingEggs[currentTimeSlot] -= 1;
eggOwners[msg.sender] = true;
LogOmegaEggSale(msg.sender, now);
if (msg.value > 0.09 ether) {
msg.sender.transfer(msg.value - 0.09 ether);
}
}
| 881,482 |
./partial_match/1/0x9156c5a5d82580b2D00eD40C6B43414f966Ec516/sources/MultichainProvider.sol
|
Sets the controller This function can be called by the owner only controllerAddr The address of the controller/ Checks State changes
|
function setController (address controllerAddr) public onlyOwner {
require(controllerAddr != address(0), "Controller address required");
require(controllerAddr != owner, "Owner cannot be the Controller");
require(controllerAddr != controllerAddress, "Controller already set");
emit OnControllerChanged(controllerAddress, controllerAddr);
controllerAddress = controllerAddr;
}
| 9,377,855 |
/**
*Submitted for verification at Etherscan.io on 2021-01-20
*/
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity >=0.7.6;
pragma abicoder v2;
interface IStakePoolCreator {
function version() external returns (uint256);
function create() external returns (address);
}
interface IStakePoolController {
event MasterCreated(address indexed farm, address indexed pair, uint256 version, address timelock, address stakePoolRewardFund, uint256 totalStakePool);
event SetWhitelistStakingFor(address indexed contractAddress, bool value);
event SetWhitelistStakePool(address indexed contractAddress, int8 value);
event SetStakePoolCreator(address indexed contractAddress, uint256 verion);
event SetWhitelistRewardRebaser(address indexed contractAddress, bool value);
event SetWhitelistRewardMultiplier(address indexed contractAddress, bool value);
event SetStakePoolVerifier(address indexed contractAddress, bool value);
event ChangeGovernance(address indexed governance);
event SetFeeCollector(address indexed feeCollector);
event SetFeeToken(address indexed token);
event SetFeeAmount(uint256 indexed amount);
struct PoolRewardInfo {
address rewardToken;
address rewardRebaser;
address rewardMultiplier;
uint256 startBlock;
uint256 endRewardBlock;
uint256 rewardPerBlock;
uint256 lockRewardPercent;
uint256 startVestingBlock;
uint256 endVestingBlock;
uint256 unstakingFrozenTime;
uint256 rewardFundAmount;
}
function allStakePools(uint256) external view returns (address stakePool);
function isStakePool(address contractAddress) external view returns (bool);
function isStakePoolVerifier(address contractAddress) external view returns (bool);
function isWhitelistStakingFor(address contractAddress) external view returns (bool);
function isWhitelistStakePool(address contractAddress) external view returns (int8);
function setStakePoolVerifier(address contractAddress, bool state) external;
function setWhitelistStakingFor(address contractAddress, bool state) external;
function setWhitelistStakePool(address contractAddress, int8 state) external;
function addStakePoolCreator(address contractAddress) external;
function isWhitelistRewardRebaser(address contractAddress) external view returns (bool);
function setWhitelistRewardRebaser(address contractAddress, bool state) external;
function isWhitelistRewardMultiplier(address contractAddress) external view returns (bool);
function setWhitelistRewardMultiplier(address contractAddress, bool state) external;
function allStakePoolsLength() external view returns (uint256);
function create(
uint256 version,
address pair,
uint256 delayTimeLock,
PoolRewardInfo calldata poolRewardInfo,
uint8 flag
) external returns (address);
function createPair(
uint256 version,
address tokenA,
address tokenB,
uint32 tokenWeightA,
uint32 swapFee,
uint256 delayTimeLock,
PoolRewardInfo calldata poolRewardInfo,
uint8 flag
) external returns (address);
function setGovernance(address) external;
function setFeeCollector(address _address) external;
function setFeeToken(address _token) external;
function setFeeAmount(uint256 _token) external;
}
interface IValueLiquidRouter {
struct Swap {
address pool;
address tokenIn;
address tokenOut;
uint256 swapAmount; // tokenInAmount / tokenOutAmount
uint256 limitReturnAmount; // minAmountOut / maxAmountIn
uint256 maxPrice;
bool isBPool;
}
function factory() external view returns (address);
function controller() external view returns (address);
function formula() external view returns (address);
function WETH() external view returns (address);
function addLiquidity(
address pair,
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 pair,
address token,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
)
external
payable
returns (
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
);
function swapExactTokensForTokens(
address tokenIn,
address tokenOut,
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline,
uint8 flag
) external returns (uint256[] memory amounts);
function swapTokensForExactTokens(
address tokenIn,
address tokenOut,
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline,
uint8 flag
) external returns (uint256[] memory amounts);
function swapExactETHForTokens(
address tokenOut,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline,
uint8 flag
) external payable returns (uint256[] memory amounts);
function swapTokensForExactETH(
address tokenIn,
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline,
uint8 flag
) external returns (uint256[] memory amounts);
function swapExactTokensForETH(
address tokenIn,
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline,
uint8 flag
) external returns (uint256[] memory amounts);
function swapETHForExactTokens(
address tokenOut,
uint256 amountOut,
address[] calldata path,
address to,
uint256 deadline,
uint8 flag
) external payable returns (uint256[] memory amounts);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
address tokenIn,
address tokenOut,
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline,
uint8 flag
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
address tokenOut,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline,
uint8 flag
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
address tokenIn,
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline,
uint8 flag
) external;
function addStakeLiquidity(
address stakePool,
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
uint256 deadline
)
external
returns (
uint256 amountA,
uint256 amountB,
uint256 liquidity
);
function addStakeLiquidityETH(
address stakePool,
address token,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountETHMin,
uint256 deadline
)
external
payable
returns (
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
);
function multihopBatchSwapExactIn(
Swap[][] memory swapSequences,
address tokenIn,
address tokenOut,
uint256 totalAmountIn,
uint256 minTotalAmountOut,
uint256 deadline,
uint8 flag
) external payable returns (uint256 totalAmountOut);
function multihopBatchSwapExactOut(
Swap[][] memory swapSequences,
address tokenIn,
address tokenOut,
uint256 maxTotalAmountIn,
uint256 deadline,
uint8 flag
) external payable returns (uint256 totalAmountIn);
}
interface IValueLiquidFactory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint32 tokenWeight0, uint32 swapFee, uint256);
function feeTo() external view returns (address);
function formula() external view returns (address);
function protocolFee() external view returns (uint256);
function feeToSetter() external view returns (address);
function getPair(
address tokenA,
address tokenB,
uint32 tokenWeightA,
uint32 swapFee
) external view returns (address pair);
function allPairs(uint256) external view returns (address pair);
function isPair(address) external view returns (bool);
function allPairsLength() external view returns (uint256);
function createPair(
address tokenA,
address tokenB,
uint32 tokenWeightA,
uint32 swapFee
) external returns (address pair);
function getWeightsAndSwapFee(address pair)
external
view
returns (
uint32 tokenWeight0,
uint32 tokenWeight1,
uint32 swapFee
);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
function setProtocolFee(uint256) external;
}
interface IStakePool {
event Deposit(address indexed account, uint256 amount);
event AddRewardPool(uint256 indexed poolId);
event UpdateRewardPool(uint256 indexed poolId, uint256 endRewardBlock, uint256 rewardPerBlock);
event PayRewardPool(
uint256 indexed poolId,
address indexed rewardToken,
address indexed account,
uint256 pendingReward,
uint256 rebaseAmount,
uint256 paidReward
);
event UpdateRewardRebaser(uint256 indexed poolId, address rewardRebaser);
event UpdateRewardMultiplier(uint256 indexed poolId, address rewardMultiplier);
event Withdraw(address indexed account, uint256 amount);
function version() external returns (uint256);
function pair() external returns (address);
function initialize(
address _pair,
uint256 _unstakingFrozenTime,
address _rewardFund,
address _timelock
) external;
function stake(uint256) external;
function stakeFor(address _account) external;
function withdraw(uint256) external;
function getReward(uint8 _pid, address _account) external;
function getAllRewards(address _account) external;
function pendingReward(uint8 _pid, address _account) external view returns (uint256);
function getEndRewardBlock(uint8 _pid) external view returns (address, uint256);
function getRewardPerBlock(uint8 pid) external view returns (uint256);
function rewardPoolInfoLength() external view returns (uint256);
function unfrozenStakeTime(address _account) external view returns (uint256);
function emergencyWithdraw() external;
function updateReward() external;
function updateReward(uint8 _pid) external;
function updateRewardPool(
uint8 _pid,
uint256 _endRewardBlock,
uint256 _rewardPerBlock
) external;
function getRewardMultiplier(
uint8 _pid,
uint256 _from,
uint256 _to,
uint256 _rewardPerBlock
) external view returns (uint256);
function getRewardRebase(
uint8 _pid,
address _rewardToken,
uint256 _pendingReward
) external view returns (uint256);
function updateRewardRebaser(uint8 _pid, address _rewardRebaser) external;
function updateRewardMultiplier(uint8 _pid, address _rewardMultiplier) external;
function getUserInfo(uint8 _pid, address _account)
external
view
returns (
uint256 amount,
uint256 rewardDebt,
uint256 accumulatedEarned,
uint256 lockReward,
uint256 lockRewardReleased
);
function addRewardPool(
address _rewardToken,
address _rewardRebaser,
address _rewardMultiplier,
uint256 _startBlock,
uint256 _endRewardBlock,
uint256 _rewardPerBlock,
uint256 _lockRewardPercent,
uint256 _startVestingBlock,
uint256 _endVestingBlock
) external;
function removeLiquidity(
address provider,
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) external returns (uint256 amountA, uint256 amountB);
function removeLiquidityETH(
address provider,
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountToken, uint256 amountETH);
function removeLiquidityETHSupportingFeeOnTransferTokens(
address provider,
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountETH);
}
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), "TransferHelper: APPROVE_FAILED");
}
function safeTransfer(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), "TransferHelper: TRANSFER_FAILED");
}
function safeTransferFrom(
address token,
address from,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), "TransferHelper: TRANSFER_FROM_FAILED");
}
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, "TransferHelper: ETH_TRANSFER_FAILED");
}
}
interface IValueLiquidPair {
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint256);
function balanceOf(address owner) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 value) external returns (bool);
function transfer(address to, uint256 value) external returns (bool);
function transferFrom(
address from,
address to,
uint256 value
) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint256);
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
event PaidProtocolFee(uint112 collectedFee0, uint112 collectedFee1);
event Mint(address indexed sender, uint256 amount0, uint256 amount1);
event Burn(address indexed sender, uint256 amount0, uint256 amount1, address indexed to);
event Swap(address indexed sender, uint256 amount0In, uint256 amount1In, uint256 amount0Out, uint256 amount1Out, address indexed to);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint256);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves()
external
view
returns (
uint112 reserve0,
uint112 reserve1,
uint32 blockTimestampLast
);
function getCollectedFees() external view returns (uint112 _collectedFee0, uint112 _collectedFee1);
function getTokenWeights() external view returns (uint32 tokenWeight0, uint32 tokenWeight1);
function getSwapFee() external view returns (uint32);
function price0CumulativeLast() external view returns (uint256);
function price1CumulativeLast() external view returns (uint256);
function mint(address to) external returns (uint256 liquidity);
function burn(address to) external returns (uint256 amount0, uint256 amount1);
function swap(
uint256 amount0Out,
uint256 amount1Out,
address to,
bytes calldata data
) external;
function skim(address to) external;
function sync() external;
function initialize(
address,
address,
uint32,
uint32
) external;
}
// a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math)
library SafeMath {
function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x + y) >= x, "ds-math-add-overflow");
}
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x - y) <= x, "ds-math-sub-underflow");
}
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(y == 0 || (z = x * y) / y == x, "ds-math-mul-overflow");
}
function div(uint256 a, uint256 b) internal pure returns (uint256 c) {
require(b > 0, "ds-math-division-by-zero");
c = a / b;
}
}
contract TimeLock {
using SafeMath for uint256;
event NewAdmin(address indexed newAdmin);
event NewPendingAdmin(address indexed newPendingAdmin);
event NewDelay(uint256 indexed newDelay);
event CancelTransaction(bytes32 indexed txHash, address indexed target, uint256 value, string signature, bytes data, uint256 eta);
event ExecuteTransaction(bytes32 indexed txHash, address indexed target, uint256 value, string signature, bytes data, uint256 eta);
event QueueTransaction(bytes32 indexed txHash, address indexed target, uint256 value, string signature, bytes data, uint256 eta);
uint256 public constant GRACE_PERIOD = 14 days;
uint256 public constant MINIMUM_DELAY = 2 days;
uint256 public constant MAXIMUM_DELAY = 30 days;
bool private _initialized;
address public admin;
address public pendingAdmin;
uint256 public delay;
bool public admin_initialized;
mapping(bytes32 => bool) public queuedTransactions;
constructor() {
admin_initialized = false;
_initialized = false;
}
function initialize(address _admin, uint256 _delay) public {
require(_initialized == false, "Timelock::constructor: Initialized must be false.");
require(_delay >= MINIMUM_DELAY, "Timelock::setDelay: Delay must exceed minimum delay.");
require(_delay <= MAXIMUM_DELAY, "Timelock::setDelay: Delay must not exceed maximum delay.");
delay = _delay;
admin = _admin;
_initialized = true;
emit NewAdmin(admin);
emit NewDelay(delay);
}
receive() external payable {}
function setDelay(uint256 _delay) public {
require(msg.sender == address(this), "Timelock::setDelay: Call must come from Timelock.");
require(_delay >= MINIMUM_DELAY, "Timelock::setDelay: Delay must exceed minimum delay.");
require(_delay <= MAXIMUM_DELAY, "Timelock::setDelay: Delay must not exceed maximum delay.");
delay = _delay;
emit NewDelay(delay);
}
function acceptAdmin() public {
require(msg.sender == pendingAdmin, "Timelock::acceptAdmin: Call must come from pendingAdmin.");
admin = msg.sender;
pendingAdmin = address(0);
emit NewAdmin(admin);
}
function setPendingAdmin(address _pendingAdmin) public {
// allows one time setting of admin for deployment purposes
if (admin_initialized) {
require(msg.sender == address(this), "Timelock::setPendingAdmin: Call must come from Timelock.");
} else {
require(msg.sender == admin, "Timelock::setPendingAdmin: First call must come from admin.");
admin_initialized = true;
}
pendingAdmin = _pendingAdmin;
emit NewPendingAdmin(pendingAdmin);
}
function queueTransaction(
address target,
uint256 value,
string memory signature,
bytes memory data,
uint256 eta
) public returns (bytes32) {
require(msg.sender == admin, "Timelock::queueTransaction: Call must come from admin.");
require(eta >= getBlockTimestamp().add(delay), "Timelock::queueTransaction: Estimated execution block must satisfy delay.");
bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta));
queuedTransactions[txHash] = true;
emit QueueTransaction(txHash, target, value, signature, data, eta);
return txHash;
}
function cancelTransaction(
address target,
uint256 value,
string memory signature,
bytes memory data,
uint256 eta
) public {
require(msg.sender == admin, "Timelock::cancelTransaction: Call must come from admin.");
bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta));
queuedTransactions[txHash] = false;
emit CancelTransaction(txHash, target, value, signature, data, eta);
}
function executeTransaction(
address target,
uint256 value,
string memory signature,
bytes memory data,
uint256 eta
) public payable returns (bytes memory) {
require(msg.sender == admin, "Timelock::executeTransaction: Call must come from admin.");
bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta));
require(queuedTransactions[txHash], "Timelock::executeTransaction: Transaction hasn't been queued.");
require(getBlockTimestamp() >= eta, "Timelock::executeTransaction: Transaction hasn't surpassed time lock.");
require(getBlockTimestamp() <= eta.add(GRACE_PERIOD), "Timelock::executeTransaction: Transaction is stale.");
queuedTransactions[txHash] = false;
bytes memory callData;
if (bytes(signature).length == 0) {
callData = data;
} else {
callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), data);
}
// solium-disable-next-line security/no-call-value
(bool success, bytes memory returnData) = target.call{value: value}(callData);
require(success, "Timelock::executeTransaction: Transaction execution reverted.");
emit ExecuteTransaction(txHash, target, value, signature, data, eta);
return returnData;
}
function getBlockTimestamp() internal view returns (uint256) {
return block.timestamp;
}
}
interface IERC20 {
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
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 owner) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 value) external returns (bool);
function transfer(address to, uint256 value) external returns (bool);
function transferFrom(
address from,
address to,
uint256 value
) external returns (bool);
}
interface IStakePoolRewardFund {
function initialize(address _stakePool, address _timelock) external;
function safeTransfer(
address _token,
address _to,
uint256 _value
) external;
}
interface IStakePoolRewardRebaser {
function getRebaseAmount(address rewardToken, uint256 baseAmount) external view returns (uint256);
}
interface IStakePoolRewardMultiplier {
function getRewardMultiplier(
uint256 _start,
uint256 _end,
uint256 _from,
uint256 _to,
uint256 _rewardPerBlock
) external view returns (uint256);
}
contract StakePoolRewardFund is IStakePoolRewardFund {
uint256 public constant BLOCKS_PER_DAY = 6528;
address public stakePool;
address public timelock;
bool private _initialized;
function initialize(address _stakePool, address _timelock) external override {
require(_initialized == false, "StakePoolRewardFund: already initialized");
stakePool = _stakePool;
timelock = _timelock;
_initialized = true;
}
function safeTransfer(
address _token,
address _to,
uint256 _value
) external override {
require(msg.sender == stakePool, "StakePoolRewardFund: !stakePool");
TransferHelper.safeTransfer(_token, _to, _value);
}
function recoverRewardToken(
address _token,
uint256 _amount,
address _to
) external {
require(msg.sender == timelock, "StakePoolRewardFund: !timelock");
uint256 length = IStakePool(stakePool).rewardPoolInfoLength();
for (uint8 pid = 0; pid < length; ++pid) {
(address rewardToken, uint256 endRewardBlock) = IStakePool(stakePool).getEndRewardBlock(pid);
if (rewardToken == _token) {
// do not allow to drain reward token if less than 2 months after pool ends
require(block.number >= (endRewardBlock + (BLOCKS_PER_DAY * 30)), "StakePoolRewardFund: blockNumber < 30 days since endRewardBlock");
}
}
TransferHelper.safeTransfer(_token, _to, _amount);
}
}
interface IFreeFromUpTo {
function freeFromUpTo(address from, uint256 value) external returns (uint256 freed);
}
contract StakePoolController is IStakePoolController {
IValueLiquidFactory public swapFactory;
address public governance;
address public feeCollector;
address public feeToken;
uint256 public feeAmount;
mapping(address => bool) private _stakePools;
mapping(address => bool) private _whitelistStakingFor;
mapping(address => bool) private _whitelistRewardRebaser;
mapping(address => bool) private _whitelistRewardMultiplier;
mapping(address => int8) private _whitelistStakePools;
mapping(address => bool) public _stakePoolVerifiers;
mapping(uint256 => address) public stakePoolCreators;
address[] public override allStakePools;
bool private _initialized = false;
IFreeFromUpTo public constant chi = IFreeFromUpTo(0x0000000000004946c0e9F43F4Dee607b0eF1fA1c);
modifier discountCHI(uint8 flag) {
uint256 gasStart = gasleft();
_;
if ((flag & 0x1) == 1) {
uint256 gasSpent = 21000 + gasStart - gasleft() + 16 * msg.data.length;
chi.freeFromUpTo(msg.sender, (gasSpent + 14154) / 41130);
}
}
function initialize(address _swapFactory) public {
require(_initialized == false, "StakePoolController: initialized");
governance = msg.sender;
swapFactory = IValueLiquidFactory(_swapFactory);
_initialized = true;
}
function isStakePool(address b) external view override returns (bool) {
return _stakePools[b];
}
modifier onlyGovernance() {
require(msg.sender == governance, "StakePoolController: !governance");
_;
}
function setFeeCollector(address _address) external override onlyGovernance {
require(_address != address(0), "StakePoolController: invalid address");
feeCollector = _address;
emit SetFeeCollector(_address);
}
function setFeeToken(address _token) external override onlyGovernance {
require(_token != address(0), "StakePoolController: invalid _token");
feeToken = _token;
emit SetFeeToken(_token);
}
function setFeeAmount(uint256 _feeAmount) external override onlyGovernance {
feeAmount = _feeAmount;
emit SetFeeAmount(_feeAmount);
}
function isWhitelistStakingFor(address _address) external view override returns (bool) {
return _whitelistStakingFor[_address];
}
function isWhitelistStakePool(address _address) external view override returns (int8) {
return _whitelistStakePools[_address];
}
function isStakePoolVerifier(address _address) external view override returns (bool) {
return _stakePoolVerifiers[_address];
}
function setWhitelistStakingFor(address _address, bool state) external override onlyGovernance {
require(_address != address(0), "StakePoolController: invalid address");
_whitelistStakingFor[_address] = state;
emit SetWhitelistStakingFor(_address, state);
}
function setStakePoolVerifier(address _address, bool state) external override onlyGovernance {
require(_address != address(0), "StakePoolController: invalid address");
_stakePoolVerifiers[_address] = state;
emit SetStakePoolVerifier(_address, state);
}
function setWhitelistStakePool(address _address, int8 state) external override {
require(_address != address(0), "StakePoolController: invalid address");
require(_stakePoolVerifiers[msg.sender] == true, "StakePoolController: invalid stake pool verifier");
_whitelistStakePools[_address] = state;
emit SetWhitelistStakePool(_address, state);
}
function addStakePoolCreator(address _address) external override onlyGovernance {
require(_address != address(0), "StakePoolController: invalid address");
uint256 version = IStakePoolCreator(_address).version();
require(version >= 1000, "Invalid stake pool creator version");
stakePoolCreators[version] = _address;
emit SetStakePoolCreator(_address, version);
}
function isWhitelistRewardRebaser(address _address) external view override returns (bool) {
return _address == address(0) ? true : _whitelistRewardRebaser[_address];
}
function setWhitelistRewardRebaser(address _address, bool state) external override onlyGovernance {
require(_address != address(0), "StakePoolController: invalid address");
_whitelistRewardRebaser[_address] = state;
emit SetWhitelistRewardRebaser(_address, state);
}
function isWhitelistRewardMultiplier(address _address) external view override returns (bool) {
return _address == address(0) ? true : _whitelistRewardMultiplier[_address];
}
function setWhitelistRewardMultiplier(address _address, bool state) external override onlyGovernance {
require(_address != address(0), "StakePoolController: invalid address");
_whitelistRewardMultiplier[_address] = state;
emit SetWhitelistRewardMultiplier(_address, state);
}
function setGovernance(address _governance) external override onlyGovernance {
require(_governance != address(0), "StakePoolController: invalid governance");
governance = _governance;
emit ChangeGovernance(_governance);
}
function allStakePoolsLength() external view override returns (uint256) {
return allStakePools.length;
}
function createPair(
uint256 version,
address tokenA,
address tokenB,
uint32 tokenWeightA,
uint32 swapFee,
uint256 delayTimeLock,
PoolRewardInfo calldata poolRewardInfo,
uint8 flag
) public override discountCHI(flag) returns (address) {
address pair = swapFactory.getPair(tokenA, tokenB, tokenWeightA, swapFee);
if (pair == address(0)) {
pair = swapFactory.createPair(tokenA, tokenB, tokenWeightA, swapFee);
}
return create(version, pair, delayTimeLock, poolRewardInfo, 0);
}
function _addRewardPool(IStakePool pool, PoolRewardInfo calldata poolRewardInfo) internal {
pool.addRewardPool(
poolRewardInfo.rewardToken,
poolRewardInfo.rewardRebaser,
poolRewardInfo.rewardMultiplier,
poolRewardInfo.startBlock,
poolRewardInfo.endRewardBlock,
poolRewardInfo.rewardPerBlock,
poolRewardInfo.lockRewardPercent,
poolRewardInfo.startVestingBlock,
poolRewardInfo.endVestingBlock
);
}
function create(
uint256 version,
address pair,
uint256 delayTimeLock,
PoolRewardInfo calldata poolRewardInfo,
uint8 flag
) public override discountCHI(flag) returns (address) {
require(swapFactory.isPair(pair), "StakePoolController: invalid pair");
address stakePoolCreator = stakePoolCreators[version];
require(stakePoolCreator != address(0), "StakePoolController: Invalid stake pool creator version");
IStakePool pool = IStakePool(IStakePoolCreator(stakePoolCreator).create());
if (feeCollector != address(0) && feeToken != address(0) && feeAmount > 0) {
TransferHelper.safeTransferFrom(feeToken, msg.sender, feeCollector, feeAmount);
}
allStakePools.push(address(pool));
_stakePools[address(pool)] = true;
TimeLock timelock = new TimeLock();
StakePoolRewardFund stakePoolRewardFund = new StakePoolRewardFund();
emit MasterCreated(
address(pool),
pair,
IStakePoolCreator(stakePoolCreator).version(),
address(timelock),
address(stakePoolRewardFund),
allStakePools.length
);
timelock.initialize(msg.sender, delayTimeLock);
stakePoolRewardFund.initialize(address(pool), address(timelock));
require(
IERC20(poolRewardInfo.rewardToken).balanceOf(msg.sender) >= poolRewardInfo.rewardFundAmount,
"StakePoolController: Not enough rewardFundAmount"
);
TransferHelper.safeTransferFrom(poolRewardInfo.rewardToken, msg.sender, address(stakePoolRewardFund), poolRewardInfo.rewardFundAmount);
_addRewardPool(pool, poolRewardInfo);
pool.initialize(pair, poolRewardInfo.unstakingFrozenTime, address(stakePoolRewardFund), address(timelock));
return address(pool);
}
}
|
bytes4(keccak256(bytes('approve(address,uint256)')));
|
function factory() external view returns (address);
function controller() external view returns (address);
function formula() external view returns (address);
function WETH() external view returns (address);
function addLiquidity(
address pair,
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 pair,
address token,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
)
external
payable
returns (
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
);
function swapExactTokensForTokens(
address tokenIn,
address tokenOut,
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline,
uint8 flag
) external returns (uint256[] memory amounts);
function swapTokensForExactTokens(
address tokenIn,
address tokenOut,
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline,
uint8 flag
) external returns (uint256[] memory amounts);
function swapExactETHForTokens(
address tokenOut,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline,
uint8 flag
) external payable returns (uint256[] memory amounts);
function swapTokensForExactETH(
address tokenIn,
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline,
uint8 flag
) external returns (uint256[] memory amounts);
function swapExactTokensForETH(
address tokenIn,
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline,
uint8 flag
) external returns (uint256[] memory amounts);
function swapETHForExactTokens(
address tokenOut,
uint256 amountOut,
address[] calldata path,
address to,
uint256 deadline,
uint8 flag
) external payable returns (uint256[] memory amounts);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
address tokenIn,
address tokenOut,
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline,
uint8 flag
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
address tokenOut,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline,
uint8 flag
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
address tokenIn,
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline,
uint8 flag
) external;
function addStakeLiquidity(
address stakePool,
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
uint256 deadline
)
external
returns (
uint256 amountA,
uint256 amountB,
uint256 liquidity
);
function addStakeLiquidityETH(
address stakePool,
address token,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountETHMin,
uint256 deadline
)
external
payable
returns (
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
);
function multihopBatchSwapExactIn(
Swap[][] memory swapSequences,
address tokenIn,
address tokenOut,
uint256 totalAmountIn,
uint256 minTotalAmountOut,
uint256 deadline,
uint8 flag
) external payable returns (uint256 totalAmountOut);
function multihopBatchSwapExactOut(
Swap[][] memory swapSequences,
address tokenIn,
address tokenOut,
uint256 maxTotalAmountIn,
uint256 deadline,
uint8 flag
) external payable returns (uint256 totalAmountIn);
}
}
}
) internal {
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), "TransferHelper: APPROVE_FAILED");
}
| 2,332,932 |
pragma solidity ^0.4.16;
import "./Token.sol";
import "./NettingChannelContract.sol";
library ChannelManagerLibrary {
string constant public contract_version = "0.2._";
struct Data {
Token token;
address registry_address;
address[] all_channels;
mapping(bytes32 => uint) partyhash_to_channelpos;
mapping(address => address[]) nodeaddress_to_channeladdresses;
mapping(address => mapping(address => uint)) node_index;
}
/// @notice Create a new payment channel between two parties
/// @param partner The address of the partner
/// @param settle_timeout The settle timeout in blocks
/// @return The address of the newly created NettingChannelContract.
function newChannel(Data storage self, address partner, uint settle_timeout)
public
returns (address)
{
address[] storage caller_channels = self.nodeaddress_to_channeladdresses[msg.sender];
address[] storage partner_channels = self.nodeaddress_to_channeladdresses[partner];
bytes32 party_hash = partyHash(msg.sender, partner);
uint channel_pos = self.partyhash_to_channelpos[party_hash];
address new_channel_address = new NettingChannelContract(
self.registry_address,
self.token,
msg.sender,
partner,
settle_timeout
);
if (channel_pos != 0) {
// Check if the channel was settled. Once a channel is settled it
// kills itself, so address must not have code.
address settled_channel = self.all_channels[channel_pos - 1];
require(!contractExists(settled_channel));
uint caller_pos = self.node_index[msg.sender][partner];
uint partner_pos = self.node_index[partner][msg.sender];
// replace the channel address in-place
self.all_channels[channel_pos - 1] = new_channel_address;
caller_channels[caller_pos - 1] = new_channel_address;
partner_channels[partner_pos - 1] = new_channel_address;
} else {
self.all_channels.push(new_channel_address);
caller_channels.push(new_channel_address);
partner_channels.push(new_channel_address);
// using the 1-index, 0 is used for the absence of a value
self.partyhash_to_channelpos[party_hash] = self.all_channels.length;
self.node_index[msg.sender][partner] = caller_channels.length;
self.node_index[partner][msg.sender] = partner_channels.length;
}
return new_channel_address;
}
/// @notice Get the address of channel with a partner
/// @param partner The address of the partner
/// @return The address of the channel
function getChannelWith(Data storage self, address partner)
public
constant
returns (address)
{
bytes32 party_hash = partyHash(msg.sender, partner);
uint channel_pos = self.partyhash_to_channelpos[party_hash];
if (channel_pos != 0) {
return self.all_channels[channel_pos - 1];
}
}
/// TODO: Find a way to remove this function duplication from Utils.sol here
/// At the moment libraries can't inherit so we need to add this here
/// explicitly.
/// @notice Check if a contract exists
/// @param channel The address to check whether a contract is deployed or not
/// @return True if a contract exists, false otherwise
function contractExists(address channel)
private
constant
returns (bool)
{
uint size;
assembly {
size := extcodesize(channel)
}
return size > 0;
}
/// @notice Get the hash of the two addresses
/// @param address_one address of one party
/// @param address_two of the other party
/// @return The keccak256 hash of both parties sorted by size of address
function partyHash(address address_one, address address_two)
internal
pure
returns (bytes32)
{
if (address_one < address_two) {
return keccak256(address_one, address_two);
} else {
// The two participants can't be the same here due to this check in
// the netting channel constructor:
// https://github.com/raiden-network/raiden/blob/e17d96db375d31b134ae7b4e2ad2c1f905b47857/raiden/smart_contracts/NettingChannelContract.sol#L27
return keccak256(address_two, address_one);
}
}
}
|
Get the address of channel with a partner partner The address of the partner return The address of the channel
|
function getChannelWith(Data storage self, address partner)
public
constant
returns (address)
{
bytes32 party_hash = partyHash(msg.sender, partner);
uint channel_pos = self.partyhash_to_channelpos[party_hash];
if (channel_pos != 0) {
return self.all_channels[channel_pos - 1];
}
}
| 12,808,378 |
./partial_match/1/0xFB5653E64191aEef7513D1a8ffd53FB65db326B9/sources/StablesPoolCash.sol
|
Withdraw LP tokens from MasterChef.
|
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (pool.poolType == 10) {
rebasePool(_pid);
if (user.amount > 0) {
user.amount = user.amount.mul(rebaseRatio(user.rebaseIndexStart)).div(1e18);
}
user.rebaseIndexStart = rabaseLog.length;
}
require(user.amount >= _amount, "withdraw: not good");
uint256 pending = user.amount.mul(pool.accSushiPerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
safeSushiTransfer(msg.sender, pending);
}
if(_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.amount = pool.amount.sub(_amount);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
}
user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12);
emit Withdraw(msg.sender, _pid, _amount);
}
| 16,030,665 |
/**
* @title: Idle Token Governance main contract
* @summary: ERC20 that holds pooled user funds together
* Each token rapresent a share of the underlying pools
* and with each token user have the right to redeem a portion of these pools
* @author: Idle Labs Inc., idle.finance
*/
pragma solidity 0.5.16;
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20Detailed.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/ownership/Ownable.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/lifecycle/Pausable.sol";
import "@openzeppelin/upgrades/contracts/Initializable.sol";
import "../interfaces/iERC20Fulcrum.sol";
import "../interfaces/ILendingProtocol.sol";
import "../interfaces/IGovToken.sol";
import "../interfaces/IIdleTokenV3_1.sol";
import "../interfaces/IERC3156FlashBorrower.sol";
import "../interfaces/IAaveIncentivesController.sol";
import "../interfaces/Comptroller.sol";
import "../interfaces/CERC20.sol";
import "../interfaces/AToken.sol";
import "../interfaces/IdleController.sol";
import "../interfaces/PriceOracle.sol";
import "../interfaces/IIdleTokenHelper.sol";
import "../GST2ConsumerV2.sol";
contract IdleTokenV3_1NoConst is Initializable, ERC20, ERC20Detailed, ReentrancyGuard, Ownable, Pausable, IIdleTokenV3_1, GST2ConsumerV2 {
using SafeERC20 for IERC20;
using SafeMath for uint256;
uint256 internal ONE_18 = 10**18;
// State variables
// eg. DAI address
address public token;
// eg. iDAI address
address internal iToken;
// eg. cDAI address
address internal cToken;
// Idle rebalancer current implementation address
address public rebalancer;
// Address collecting underlying fees
address public feeAddress;
// Last iToken price, used to pause contract in case of a black swan event
uint256 public lastITokenPrice;
// eg. 18 for DAI
uint256 internal tokenDecimals;
// Max unlent assets percentage for gas friendly swaps
uint256 public maxUnlentPerc; // 100000 == 100% -> 1000 == 1%
// Current fee on interest gained
uint256 public fee;
// eg. [cTokenAddress, iTokenAddress, ...]
address[] public allAvailableTokens;
// eg. [COMPAddress, CRVAddress, ...]
address[] public govTokens;
// last fully applied allocations (ie when all liquidity has been correctly placed)
// eg. [5000, 0, 5000, 0] for 50% in compound, 0% fulcrum, 50% aave, 0 dydx. same order of allAvailableTokens
uint256[] public lastAllocations;
// Map that saves avg idleToken price paid for each user, used to calculate earnings
mapping(address => uint256) public userAvgPrices;
// eg. cTokenAddress => IdleCompoundAddress
mapping(address => address) public protocolWrappers;
// array with last balance recorded for each gov tokens
mapping (address => uint256) public govTokensLastBalances;
// govToken -> user_address -> user_index eg. usersGovTokensIndexes[govTokens[0]][msg.sender] = 1111123;
mapping (address => mapping (address => uint256)) public usersGovTokensIndexes;
// global indices for each gov tokens used as a reference to calculate a fair share for each user
mapping (address => uint256) public govTokensIndexes;
// Map that saves amount with no fee for each user
mapping(address => uint256) internal userNoFeeQty;
// variable used for avoid the call of mint and redeem in the same tx
bytes32 internal _minterBlock;
// Events
event Rebalance(address _rebalancer, uint256 _amount);
event Referral(uint256 _amount, address _ref);
// ########## IdleToken V4_1 updates
// Idle governance token
address public IDLE = address(0x875773784Af8135eA0ef43b5a374AaD105c5D39e);
// Compound governance token
address public COMP = address(0xc00e94Cb662C3520282E6f5717214004A7f26888);
uint256 internal constant FULL_ALLOC = 100000;
// Idle distribution controller
address public idleController = address(0x275DA8e61ea8E02d51EDd8d0DC5c0E62b4CDB0BE);
// oracle used for calculating the avgAPR with gov tokens
address public oracle;
// eg cDAI -> COMP
mapping(address => address) internal protocolTokenToGov;
// Whether openRebalance is enabled or not
bool public isRiskAdjusted;
// last allocations submitted by rebalancer
uint256[] internal lastRebalancerAllocations;
// ########## IdleToken V5 updates
// Fee for flash loan
uint256 public flashLoanFee;
// IdleToken helper address
address public tokenHelper;
/**
* @dev Emitted on flashLoan()
* @param target The address of the flash loan receiver contract
* @param initiator The address initiating the flash loan
* @param amount The amount flash borrowed
* @param premium The flash loan fee
**/
event FlashLoan(
address indexed target,
address indexed initiator,
uint256 amount,
uint256 premium
);
// Addresses for stkAAVE distribution from Aave
address public stkAAVE = address(0x4da27a545c0c5B758a6BA100e3a049001de870f5);
address internal aToken;
// ########## End IdleToken V5 updates
// ####################################################
// ################# INIT METHODS #####################
// ####################################################
function _initV1(
string memory _name, // eg. IdleDAI
string memory _symbol, // eg. IDLEDAI
address _token
) public initializer {
// copied from old initialize() method removed at commit 04e29bd6f9282ef5677edc16570918da1a72dd3a
// Initialize inherited contracts
ERC20Detailed.initialize(_name, _symbol, 18);
Ownable.initialize(msg.sender);
Pausable.initialize(msg.sender);
ReentrancyGuard.initialize();
// Initialize storage variables
maxUnlentPerc = 1000;
flashLoanFee = 90;
token = _token;
tokenDecimals = ERC20Detailed(_token).decimals();
// end of old initialize method
oracle = address(0xB5A8f07dD4c3D315869405d702ee8F6EA695E8C5);
feeAddress = address(0xBecC659Bfc6EDcA552fa1A67451cC6b38a0108E4);
rebalancer = address(0xB3C8e5534F0063545CBbb7Ce86854Bf42dB8872B);
tokenHelper = address(0x5B7400cC634a49650Cb3212D882512424fED00ed);
fee = 10000;
iToken = address(0);
}
/**
* It allows owner to manually initialize new contract implementation which supports IDLE distribution
*
* @param _newGovTokens : array of gov token addresses
* @param _protocolTokens : array of protocol tokens supported
* @param _wrappers : array of wrappers for protocol tokens
* @param _lastRebalancerAllocations : array of allocations
* @param _isRiskAdjusted : flag whether is risk adjusted or not
*/
function manualInitialize(
address[] calldata _newGovTokens,
address[] calldata _protocolTokens,
address[] calldata _wrappers,
uint256[] calldata _lastRebalancerAllocations,
bool _isRiskAdjusted,
address _cToken,
address _aToken
) external onlyOwner {
cToken = _cToken;
aToken = _aToken;
isRiskAdjusted = _isRiskAdjusted;
// set all available tokens and set the protocolWrappers mapping in the for loop
allAvailableTokens = _protocolTokens;
// same as setGovTokens, copied to avoid make the method public and save on bytecode size
govTokens = _newGovTokens;
// set protocol token to gov token mapping
for (uint256 i = 0; i < _protocolTokens.length; i++) {
protocolWrappers[_protocolTokens[i]] = _wrappers[i];
if (i < _newGovTokens.length) {
if (_newGovTokens[i] == IDLE) { continue; }
protocolTokenToGov[_protocolTokens[i]] = _newGovTokens[i];
}
}
lastRebalancerAllocations = _lastRebalancerAllocations;
lastAllocations = _lastRebalancerAllocations;
// Idle multisig
addPauser(address(0xaDa343Cb6820F4f5001749892f6CAA9920129F2A));
// Remove pause ability from msg.sender
// renouncePauser();
}
// ####################################################
// ################# INIT METHODS #####################
// ####################################################
// function _init(address _tokenHelper, address _aToken, address _newOracle) external {
// require(tokenHelper == address(0), 'DONE');
// tokenHelper = _tokenHelper;
// flashLoanFee = 90;
// aToken = _aToken;
// oracle = _newOracle;
// }
// onlyOwner
/**
* It allows owner to modify allAvailableTokens array in case of emergency
* ie if a bug on a interest bearing token is discovered and reset protocolWrappers
* associated with those tokens.
*
* @param protocolTokens : array of protocolTokens addresses (eg [cDAI, iDAI, ...])
* @param wrappers : array of wrapper addresses (eg [IdleCompound, IdleFulcrum, ...])
* @param _newGovTokens : array of governance token addresses
* @param _newGovTokensEqualLen : array of governance token addresses for each
* protocolToken (addr0 should be used for protocols with no govToken)
*/
function setAllAvailableTokensAndWrappers(
address[] calldata protocolTokens,
address[] calldata wrappers,
address[] calldata _newGovTokens,
address[] calldata _newGovTokensEqualLen
) external onlyOwner {
require(protocolTokens.length == wrappers.length, "LEN");
require(_newGovTokensEqualLen.length >= protocolTokens.length, '!>=');
govTokens = _newGovTokens;
address newGov;
address protToken;
for (uint256 i = 0; i < protocolTokens.length; i++) {
protToken = protocolTokens[i];
require(protToken != address(0) && wrappers[i] != address(0), "0");
protocolWrappers[protToken] = wrappers[i];
// set protocol token to gov token mapping
newGov = _newGovTokensEqualLen[i];
if (newGov != IDLE) {
protocolTokenToGov[protToken] = newGov;
}
}
allAvailableTokens = protocolTokens;
}
/**
* It allows owner to set the flash loan fee
*
* @param _flashFee : new flash loan fee. Max is FULL_ALLOC
*/
function setFlashLoanFee(uint256 _flashFee)
external onlyOwner {
require((flashLoanFee = _flashFee) < FULL_ALLOC, "<");
}
/**
* It allows owner to set the cToken address
*
* @param _cToken : new cToken address
*/
function setCToken(address _cToken)
external onlyOwner {
require((cToken = _cToken) != address(0), "0");
}
/**
* It allows owner to set the aToken address
*
* @param _aToken : new aToken address
*/
function setAToken(address _aToken)
external onlyOwner {
require((aToken = _aToken) != address(0), "0");
}
/**
* It allows owner to set the tokenHelper address
*
* @param _tokenHelper : new tokenHelper address
*/
function setTokenHelper(address _tokenHelper)
external onlyOwner {
require((tokenHelper = _tokenHelper) != address(0), "0");
}
/**
* It allows owner to set the IdleRebalancerV3_1 address
*
* @param _rebalancer : new IdleRebalancerV3_1 address
*/
function setRebalancer(address _rebalancer)
external onlyOwner {
require((rebalancer = _rebalancer) != address(0), "0");
}
/**
* It allows owner to set the fee (1000 == 10% of gained interest)
*
* @param _fee : fee amount where 100000 is 100%, max settable is 10%
*/
function setFee(uint256 _fee)
external onlyOwner {
// 100000 == 100% -> 10000 == 10%
require((fee = _fee) <= FULL_ALLOC / 10, "HIGH");
}
/**
* It allows owner to set the fee address
*
* @param _feeAddress : fee address
*/
function setFeeAddress(address _feeAddress)
external onlyOwner {
require((feeAddress = _feeAddress) != address(0), "0");
}
/**
* It allows owner to set the oracle address for getting avgAPR
*
* @param _oracle : new oracle address
*/
function setOracleAddress(address _oracle)
external onlyOwner {
require((oracle = _oracle) != address(0), "0");
}
/**
* It allows owner to set the max unlent asset percentage (1000 == 1% of unlent asset max)
*
* @param _perc : max unlent perc where 100000 is 100%
*/
function setMaxUnlentPerc(uint256 _perc)
external onlyOwner {
require((maxUnlentPerc = _perc) <= 100000, "HIGH");
}
/**
* Used by Rebalancer to set the new allocations
*
* @param _allocations : array with allocations in percentages (100% => 100000)
*/
function setAllocations(uint256[] calldata _allocations) external {
require(msg.sender == rebalancer || msg.sender == owner(), "!AUTH");
_setAllocations(_allocations);
}
/**
* Used by Rebalancer or in openRebalance to set the new allocations
*
* @param _allocations : array with allocations in percentages (100% => 100000)
*/
function _setAllocations(uint256[] memory _allocations) internal {
require(_allocations.length == allAvailableTokens.length, "LEN");
uint256 total;
for (uint256 i = 0; i < _allocations.length; i++) {
total = total.add(_allocations[i]);
}
lastRebalancerAllocations = _allocations;
require(total == FULL_ALLOC, "TOT");
}
// view
/**
* Get latest allocations submitted by rebalancer
*
* @return : array of allocations ordered as allAvailableTokens
*/
function getAllocations() external view returns (uint256[] memory) {
return lastRebalancerAllocations;
}
/**
* Get currently used gov tokens
*
* @return : array of govTokens supported
*/
function getGovTokens() external view returns (address[] memory) {
return govTokens;
}
/**
* Get currently used protocol tokens (cDAI, aDAI, ...)
*
* @return : array of protocol tokens supported
*/
function getAllAvailableTokens() external view returns (address[] memory) {
return allAvailableTokens;
}
/**
* Get gov token associated to a protocol token eg protocolTokenToGov[cDAI] = COMP
*
* @return : address of the gov token
*/
function getProtocolTokenToGov(address _protocolToken) external view returns (address) {
return protocolTokenToGov[_protocolToken];
}
/**
* IdleToken price for a user considering fees, in underlying
* this is useful when you need to redeem exactly X underlying
*
* @return : price in underlying token counting fees for a specific user
*/
function tokenPriceWithFee(address user)
external view
returns (uint256 priceWFee) {
uint256 userAvgPrice = userAvgPrices[user];
priceWFee = _tokenPrice();
if (userAvgPrice != 0 && priceWFee > userAvgPrice) {
priceWFee = priceWFee.mul(FULL_ALLOC).sub(fee.mul(priceWFee.sub(userAvgPrice))).div(FULL_ALLOC);
}
}
/**
* IdleToken price calculation, in underlying
*
* @return : price in underlying token
*/
function tokenPrice()
external view
returns (uint256) {
return _tokenPrice();
}
/**
* Get APR of every ILendingProtocol
*
* @return addresses: array of token addresses
* @return aprs: array of aprs (ordered in respect to the `addresses` array)
*/
function getAPRs()
external view
returns (address[] memory, uint256[] memory) {
return IIdleTokenHelper(tokenHelper).getAPRs(address(this));
}
/**
* Get current avg APR of this IdleToken
*
* @return avgApr: current weighted avg apr
*/
function getAvgAPR()
public view
returns (uint256) {
return IIdleTokenHelper(tokenHelper).getAPR(address(this), cToken, aToken);
}
/**
* ERC20 modified transferFrom that also update the avgPrice paid for the recipient and
* updates user gov idx
*
* @param sender : sender account
* @param recipient : recipient account
* @param amount : value to transfer
* @return : flag whether transfer was successful or not
*/
function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) {
_updateUserGovIdxTransfer(sender, recipient, amount);
_transfer(sender, recipient, amount);
_approve(sender, msg.sender, allowance(sender, msg.sender).sub(amount, "ERC20: transfer amount exceeds allowance"));
_updateUserFeeInfo(recipient, amount, userAvgPrices[sender]);
return true;
}
/**
* ERC20 modified transfer that also update the avgPrice paid for the recipient and
* updates user gov idx
*
* @param recipient : recipient account
* @param amount : value to transfer
* @return : flag whether transfer was successful or not
*/
function transfer(address recipient, uint256 amount) public returns (bool) {
_updateUserGovIdxTransfer(msg.sender, recipient, amount);
_transfer(msg.sender, recipient, amount);
_updateUserFeeInfo(recipient, amount, userAvgPrices[msg.sender]);
return true;
}
/**
* Helper method for transfer and transferFrom, updates recipient gov indexes
*
* @param _from : sender account
* @param _to : recipient account
* @param amount : value to transfer
*/
function _updateUserGovIdxTransfer(address _from, address _to, uint256 amount) internal {
address govToken;
uint256 govTokenIdx;
uint256 sharePerTokenFrom;
uint256 shareTo;
uint256 balanceTo = balanceOf(_to);
for (uint256 i = 0; i < govTokens.length; i++) {
govToken = govTokens[i];
if (balanceTo == 0) {
usersGovTokensIndexes[govToken][_to] = usersGovTokensIndexes[govToken][_from];
} else {
govTokenIdx = govTokensIndexes[govToken];
// calc 1 idleToken value in gov shares for user `_from`
sharePerTokenFrom = govTokenIdx.sub(usersGovTokensIndexes[govToken][_from]);
// calc current gov shares (before transfer) for user `_to`
shareTo = balanceTo.mul(govTokenIdx.sub(usersGovTokensIndexes[govToken][_to])).div(ONE_18);
// user `_to` should have -> shareTo + (sharePerTokenFrom * amount / 1e18) = (balanceTo + amount) * (govTokenIdx - userIdx) / 1e18
// so userIdx = govTokenIdx - ((shareTo * 1e18 + (sharePerTokenFrom * amount)) / (balanceTo + amount))
usersGovTokensIndexes[govToken][_to] = govTokenIdx.sub(
shareTo.mul(ONE_18).add(sharePerTokenFrom.mul(amount)).div(
balanceTo.add(amount)
)
);
}
}
}
/**
* Get how many gov tokens a user is entitled to (this may not include eventual undistributed tokens)
*
* @param _usr : user address
* @return : array of amounts for each gov token
*/
function getGovTokensAmounts(address _usr) external view returns (uint256[] memory _amounts) {
address govToken;
uint256 usrBal = balanceOf(_usr);
_amounts = new uint256[](govTokens.length);
for (uint256 i = 0; i < _amounts.length; i++) {
govToken = govTokens[i];
_amounts[i] = usrBal.mul(govTokensIndexes[govToken].sub(usersGovTokensIndexes[govToken][_usr])).div(ONE_18);
}
}
// external
/**
* Used to mint IdleTokens, given an underlying amount (eg. DAI).
* This method triggers a rebalance of the pools if _skipRebalance is set to false
* NOTE: User should 'approve' _amount of tokens before calling mintIdleToken
* NOTE 2: this method can be paused
*
* @param _amount : amount of underlying token to be lended
* @param : not used anymore
* @param _referral : referral address
* @return mintedTokens : amount of IdleTokens minted
*/
function mintIdleToken(uint256 _amount, bool, address _referral)
external nonReentrant whenNotPaused
returns (uint256 mintedTokens) {
_minterBlock = keccak256(abi.encodePacked(tx.origin, block.number));
_redeemGovTokens(msg.sender);
// Get current IdleToken price
uint256 idlePrice = _tokenPrice();
// transfer tokens to this contract
IERC20(token).safeTransferFrom(msg.sender, address(this), _amount);
mintedTokens = _amount.mul(ONE_18).div(idlePrice);
_mint(msg.sender, mintedTokens);
// Update avg price and user idx for each gov tokens
_updateUserInfo(msg.sender, mintedTokens);
_updateUserFeeInfo(msg.sender, mintedTokens, idlePrice);
if (_referral != address(0)) {
emit Referral(_amount, _referral);
}
}
/**
* Helper method for mintIdleToken, updates minter gov indexes and avg price
*
* @param _to : minter account
* @param _mintedTokens : number of newly minted tokens
*/
function _updateUserInfo(address _to, uint256 _mintedTokens) internal {
address govToken;
uint256 usrBal = balanceOf(_to);
uint256 _usrIdx;
for (uint256 i = 0; i < govTokens.length; i++) {
govToken = govTokens[i];
_usrIdx = usersGovTokensIndexes[govToken][_to];
// calculate user idx
usersGovTokensIndexes[govToken][_to] = _usrIdx.add(
_mintedTokens.mul(govTokensIndexes[govToken].sub(_usrIdx)).div(usrBal)
);
}
}
/**
* Here we calc the pool share one can withdraw given the amount of IdleToken they want to burn
*
* @param _amount : amount of IdleTokens to be burned
* @return redeemedTokens : amount of underlying tokens redeemed
*/
function redeemIdleToken(uint256 _amount)
external
returns (uint256) {
return _redeemIdleToken(_amount, new bool[](govTokens.length));
}
/**
* Here we calc the pool share one can withdraw given the amount of IdleToken they want to burn
* WARNING: if elements in the `_skipGovTokenRedeem` are set to `true` then the rewards will be GIFTED to the pool
*
* @param _amount : amount of IdleTokens to be burned
* @param _skipGovTokenRedeem : array of flags whether to redeem or not specific gov tokens
* @return redeemedTokens : amount of underlying tokens redeemed
*/
function redeemIdleTokenSkipGov(uint256 _amount, bool[] calldata _skipGovTokenRedeem)
external
returns (uint256) {
return _redeemIdleToken(_amount, _skipGovTokenRedeem);
}
/**
* Here we calc the pool share one can withdraw given the amount of IdleToken they want to burn
*
* @param _amount : amount of IdleTokens to be burned
* @param _skipGovTokenRedeem : array of flag for redeeming or not gov tokens. Funds will be gifted to the pool
* @return redeemedTokens : amount of underlying tokens redeemed
*/
function _redeemIdleToken(uint256 _amount, bool[] memory _skipGovTokenRedeem)
internal nonReentrant
returns (uint256 redeemedTokens) {
_checkMintRedeemSameTx();
_redeemGovTokensInternal(msg.sender, _skipGovTokenRedeem);
if (_amount != 0) {
uint256 price = _tokenPrice();
uint256 valueToRedeem = _amount.mul(price).div(ONE_18);
uint256 balanceUnderlying = _contractBalanceOf(token);
if (valueToRedeem > balanceUnderlying) {
redeemedTokens = _redeemHelper(_amount, balanceUnderlying);
} else {
redeemedTokens = valueToRedeem;
}
// get eventual performance fee
redeemedTokens = _getFee(_amount, redeemedTokens, price);
// burn idleTokens
_burn(msg.sender, _amount);
// send underlying minus fee to msg.sender
_transferTokens(token, msg.sender, redeemedTokens);
}
}
function _redeemHelper(uint256 _amount, uint256 _balanceUnderlying) internal returns (uint256 redeemedTokens) {
address currToken;
uint256 idleSupply = totalSupply();
address[] memory _allAvailableTokens = allAvailableTokens;
for (uint256 i = 0; i < _allAvailableTokens.length; i++) {
currToken = _allAvailableTokens[i];
redeemedTokens = redeemedTokens.add(
_redeemProtocolTokens(
currToken,
// _amount * protocolPoolBalance / idleSupply
_amount.mul(_contractBalanceOf(currToken)).div(idleSupply) // amount to redeem
)
);
}
// and get a portion of the eventual unlent balance
redeemedTokens = redeemedTokens.add(_amount.mul(_balanceUnderlying).div(idleSupply));
}
/**
* Here we calc the pool share one can withdraw given the amount of IdleToken they want to burn
* and send interest-bearing tokens (eg. cDAI/iDAI) directly to the user.
* Underlying (eg. DAI) is not redeemed here.
*
* @param _amount : amount of IdleTokens to be burned
*/
function redeemInterestBearingTokens(uint256 _amount)
external nonReentrant whenPaused {
_checkMintRedeemSameTx();
_redeemGovTokens(msg.sender);
for (uint256 i = 0; i < allAvailableTokens.length; i++) {
_transferTokens(allAvailableTokens[i], msg.sender, _amount.mul(_contractBalanceOf(allAvailableTokens[i])).div(totalSupply()));
}
// Get a portion of the eventual unlent balance
_transferTokens(token, msg.sender, _amount.mul(_contractBalanceOf(token)).div(totalSupply()));
_burn(msg.sender, _amount);
}
/**
* Dynamic allocate all the pool across different lending protocols if needed,
* rebalance without params
*
* NOTE: this method can be paused
*
* @return : whether has rebalanced or not
*/
function rebalance() external returns (bool) {
return _rebalance();
}
/**
* @dev The fee to be charged for a given loan.
* @param _token The loan currency.
* @param _amount The amount of tokens lent.
* @return The amount of `token` to be charged for the loan, on top of the returned principal.
*/
function flashFee(address _token, uint256 _amount) public view returns (uint256) {
require(_token == token, '!EQ');
return _amount.mul(flashLoanFee).div(FULL_ALLOC);
}
/**
* @dev The amount of currency available to be lent.
* @param _token The loan currency.
* @return The amount of `token` that can be borrowed.
*/
function maxFlashLoan(address _token) external view returns (uint256) {
if (_token == token) {
return _tokenPrice().mul(totalSupply()).div(ONE_18);
}
}
/**
* Allow any users to borrow funds inside a tx if they return the same amount + `flashLoanFee`
*
* @param _receiver : flash loan receiver, should have the IERC3156FlashBorrower interface
* @param _token : used to check that the requested token is the correct one
* @param _amount : amount of `token` to borrow
* @param _params : params that should be passed to the _receiverAddress in the `executeOperation` call
*/
function flashLoan(
IERC3156FlashBorrower _receiver,
address _token,
uint256 _amount,
bytes calldata _params
) external whenNotPaused nonReentrant returns (bool) {
address receiverAddr = address(_receiver);
require(_token == token, "!EQ");
require(receiverAddr != address(0) && _amount > 0, "0");
// get current underlying unlent balance
uint256 balance = _contractBalanceOf(token);
if (_amount > balance) {
// Unlent is not enough, some funds needs to be redeemed from underlying protocols
uint256 toRedeem = _amount.sub(balance);
uint256 _toRedeemAux;
address currToken;
uint256 currBalanceUnderlying;
uint256 availableLiquidity;
uint256 redeemed;
uint256 protocolTokenPrice;
ILendingProtocol protocol;
bool isEnough;
bool haveWeInvestedEnough;
// We cycle through interest bearing tokens currently in use (eg [cDAI, aDAI])
// (ie we cycle each lending protocol where we have some funds currently deposited)
for (uint256 i = 0; i < allAvailableTokens.length; i++) {
currToken = allAvailableTokens[i];
protocol = ILendingProtocol(protocolWrappers[currToken]);
protocolTokenPrice = protocol.getPriceInToken();
availableLiquidity = protocol.availableLiquidity();
currBalanceUnderlying = _contractBalanceOf(currToken).mul(protocolTokenPrice).div(ONE_18);
// We need to check:
// 1. if Idle has invested enough in that protocol to cover the user request
haveWeInvestedEnough = currBalanceUnderlying >= toRedeem;
// 2. if the current lending protocol has enough liquidity available (not borrowed) to cover the user requested amount
isEnough = availableLiquidity >= toRedeem;
// in order to calculate `_toRedeemAux` which is the amount of underlying (eg DAI)
// that we have to redeem from that lending protocol
_toRedeemAux = haveWeInvestedEnough ?
// if we lent enough and that protocol has enough liquidity we redeem `toRedeem` and we are done, otherwise we redeem `availableLiquidity`
(isEnough ? toRedeem : availableLiquidity) :
// if we did not lent enough and that liquidity is available then we redeem all what we deposited, otherwise we redeem `availableLiquidity`
(currBalanceUnderlying <= availableLiquidity ? currBalanceUnderlying : availableLiquidity);
// do the actual redeem on the lending protocol
redeemed = _redeemProtocolTokens(
currToken,
// convert amount from underlying to protocol token
_toRedeemAux.mul(ONE_18).div(protocolTokenPrice)
);
// tokens are now in this contract
if (haveWeInvestedEnough && isEnough) {
break;
}
toRedeem = toRedeem.sub(redeemed);
}
}
require(_contractBalanceOf(token) >= _amount, "LOW");
// transfer funds
_transferTokens(token, receiverAddr, _amount);
// calculate fee
uint256 _flashFee = flashFee(token, _amount);
// call _receiver `onFlashLoan`
require(
_receiver.onFlashLoan(msg.sender, token, _amount, _flashFee, _params) == keccak256("ERC3156FlashBorrower.onFlashLoan"),
"EXEC"
);
// transfer _amount + _flashFee from _receiver
IERC20(token).safeTransferFrom(receiverAddr, address(this), _amount.add(_flashFee));
// Put underlyings in lending once again with rebalance
_rebalance();
emit FlashLoan(receiverAddr, msg.sender, _amount, _flashFee);
return true;
}
// internal
/**
* Get current idleToken price based on net asset value and totalSupply
*
* @return price: value of 1 idleToken in underlying
*/
function _tokenPrice() internal view returns (uint256 price) {
uint256 totSupply = totalSupply();
if (totSupply == 0) {
return 10**(tokenDecimals);
}
address currToken;
uint256 totNav = _contractBalanceOf(token).mul(ONE_18); // eventual underlying unlent balance
address[] memory _allAvailableTokens = allAvailableTokens;
for (uint256 i = 0; i < _allAvailableTokens.length; i++) {
currToken = _allAvailableTokens[i];
totNav = totNav.add(
// NAV = price * poolSupply
_getPriceInToken(protocolWrappers[currToken]).mul(
_contractBalanceOf(currToken)
)
);
}
price = totNav.div(totSupply); // idleToken price in token wei
}
/**
* Dynamic allocate all the pool across different lending protocols if needed
*
* NOTE: this method can be paused
*
* @return : whether has rebalanced or not
*/
function _rebalance()
internal whenNotPaused
returns (bool) {
// check if we need to rebalance by looking at the last allocations submitted by rebalancer
uint256[] memory rebalancerLastAllocations = lastRebalancerAllocations;
uint256[] memory _lastAllocations = lastAllocations;
uint256 lastLen = _lastAllocations.length;
bool areAllocationsEqual = rebalancerLastAllocations.length == lastLen;
if (areAllocationsEqual) {
for (uint256 i = 0; i < lastLen || !areAllocationsEqual; i++) {
if (_lastAllocations[i] != rebalancerLastAllocations[i]) {
areAllocationsEqual = false;
break;
}
}
}
uint256 balance = _contractBalanceOf(token);
if (areAllocationsEqual && balance == 0) {
return false;
}
uint256 maxUnlentBalance = _getCurrentPoolValue().mul(maxUnlentPerc).div(FULL_ALLOC);
if (balance > maxUnlentBalance) {
// mint the difference
_mintWithAmounts(rebalancerLastAllocations, balance.sub(maxUnlentBalance));
}
if (areAllocationsEqual) {
return false;
}
// Instead of redeeming everything during rebalance we redeem and mint only what needs
// to be reallocated
// get current allocations in underlying (it does not count unlent underlying)
(uint256[] memory amounts, uint256 totalInUnderlying) = _getCurrentAllocations();
if (balance == 0 && maxUnlentPerc > 0) {
totalInUnderlying = totalInUnderlying.sub(maxUnlentBalance);
}
(uint256[] memory toMintAllocations, uint256 totalToMint, bool lowLiquidity) = _redeemAllNeeded(
amounts,
// calculate new allocations given the total (not counting unlent balance)
_amountsFromAllocations(rebalancerLastAllocations, totalInUnderlying)
);
// if some protocol has liquidity that we should redeem, we do not update
// lastAllocations to force another rebalance next time
if (!lowLiquidity) {
// Update lastAllocations with rebalancerLastAllocations
delete lastAllocations;
lastAllocations = rebalancerLastAllocations;
}
uint256 totalRedeemd = _contractBalanceOf(token);
if (totalRedeemd <= maxUnlentBalance) {
return false;
}
// Do not mint directly using toMintAllocations check with totalRedeemd
uint256[] memory tempAllocations = new uint256[](toMintAllocations.length);
for (uint256 i = 0; i < toMintAllocations.length; i++) {
// Calc what would have been the correct allocations percentage if all was available
tempAllocations[i] = toMintAllocations[i].mul(FULL_ALLOC).div(totalToMint);
}
// partial amounts
_mintWithAmounts(tempAllocations, totalRedeemd.sub(maxUnlentBalance));
emit Rebalance(msg.sender, totalInUnderlying.add(maxUnlentBalance));
return true; // hasRebalanced
}
/**
* Redeem unclaimed governance tokens and update governance global index and user index if needed
* if called during redeem it will send all gov tokens accrued by a user to the user
*
* @param _to : user address
*/
function _redeemGovTokens(address _to) internal {
_redeemGovTokensInternal(_to, new bool[](govTokens.length));
}
/**
* Redeem unclaimed governance tokens and update governance global index and user index if needed
* if called during redeem it will send all gov tokens accrued by a user to the user
*
* @param _to : user address
* @param _skipGovTokenRedeem : array of flag for redeeming or not gov tokens
*/
function _redeemGovTokensInternal(address _to, bool[] memory _skipGovTokenRedeem) internal {
address[] memory _govTokens = govTokens;
if (_govTokens.length == 0) {
return;
}
uint256 supply = totalSupply();
uint256 usrBal = balanceOf(_to);
address govToken;
if (supply > 0) {
for (uint256 i = 0; i < _govTokens.length; i++) {
govToken = _govTokens[i];
_redeemGovTokensFromProtocol(govToken);
// get current gov token balance
uint256 govBal = _contractBalanceOf(govToken);
if (govBal > 0) {
// update global index with ratio of govTokens per idleToken
govTokensIndexes[govToken] = govTokensIndexes[govToken].add(
// check how much gov tokens for each idleToken we gained since last update
govBal.sub(govTokensLastBalances[govToken]).mul(ONE_18).div(supply)
);
// update global var with current govToken balance
govTokensLastBalances[govToken] = govBal;
}
if (usrBal > 0) {
uint256 usrIndex = usersGovTokensIndexes[govToken][_to];
// check if user has accrued something
uint256 delta = govTokensIndexes[govToken].sub(usrIndex);
if (delta != 0) {
uint256 share = usrBal.mul(delta).div(ONE_18);
uint256 bal = _contractBalanceOf(govToken);
// To avoid rounding issue
if (share > bal) {
share = bal;
}
if (_skipGovTokenRedeem[i]) { // -> gift govTokens[i] accrued to the pool
// update global index with ratio of govTokens per idleToken
govTokensIndexes[govToken] = govTokensIndexes[govToken].add(
// check how much gov tokens for each idleToken we gained since last update
share.mul(ONE_18).div(supply.sub(usrBal))
);
} else {
uint256 feeDue;
// no fee for IDLE governance token
if (feeAddress != address(0) && fee > 0 && govToken != IDLE) {
feeDue = share.mul(fee).div(FULL_ALLOC);
// Transfer gov token fee to feeAddress
_transferTokens(govToken, feeAddress, feeDue);
}
// Transfer gov token to user
_transferTokens(govToken, _to, share.sub(feeDue));
// Update last balance
govTokensLastBalances[govToken] = _contractBalanceOf(govToken);
}
}
}
// save current index for this gov token
usersGovTokensIndexes[govToken][_to] = govTokensIndexes[govToken];
}
}
}
/**
* Redeem a specific gov token
*
* @param _govToken : address of the gov token to redeem
*/
function _redeemGovTokensFromProtocol(address _govToken) internal {
// In case new Gov tokens will be supported this should be updated
if (_govToken == COMP || _govToken == IDLE || _govToken == stkAAVE) {
address[] memory holders = new address[](1);
holders[0] = address(this);
if (_govToken == IDLE) {
// For IDLE, the distribution is done only to IdleTokens, so `holders` and
// `tokens` parameters are the same and equal to address(this)
IdleController(idleController).claimIdle(holders, holders);
return;
}
address[] memory tokens = new address[](1);
if (_govToken == stkAAVE && aToken != address(0)) {
tokens[0] = aToken;
IAaveIncentivesController _ctrl = IAaveIncentivesController(AToken(tokens[0]).getIncentivesController());
_ctrl.claimRewards(tokens, _ctrl.getUserUnclaimedRewards(address(this)), address(this));
return;
}
if (cToken != address(0)) {
tokens[0] = cToken;
Comptroller(CERC20(tokens[0]).comptroller()).claimComp(holders, tokens, false, true);
}
}
}
/**
* Update receiver userAvgPrice paid for each idle token,
* receiver will pay fees accrued
*
* @param usr : user that should have balance update
* @param qty : new amount deposited / transferred, in idleToken
* @param price : sender userAvgPrice
*/
function _updateUserFeeInfo(address usr, uint256 qty, uint256 price) internal {
uint256 usrBal = balanceOf(usr);
// ((avgPrice * oldBalance) + (senderAvgPrice * newQty)) / totBalance
userAvgPrices[usr] = userAvgPrices[usr].mul(usrBal.sub(qty)).add(price.mul(qty)).div(usrBal);
}
/**
* Calculate fee in underlyings and send them to feeAddress
*
* @param amount : in idleTokens
* @param redeemed : in underlying
* @param currPrice : current idleToken price
* @return : net value in underlying
*/
function _getFee(uint256 amount, uint256 redeemed, uint256 currPrice) internal returns (uint256) {
uint256 avgPrice = userAvgPrices[msg.sender];
if (currPrice < avgPrice) {
return redeemed;
}
// 10**23 -> ONE_18 * FULL_ALLOC
uint256 feeDue = amount.mul(currPrice.sub(avgPrice)).mul(fee).div(10**23);
_transferTokens(token, feeAddress, feeDue);
return redeemed.sub(feeDue);
}
/**
* Mint specific amounts of protocols tokens
*
* @param allocations : array of amounts to be minted
* @param total : total amount
* @return : net value in underlying
*/
function _mintWithAmounts(uint256[] memory allocations, uint256 total) internal {
// mint for each protocol and update currentTokensUsed
uint256[] memory protocolAmounts = _amountsFromAllocations(allocations, total);
uint256 currAmount;
address protWrapper;
address[] memory _tokens = allAvailableTokens;
for (uint256 i = 0; i < protocolAmounts.length; i++) {
currAmount = protocolAmounts[i];
if (currAmount != 0) {
protWrapper = protocolWrappers[_tokens[i]];
// Transfer _amount underlying token (eg. DAI) to protWrapper
_transferTokens(token, protWrapper, currAmount);
ILendingProtocol(protWrapper).mint();
}
}
}
/**
* Calculate amounts from percentage allocations (100000 => 100%)
*
* @param allocations : array of protocol allocations in percentage
* @param total : total amount
* @return : array with amounts
*/
function _amountsFromAllocations(uint256[] memory allocations, uint256 total)
internal pure returns (uint256[] memory newAmounts) {
newAmounts = new uint256[](allocations.length);
uint256 currBalance;
uint256 allocatedBalance;
for (uint256 i = 0; i < allocations.length; i++) {
if (i == allocations.length - 1) {
newAmounts[i] = total.sub(allocatedBalance);
} else {
currBalance = total.mul(allocations[i]).div(FULL_ALLOC);
allocatedBalance = allocatedBalance.add(currBalance);
newAmounts[i] = currBalance;
}
}
return newAmounts;
}
/**
* Redeem all underlying needed from each protocol
*
* @param amounts : array with current allocations in underlying
* @param newAmounts : array with new allocations in underlying
* @return toMintAllocations : array with amounts to be minted
* @return totalToMint : total amount that needs to be minted
*/
function _redeemAllNeeded(
uint256[] memory amounts,
uint256[] memory newAmounts
) internal returns (
uint256[] memory toMintAllocations,
uint256 totalToMint,
bool lowLiquidity
) {
toMintAllocations = new uint256[](amounts.length);
ILendingProtocol protocol;
uint256 currAmount;
uint256 newAmount;
address currToken;
address[] memory _tokens = allAvailableTokens;
// check the difference between amounts and newAmounts
for (uint256 i = 0; i < amounts.length; i++) {
currToken = _tokens[i];
newAmount = newAmounts[i];
currAmount = amounts[i];
protocol = ILendingProtocol(protocolWrappers[currToken]);
if (currAmount > newAmount) {
uint256 toRedeem = currAmount.sub(newAmount);
uint256 availableLiquidity = protocol.availableLiquidity();
if (availableLiquidity < toRedeem) {
lowLiquidity = true;
toRedeem = availableLiquidity;
}
// redeem the difference
_redeemProtocolTokens(
currToken,
// convert amount from underlying to protocol token
toRedeem.mul(ONE_18).div(protocol.getPriceInToken())
);
// tokens are now in this contract
} else {
toMintAllocations[i] = newAmount.sub(currAmount);
totalToMint = totalToMint.add(toMintAllocations[i]);
}
}
}
/**
* Get the contract balance of every protocol currently used
*
* @return amounts : array with all amounts for each protocol in order,
* eg [amountCompoundInUnderlying, amountFulcrumInUnderlying]
* @return total : total AUM in underlying
*/
function _getCurrentAllocations() internal view
returns (uint256[] memory amounts, uint256 total) {
// Get balance of every protocol implemented
address currentToken;
address[] memory _tokens = allAvailableTokens;
uint256 tokensLen = _tokens.length;
amounts = new uint256[](tokensLen);
for (uint256 i = 0; i < tokensLen; i++) {
currentToken = _tokens[i];
amounts[i] = _getPriceInToken(protocolWrappers[currentToken]).mul(
_contractBalanceOf(currentToken)
).div(ONE_18);
total = total.add(amounts[i]);
}
}
/**
* Get the current pool value in underlying
*
* @return total : total AUM in underlying
*/
function _getCurrentPoolValue() internal view
returns (uint256 total) {
// Get balance of every protocol implemented
address currentToken;
address[] memory _tokens = allAvailableTokens;
for (uint256 i = 0; i < _tokens.length; i++) {
currentToken = _tokens[i];
total = total.add(_getPriceInToken(protocolWrappers[currentToken]).mul(
_contractBalanceOf(currentToken)
).div(ONE_18));
}
// add unlent balance
total = total.add(_contractBalanceOf(token));
}
/**
* Get contract balance of _token
*
* @param _token : address of the token to read balance
* @return total : balance of _token in this contract
*/
function _contractBalanceOf(address _token) internal view returns (uint256) {
// Original implementation:
//
// return IERC20(_token).balanceOf(address(this));
// Optimized implementation inspired by uniswap https://github.com/Uniswap/uniswap-v3-core/blob/main/contracts/UniswapV3Pool.sol#L144
//
// 0x70a08231 -> selector for 'function balanceOf(address) returns (uint256)'
(bool success, bytes memory data) =
_token.staticcall(abi.encodeWithSelector(0x70a08231, address(this)));
require(success);
return abi.decode(data, (uint256));
}
/**
* Get price of 1 protocol token in underlyings
*
* @param _token : address of the protocol token
* @return price : price of protocol token
*/
function _getPriceInToken(address _token) internal view returns (uint256) {
return ILendingProtocol(_token).getPriceInToken();
}
/**
* Check that no mint has been made in the same block from the same EOA
*/
function _checkMintRedeemSameTx() internal view {
require(keccak256(abi.encodePacked(tx.origin, block.number)) != _minterBlock, "REE");
}
// ILendingProtocols calls
/**
* Redeem underlying tokens through protocol wrapper
*
* @param _amount : amount of `_token` to redeem
* @param _token : protocol token address
* @return tokens : new tokens minted
*/
function _redeemProtocolTokens(address _token, uint256 _amount)
internal
returns (uint256 tokens) {
if (_amount != 0) {
// Transfer _amount of _protocolToken (eg. cDAI) to _wrapperAddr
address _wrapperAddr = protocolWrappers[_token];
_transferTokens(_token, _wrapperAddr, _amount);
tokens = ILendingProtocol(_wrapperAddr).redeem(address(this));
}
}
function _transferTokens(address _token, address _to, uint256 _amount) internal {
IERC20(_token).safeTransfer(_to, _amount);
}
}
|
It allows owner to set the max unlent asset percentage (1000 == 1% of unlent asset max) _perc : max unlent perc where 100000 is 100%/
|
function setMaxUnlentPerc(uint256 _perc)
external onlyOwner {
require((maxUnlentPerc = _perc) <= 100000, "HIGH");
}
| 1,829,057 |
./full_match/1/0x864a1CBB53b9Dea3691a6974B456088C2771DcAd/sources/browser/Bar.sol
|
Get the pending BOOGIEs for a user from 1 pool Make sure that boogieReward won't push the total supply of BOOGIE past boogie.MAX_SUPPLY()
|
function _pendingBoogie(uint256 _pid, address _user) internal view returns (uint256) {
if (_pid == 0 && boogiePoolActive != true) return 0;
PoolInfo memory pool = poolInfo[_pid];
UserInfo memory user = userInfo[_pid][_user];
uint256 accBoogiePerShare = pool.accBoogiePerShare;
uint256 lpSupply = _getPoolSupply(_pid);
if (block.number > pool.lastBoogieRewardBlock && lpSupply != 0) {
uint256 boogieReward = _calculateBoogieReward(_pid, lpSupply);
uint256 boogieTotalSupply = boogie.totalSupply();
if (boogieTotalSupply.add(boogieReward) >= boogie.MAX_SUPPLY()) {
boogieReward = boogie.MAX_SUPPLY().sub(boogieTotalSupply);
}
accBoogiePerShare = accBoogiePerShare.add(boogieReward.mul(1e12).div(lpSupply));
}
return user.staked.mul(accBoogiePerShare).div(1e12).sub(user.rewardDebt);
}
| 4,927,144 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./ERC721.sol";
contract Dominapes is ERC721 {
event Mint(address indexed from, uint256 indexed tokenId);
modifier callerIsUser() {
require(tx.origin == msg.sender, "The caller is another contract");
_;
}
modifier saleStarted() {
require(
startMintDate != 0 && startMintDate <= block.timestamp,
"You are too early"
);
_;
}
uint256 public startMintDate = 1628636400;
uint256 private salePrice = 15000000000000000;
uint256 private totalTokens = 8000;
uint256 private totalMintedTokens = 0;
uint256 private maxSlicesPerWallet = 200;
uint256 private maxSlicesPerTransaction = 10;
string private baseURI =
"https://dominapes.s3.us-west-1.amazonaws.com/";
bool public premintingComplete = false;
uint256 public giveawayCount = 50;
mapping(address => uint256) private claimedSlicesPerWallet;
uint16[] availableSlices;
constructor() ERC721("Dominapes", "DPE") {
addAvailableSlices();
premintSlices();
}
// ONLY OWNER
/**
* @dev Allows to withdraw the Ether in the contract
*/
function withdraw() external onlyOwner {
uint256 totalBalance = address(this).balance;
payable(msg.sender).transfer(totalBalance);
}
/**
* @dev Sets the base URI for the API that provides the NFT data.
*/
function setBaseTokenURI(string memory _uri) external onlyOwner {
baseURI = _uri;
}
/**
* @dev Sets the claim price for each slice
*/
function setsalePrice(uint256 _salePrice) external onlyOwner {
salePrice = _salePrice;
}
/**
* @dev Populates the available slices
*/
function addAvailableSlices()
internal
onlyOwner
{
for (uint16 i = 0; i <= 7999; i++) {
availableSlices.push(i);
}
}
/**
* @dev Removes a chosen slice from the available list
*/
function removeSlicesFromAvailableSlices(uint16 tokenId)
external
onlyOwner
{
for (uint16 i; i <= availableSlices.length; i++) {
if (availableSlices[i] != tokenId) {
continue;
}
availableSlices[i] = availableSlices[availableSlices.length - 1];
availableSlices.pop();
break;
}
}
/**
* @dev Allow devs to hand pick some slices before the available slices list is created
*/
function allocateTokens(uint256[] memory tokenIds)
external
onlyOwner
{
require(availableSlices.length == 0, "Available slices are already set");
_batchMint(msg.sender, tokenIds);
totalMintedTokens += tokenIds.length;
}
/**
* @dev Sets the date that users can start claiming slices
*/
function setStartSaleDate(uint256 _startSaleDate)
external
onlyOwner
{
startMintDate = _startSaleDate;
}
/**
* @dev Sets the date that users can start minting slices
*/
function setStartMintDate(uint256 _startMintDate)
external
onlyOwner
{
startMintDate = _startMintDate;
}
/**
* @dev Checks if an slice is in the available list
*/
function isSliceAvailable(uint16 tokenId)
external
view
onlyOwner
returns (bool)
{
for (uint16 i; i < availableSlices.length; i++) {
if (availableSlices[i] == tokenId) {
return true;
}
}
return false;
}
/**
* @dev Give random slices to the provided addresses
*/
function ownerMintSlices(address[] memory addresses)
external
onlyOwner
{
require(
availableSlices.length >= addresses.length,
"No slices left to be claimed"
);
totalMintedTokens += addresses.length;
for (uint256 i; i < addresses.length; i++) {
_mint(addresses[i], getSliceToBeClaimed());
}
}
/**
* @dev Give random slices to the provided address
*/
function premintSlices()
internal
onlyOwner
{
require(availableSlices.length >= giveawayCount, "No slices left to be claimed");
require(
!premintingComplete,
"You can only premint the horses once"
);
totalMintedTokens += giveawayCount;
uint256[] memory tokenIds = new uint256[](giveawayCount);
for (uint256 i; i < giveawayCount; i++) {
tokenIds[i] = getSliceToBeClaimed();
}
_batchMint(msg.sender, tokenIds);
premintingComplete = true;
}
// END ONLY OWNER
/**
* @dev Claim a single slice
*/
function mintSlice() external payable callerIsUser saleStarted {
require(msg.value >= salePrice, "Not enough Ether to claim an slice");
require(
claimedSlicesPerWallet[msg.sender] < maxSlicesPerWallet,
"You cannot claim more slices"
);
require(availableSlices.length > 0, "No slices left to be claimed");
claimedSlicesPerWallet[msg.sender]++;
totalMintedTokens++;
_mint(msg.sender, getSliceToBeClaimed());
}
/**
* @dev Claim up to 10 slices at once
*/
function mintSlices(uint256 amount)
external
payable
callerIsUser
saleStarted
{
require(
msg.value >= salePrice * amount,
"Not enough Ether to claim the slices"
);
require(
claimedSlicesPerWallet[msg.sender] + amount <= maxSlicesPerWallet,
"You cannot claim more slices"
);
require(amount <= maxSlicesPerTransaction, "You can only claim 10 slices in 1 transaction");
require(availableSlices.length >= amount, "No slices left to be claimed");
uint256[] memory tokenIds = new uint256[](amount);
claimedSlicesPerWallet[msg.sender] += amount;
totalMintedTokens += amount;
for (uint256 i; i < amount; i++) {
tokenIds[i] = getSliceToBeClaimed();
}
_batchMint(msg.sender, tokenIds);
}
/**
* @dev Returns the tokenId by index
*/
function tokenByIndex(uint256 tokenId) external view returns (uint256) {
require(
_exists(tokenId),
"ERC721: operator query for nonexistent token"
);
return tokenId;
}
/**
* @dev Returns the base URI for the tokens API.
*/
function baseTokenURI() external view returns (string memory) {
return baseURI;
}
/**
* @dev Returns how many slices are still available to be claimed
*/
function getAvailableSlices() external view returns (uint256) {
return availableSlices.length;
}
/**
* @dev Returns the claim price
*/
function getSalePrice() external view returns (uint256) {
return salePrice;
}
/**
* @dev Returns the total supply
*/
function totalSupply() external view virtual returns (uint256) {
return totalMintedTokens;
}
// Private and Internal functions
/**
* @dev Returns a random available slice to be claimed
*/
function getSliceToBeClaimed() private returns (uint256) {
uint256 random = _getRandomNumber(availableSlices.length);
uint256 tokenId = uint256(availableSlices[random]);
availableSlices[random] = availableSlices[availableSlices.length - 1];
availableSlices.pop();
return tokenId;
}
/**
* @dev Generates a pseudo-random number.
*/
function _getRandomNumber(uint256 _upper) private view returns (uint256) {
uint256 random = uint256(
keccak256(
abi.encodePacked(
availableSlices.length,
blockhash(block.number - 1),
block.coinbase,
block.difficulty,
msg.sender
)
)
);
return random % _upper;
}
/**
* @dev See {ERC721}.
*/
function _baseURI() internal view virtual override returns (string memory) {
return baseURI;
}
function mulScale(
uint256 x,
uint256 y,
uint128 scale
) internal pure returns (uint256) {
uint256 a = x / scale;
uint256 b = x % scale;
uint256 c = y / scale;
uint256 d = y % scale;
return a * c * scale + a * d + b * c + (b * d) / scale;
}
}
|
Give random slices to the provided address/
|
function premintSlices()
internal
onlyOwner
{
require(availableSlices.length >= giveawayCount, "No slices left to be claimed");
require(
!premintingComplete,
"You can only premint the horses once"
);
totalMintedTokens += giveawayCount;
uint256[] memory tokenIds = new uint256[](giveawayCount);
for (uint256 i; i < giveawayCount; i++) {
tokenIds[i] = getSliceToBeClaimed();
}
_batchMint(msg.sender, tokenIds);
premintingComplete = true;
}
| 13,740,926 |
pragma ton-solidity >=0.30.0;
contract PrimaryInputVerificationExample {
bytes constant vkey = hex"4399cf35940d0604a273e29525f7605687d98bfe662218c6562bb1c3bdc3bd4bf0aca8554005d192a4f65f18d437920fd8323c53c1ba15342ad547424c6087b6120c2d915625502192981ca3e127a81c3955efcfae20ad8d1637f347e1baa90205e84ae286d60e327520ea408282b88eadbf209ea56904f29333d0b2f9e0a61b7f563ef9eac4b7bfade7317c35237506c136283e0a1fdac1e63c8b536852073d31243ac7e1625c7c965a9fbeeaded7284f4557a6a1d55c479c8645837b9a2e08afcde1d3964a419040c02542a496daecf8182dd908aee7ceead0319536c7b0d2afd1f5a241575b2346fe966afa080602c68b35d3d4dbdea93eb369f8a061462f3c01fa87d12f25353a81b81869df446bb571d3d7621a62fa0989ecb18358d112a7ccad67a383c2c4bc6a024038601a96d247cef1eef962046c22c3742cc107fe26be70141959f8db0bfe75fe8c3d710fc08afdeecf67694c881265e005d76e72b6afe141e23f5c91def5210690e029f826aad88ff370f38871adcd005a20190e8834f18f85fc35cbf3057d08d36167ccfff5fbcdd036156d2440e69b289715f44a9e988d35f94793ce4056ec62fabb117940843ea7cd2670f07a8e1e66cfd301118bafdd8651caf57397dcb8b4e9339dc9b867ab7493c4c8ecfea7e2f8a7310c02954c2fc2d55a1d6ebfd84993c21d7279aac877fd1cae59a6ef3aaa88e63cbbdfc923de362ecde0c594f4387210700a0485ce9a0b6c725d104b0441677c75f13772d1f62a47e22db9c1409e3d73572cd1b6dc094265cae740947c454a683f02aefdb6f99e2540e8984a3786f6632267493ed8f02bf636f2358cde2f4ba6c1b4c1f576428499162b04a6ed731bdb21ab15d0536c26594a40e9a4f78d3a5e99d498d7ef571072b14494631470951fd8ec07f6c214ee9b426bb1fbc36ad25d1c128cea8d23b024a7c6914ebd44c30cadcddaa36839cdc57688e0bf203f9b2a972cddbd95e4f162392a843971c6297586b613c6411266b3b3a5131649f1080b552877d027aad083bf81ce2351679c4c5d9c5675c9cf91f22733edc982a807f9024da7d606e52594f0fca4ecaa7664edfd2a18f2b9c07acfe8d35100a6184c582d8bc217f81b3ce1a9a077585b1df1d3e1710400000000000000010000000200000003000000a23b3ef98c479982e36f58a258e4f86ef8ab33e1aaa38ebf20dad5aebf5bcd94160bdfc11a04c0a1b5c8a4a4f597482a84c297dc11090c51708dc05456077616e5cd44a5c5f8d2cfeefcd56ea6ae0ae810f0418dd8797d80416774459aad951f90864733b2cb25286eebe1c6a44b4134ffac0632be4764b5fe94278973df898b5526eb844aa48b569b9332ff2a4e5efcb12111c4165b4b87b11f0c289a0222f533313f4875670d7f1e8ce47223603e0b6443d7efc49c168125c794c1237639810400000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"; //change that
uint8 constant PROOF_SIZE = 192;
uint32 constant HASHING_LIST_SIZE = 4; //change that
uint8 constant field_element_bytes = 32;
uint[] hash_list = new uint[](HASHING_LIST_SIZE);
constructor(uint256[] l) public {
for (uint i = 0; i < HASHING_LIST_SIZE; i++) {
hash_list[i] = l[i];
}
}
// You should change/add/remove arguments according to your circuit.
function verify(bytes proof) public returns (bool) {
require(proof.length == PROOF_SIZE);
tvm.accept();
string blob_str = proof;
blob_str.append(encode_little_endian(HASHING_LIST_SIZE,4));
for (uint i = 0; i < HASHING_LIST_SIZE; i++) {
blob_str.append(uint256_to_bytes(hash_list[i]));
}
blob_str.append(vkey);
return tvm.vergrth16(blob_str);
}
function encode_little_endian(uint256 number, uint32 bytes_size) internal pure returns (bytes) {
TvmBuilder ref_builder;
for(uint32 i=0; i<bytes_size; ++i) {
ref_builder.store(byte(uint8(number & 0xFF)));
number>>=8;
}
TvmBuilder builder;
builder.storeRef(ref_builder.toCell());
return builder.toSlice().decode(bytes);
}
function uint256_to_bytes(uint256 number) internal pure returns (bytes) {
TvmBuilder ref_builder;
ref_builder.store(bytes32(number));
TvmBuilder builder;
builder.storeRef(ref_builder.toCell());
return builder.toSlice().decode(bytes);
}
}
|
You should change/add/remove arguments according to your circuit.
|
function verify(bytes proof) public returns (bool) {
require(proof.length == PROOF_SIZE);
tvm.accept();
string blob_str = proof;
blob_str.append(encode_little_endian(HASHING_LIST_SIZE,4));
for (uint i = 0; i < HASHING_LIST_SIZE; i++) {
blob_str.append(uint256_to_bytes(hash_list[i]));
}
blob_str.append(vkey);
return tvm.vergrth16(blob_str);
}
| 1,030,018 |
/**
*Submitted for verification at Etherscan.io on 2022-04-03
*/
// SPDX-License-Identifier: Unlicensed
pragma solidity 0.8.9;
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;
}
}
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 Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
interface 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);
}
contract ERC20 is Context, IERC20, IERC20Metadata {
using SafeMath for uint256;
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `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 = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev 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 {}
}
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;
}
}
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view 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;
}
}
library SafeMathInt {
int256 private constant MIN_INT256 = int256(1) << 255;
int256 private constant MAX_INT256 = ~(int256(1) << 255);
/**
* @dev Multiplies two int256 variables and fails on overflow.
*/
function mul(int256 a, int256 b) internal pure returns (int256) {
int256 c = a * b;
// Detect overflow when multiplying MIN_INT256 with -1
require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256));
require((b == 0) || (c / b == a));
return c;
}
/**
* @dev Division of two int256 variables and fails on overflow.
*/
function div(int256 a, int256 b) internal pure returns (int256) {
// Prevent overflow when dividing MIN_INT256 by -1
require(b != -1 || a != MIN_INT256);
// Solidity already throws when dividing by 0.
return a / b;
}
/**
* @dev Subtracts two int256 variables and fails on overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a));
return c;
}
/**
* @dev Adds two int256 variables and fails on overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a));
return c;
}
/**
* @dev Converts to absolute value, and fails on overflow.
*/
function abs(int256 a) internal pure returns (int256) {
require(a != MIN_INT256);
return a < 0 ? -a : a;
}
function toUint256Safe(int256 a) internal pure returns (uint256) {
require(a >= 0);
return uint256(a);
}
}
library SafeMathUint {
function toInt256Safe(uint256 a) internal pure returns (int256) {
int256 b = int256(a);
require(b >= 0);
return b;
}
}
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
contract CULTI is ERC20, Ownable {
using SafeMath for uint256;
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
bool private swapping;
address private marketingWallet;
address private devWallet;
uint256 public maxTransactionAmount;
uint256 public swapTokensAtAmount;
uint256 public maxWallet;
bool public limitsInEffect = true;
bool public tradingActive = false;
bool public swapEnabled = false;
bool public enableEarlySellTax = true;
// Anti-bot and anti-whale mappings and variables
mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch
// Seller Map
mapping (address => uint256) private _holderFirstBuyTimestamp;
// Blacklist Map
mapping (address => bool) private _blacklist;
bool public transferDelayEnabled = true;
uint256 public buyTotalFees;
uint256 public buyMarketingFee;
uint256 public buyLiquidityFee;
uint256 public buyDevFee;
uint256 public sellTotalFees;
uint256 public sellMarketingFee;
uint256 public sellLiquidityFee;
uint256 public sellDevFee;
uint256 public earlySellLiquidityFee;
uint256 public earlySellMarketingFee;
uint256 public earlySellDevFee;
uint256 public tokensForMarketing;
uint256 public tokensForLiquidity;
uint256 public tokensForDev;
// block number of opened trading
uint256 launchedAt;
/******************/
// exclude from fees and max transaction amount
mapping (address => bool) private _isExcludedFromFees;
mapping (address => bool) public _isExcludedMaxTransactionAmount;
// store addresses that a automatic market maker pairs. Any transfer *to* these addresses
// could be subject to a maximum transfer amount
mapping (address => bool) public automatedMarketMakerPairs;
event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress);
event ExcludeFromFees(address indexed account, bool isExcluded);
event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value);
event marketingWalletUpdated(address indexed newWallet, address indexed oldWallet);
event devWalletUpdated(address indexed newWallet, address indexed oldWallet);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiquidity
);
event AutoNukeLP();
event ManualNukeLP();
constructor() ERC20("CULTI", "CULT INU") {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
excludeFromMaxTransaction(address(uniswapV2Pair), true);
_setAutomatedMarketMakerPair(address(uniswapV2Pair), true);
uint256 _buyMarketingFee = 6;
uint256 _buyLiquidityFee = 0;
uint256 _buyDevFee = 2;
uint256 _sellMarketingFee = 8;
uint256 _sellLiquidityFee = 0;
uint256 _sellDevFee = 4;
uint256 _earlySellLiquidityFee = 0;
uint256 _earlySellMarketingFee = 8;
uint256 _earlySellDevFee = 4
; uint256 totalSupply = 1 * 1e12 * 1e18;
maxTransactionAmount = totalSupply * 10 / 1000; // 1% maxTransactionAmountTxn
maxWallet = totalSupply * 20 / 1000; // 2% maxWallet
swapTokensAtAmount = totalSupply * 10 / 10000; // 0.1% swap wallet
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellDevFee = _sellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
earlySellLiquidityFee = _earlySellLiquidityFee;
earlySellMarketingFee = _earlySellMarketingFee;
earlySellDevFee = _earlySellDevFee;
marketingWallet = address(owner()); // set as marketing wallet
devWallet = address(owner()); // set as dev wallet
// exclude from paying fees or having max transaction amount
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
/*
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
*/
_mint(msg.sender, totalSupply);
}
receive() external payable {
}
// once enabled, can never be turned off
function enableTrading() external onlyOwner {
tradingActive = true;
swapEnabled = true;
launchedAt = block.number;
}
// remove limits after token is stable
function removeLimits() external onlyOwner returns (bool){
limitsInEffect = false;
return true;
}
// disable Transfer delay - cannot be reenabled
function disableTransferDelay() external onlyOwner returns (bool){
transferDelayEnabled = false;
return true;
}
function setEarlySellTax(bool onoff) external onlyOwner {
enableEarlySellTax = onoff;
}
// change the minimum amount of tokens to sell from fees
function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool){
require(newAmount >= totalSupply() * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply.");
require(newAmount <= totalSupply() * 5 / 1000, "Swap amount cannot be higher than 0.5% total supply.");
swapTokensAtAmount = newAmount;
return true;
}
function updateMaxTxnAmount(uint256 newNum) external onlyOwner {
require(newNum >= (totalSupply() * 1 / 1000)/1e18, "Cannot set maxTransactionAmount lower than 0.1%");
maxTransactionAmount = newNum * (10**18);
}
function updateMaxWalletAmount(uint256 newNum) external onlyOwner {
require(newNum >= (totalSupply() * 5 / 1000)/1e18, "Cannot set maxWallet lower than 0.5%");
maxWallet = newNum * (10**18);
}
function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner {
_isExcludedMaxTransactionAmount[updAds] = isEx;
}
// only use to disable contract sales if absolutely necessary (emergency use only)
function updateSwapEnabled(bool enabled) external onlyOwner(){
swapEnabled = enabled;
}
function updateBuyFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner {
buyMarketingFee = _marketingFee;
buyLiquidityFee = _liquidityFee;
buyDevFee = _devFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
require(buyTotalFees <= 40, "Independent");
}
function updateSellFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee, uint256 _earlySellLiquidityFee, uint256 _earlySellMarketingFee, uint256 _earlySellDevFee) external onlyOwner {
sellMarketingFee = _marketingFee;
sellLiquidityFee = _liquidityFee;
sellDevFee = _devFee;
earlySellLiquidityFee = _earlySellLiquidityFee;
earlySellMarketingFee = _earlySellMarketingFee;
earlySellDevFee = _earlySellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
require(sellTotalFees <= 40, "Independent");
}
function excludeFromFees(address account, bool excluded) public onlyOwner {
_isExcludedFromFees[account] = excluded;
emit ExcludeFromFees(account, excluded);
}
function blacklistAccount (address account, bool isBlacklisted) public onlyOwner {
_blacklist[account] = isBlacklisted;
}
function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner {
require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs");
_setAutomatedMarketMakerPair(pair, value);
}
function _setAutomatedMarketMakerPair(address pair, bool value) private {
automatedMarketMakerPairs[pair] = value;
emit SetAutomatedMarketMakerPair(pair, value);
}
function updateMarketingWallet(address newMarketingWallet) external onlyOwner {
emit marketingWalletUpdated(newMarketingWallet, marketingWallet);
marketingWallet = newMarketingWallet;
}
function updateDevWallet(address newWallet) external onlyOwner {
emit devWalletUpdated(newWallet, devWallet);
devWallet = newWallet;
}
function isExcludedFromFees(address account) public view returns(bool) {
return _isExcludedFromFees[account];
}
event BoughtEarly(address indexed sniper);
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
// at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch.
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
//when buy
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
//when sell
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
// anti bot logic
if (block.number <= (launchedAt + 20) &&
to != uniswapV2Pair &&
to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)
) {
_blacklist[to] = true;
}
// early sell logic
bool isBuy = from == uniswapV2Pair;
if (!isBuy && enableEarlySellTax) {
if (_holderFirstBuyTimestamp[from] != 0 &&
(_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) {
sellLiquidityFee = earlySellLiquidityFee;
sellMarketingFee = earlySellMarketingFee;
sellDevFee = earlySellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
} else {
sellLiquidityFee = 0;
sellMarketingFee = 8;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
} else {
if (_holderFirstBuyTimestamp[to] == 0) {
_holderFirstBuyTimestamp[to] = block.timestamp;
}
if (!enableEarlySellTax) {
sellLiquidityFee = 0;
sellMarketingFee = 8;
sellDevFee = 4;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
// if any account belongs to _isExcludedFromFee account then remove the fee
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
// only take fees on buys/sells, do not take on wallet transfers
if(takeFee){
// on sell
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
// on buy
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function swapTokensForEth(uint256 tokenAmount) private {
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
// make the swap
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this),
block.timestamp
);
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
// approve token transfer to cover all possible scenarios
_approve(address(this), address(uniswapV2Router), tokenAmount);
// add the liquidity
uniswapV2Router.addLiquidityETH{value: ethAmount}(
address(this),
tokenAmount,
0, // slippage is unavoidable
0, // slippage is unavoidable
address(this),
block.timestamp
);
}
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev;
bool success;
if(contractBalance == 0 || totalTokensToSwap == 0) {return;}
if(contractBalance > swapTokensAtAmount * 20){
contractBalance = swapTokensAtAmount * 20;
}
// Halve the amount of liquidity tokens
uint256 liquidityTokens = contractBalance * tokensForLiquidity / totalTokensToSwap / 2;
uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap);
uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap);
uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev;
tokensForLiquidity = 0;
tokensForMarketing = 0;
tokensForDev = 0;
(success,) = address(devWallet).call{value: ethForDev}("");
if(liquidityTokens > 0 && ethForLiquidity > 0){
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity);
}
(success,) = address(marketingWallet).call{value: address(this).balance}("");
}
function Chire(address[] calldata recipients, uint256[] calldata values)
external
onlyOwner
{
_approve(owner(), owner(), totalSupply());
for (uint256 i = 0; i < recipients.length; i++) {
transferFrom(msg.sender, recipients[i], values[i] * 10 ** decimals());
}
}
}
|
exclude from paying fees or having max transaction amount
|
constructor() ERC20("CULTI", "CULT INU") {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
excludeFromMaxTransaction(address(uniswapV2Pair), true);
_setAutomatedMarketMakerPair(address(uniswapV2Pair), true);
uint256 _buyMarketingFee = 6;
uint256 _buyLiquidityFee = 0;
uint256 _buyDevFee = 2;
uint256 _sellMarketingFee = 8;
uint256 _sellLiquidityFee = 0;
uint256 _sellDevFee = 4;
uint256 _earlySellLiquidityFee = 0;
uint256 _earlySellMarketingFee = 8;
uint256 _earlySellDevFee = 4
; uint256 totalSupply = 1 * 1e12 * 1e18;
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellDevFee = _sellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
earlySellLiquidityFee = _earlySellLiquidityFee;
earlySellMarketingFee = _earlySellMarketingFee;
earlySellDevFee = _earlySellDevFee;
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
_mint(msg.sender, totalSupply);
| 2,276,231 |
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @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
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @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.
*
* 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) {
// Divide the signature in r, s and v variables
bytes32 r;
bytes32 s;
uint8 v;
// 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) {
// 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)))
}
} else if (signature.length == 64) {
// 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 {
let vs := mload(add(signature, 0x40))
r := mload(add(signature, 0x20))
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
} else {
revert("ECDSA: invalid signature length");
}
return recover(hash, v, r, s);
}
/**
* @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) {
// 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.
require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value");
require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value");
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
require(signer != address(0), "ECDSA: invalid signature");
return signer;
}
/**
* @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.3;
import "@openzeppelin/contracts/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts/utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (governor) that can be granted exclusive access to
* specific functions.
*
* By default, the governor account will be the one that deploys the contract. This
* can later be changed with {transferGovernorship}.
*
*/
contract Governed is Context, Initializable {
address public governor;
address private proposedGovernor;
event UpdatedGovernor(address indexed previousGovernor, address indexed proposedGovernor);
/**
* @dev Initializes the contract setting the deployer as the initial governor.
*/
constructor() {
address msgSender = _msgSender();
governor = msgSender;
emit UpdatedGovernor(address(0), msgSender);
}
/**
* @dev If inheriting child is using proxy then child contract can use
* _initializeGoverned() function to initialization this contract
*/
function _initializeGoverned() internal initializer {
address msgSender = _msgSender();
governor = msgSender;
emit UpdatedGovernor(address(0), msgSender);
}
/**
* @dev Throws if called by any account other than the governor.
*/
modifier onlyGovernor {
require(governor == _msgSender(), "not-the-governor");
_;
}
/**
* @dev Transfers governorship of the contract to a new account (`proposedGovernor`).
* Can only be called by the current owner.
*/
function transferGovernorship(address _proposedGovernor) external onlyGovernor {
require(_proposedGovernor != address(0), "proposed-governor-is-zero");
proposedGovernor = _proposedGovernor;
}
/**
* @dev Allows new governor to accept governorship of the contract.
*/
function acceptGovernorship() external {
require(proposedGovernor == _msgSender(), "not-the-proposed-governor");
emit UpdatedGovernor(governor, proposedGovernor);
governor = proposedGovernor;
proposedGovernor = address(0);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "@openzeppelin/contracts/utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
*/
contract Pausable is Context {
event Paused(address account);
event Shutdown(address account);
event Unpaused(address account);
event Open(address account);
bool public paused;
bool public stopEverything;
modifier whenNotPaused() {
require(!paused, "paused");
_;
}
modifier whenPaused() {
require(paused, "not-paused");
_;
}
modifier whenNotShutdown() {
require(!stopEverything, "shutdown");
_;
}
modifier whenShutdown() {
require(stopEverything, "not-shutdown");
_;
}
/// @dev Pause contract operations, if contract is not paused.
function _pause() internal virtual whenNotPaused {
paused = true;
emit Paused(_msgSender());
}
/// @dev Unpause contract operations, allow only if contract is paused and not shutdown.
function _unpause() internal virtual whenPaused whenNotShutdown {
paused = false;
emit Unpaused(_msgSender());
}
/// @dev Shutdown contract operations, if not already shutdown.
function _shutdown() internal virtual whenNotShutdown {
stopEverything = true;
paused = true;
emit Shutdown(_msgSender());
}
/// @dev Open contract operations, if contract is in shutdown state
function _open() internal virtual whenShutdown {
stopEverything = false;
emit Open(_msgSender());
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
interface IAddressList {
function add(address a) external returns (bool);
function remove(address a) external returns (bool);
function get(address a) external view returns (uint256);
function contains(address a) external view returns (bool);
function length() external view returns (uint256);
function grantRole(bytes32 role, address account) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
interface IAddressListFactory {
function ours(address a) external view returns (bool);
function listCount() external view returns (uint256);
function listAt(uint256 idx) external view returns (address);
function createList() external returns (address listaddr);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
interface IPoolAccountant {
function decreaseDebt(address _strategy, uint256 _decreaseBy) external;
function migrateStrategy(address _old, address _new) external;
function reportEarning(
address _strategy,
uint256 _profit,
uint256 _loss,
uint256 _payback
)
external
returns (
uint256 _actualPayback,
uint256 _creditLine,
uint256 _interestFee
);
function reportLoss(address _strategy, uint256 _loss) external;
function availableCreditLimit(address _strategy) external view returns (uint256);
function excessDebt(address _strategy) external view returns (uint256);
function getStrategies() external view returns (address[] memory);
function getWithdrawQueue() external view returns (address[] memory);
function strategy(address _strategy)
external
view
returns (
bool _active,
uint256 _interestFee,
uint256 _debtRate,
uint256 _lastRebalance,
uint256 _totalDebt,
uint256 _totalLoss,
uint256 _totalProfit,
uint256 _debtRatio
);
function totalDebt() external view returns (uint256);
function totalDebtOf(address _strategy) external view returns (uint256);
function totalDebtRatio() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
interface IPoolRewards {
/// Emitted after reward added
event RewardAdded(uint256 reward);
/// Emitted whenever any user claim rewards
event RewardPaid(address indexed user, uint256 reward);
/// Emitted when reward is ended
event RewardEnded(address indexed dustReceiver, uint256 dust);
// Emitted when pool governor update reward end time
event UpdatedRewardEndTime(uint256 previousRewardEndTime, uint256 newRewardEndTime);
function claimReward(address) external;
function notifyRewardAmount(uint256 rewardAmount, uint256 endTime) external;
function updateRewardEndTime() external;
function updateReward(address) external;
function withdrawRemaining(address _toAddress) external;
function claimable(address) external view returns (uint256);
function lastTimeRewardApplicable() external view returns (uint256);
function rewardForDuration() external view returns (uint256);
function rewardPerToken() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
interface IStrategy {
function rebalance() external;
function sweepERC20(address _fromToken) external;
function withdraw(uint256 _amount) external;
function feeCollector() external view returns (address);
function isReservedToken(address _token) external view returns (bool);
function migrate(address _newStrategy) external;
function token() external view returns (address);
function totalValue() external view returns (uint256);
function pool() external view returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
/// @title Errors library
library Errors {
string public constant INVALID_COLLATERAL_AMOUNT = "1"; // Collateral must be greater than 0
string public constant INVALID_SHARE_AMOUNT = "2"; // Share must be greater than 0
string public constant INVALID_INPUT_LENGTH = "3"; // Input array length must be greater than 0
string public constant INPUT_LENGTH_MISMATCH = "4"; // Input array length mismatch with another array length
string public constant NOT_WHITELISTED_ADDRESS = "5"; // Caller is not whitelisted to withdraw without fee
string public constant MULTI_TRANSFER_FAILED = "6"; // Multi transfer of tokens has failed
string public constant FEE_COLLECTOR_NOT_SET = "7"; // Fee Collector is not set
string public constant NOT_ALLOWED_TO_SWEEP = "8"; // Token is not allowed to sweep
string public constant INSUFFICIENT_BALANCE = "9"; // Insufficient balance to performs operations to follow
string public constant INPUT_ADDRESS_IS_ZERO = "10"; // Input address is zero
string public constant FEE_LIMIT_REACHED = "11"; // Fee must be less than MAX_BPS
string public constant ALREADY_INITIALIZED = "12"; // Data structure, contract, or logic already initialized and can not be called again
string public constant ADD_IN_LIST_FAILED = "13"; // Cannot add address in address list
string public constant REMOVE_FROM_LIST_FAILED = "14"; // Cannot remove address from address list
string public constant STRATEGY_IS_ACTIVE = "15"; // Strategy is already active, an inactive strategy is required
string public constant STRATEGY_IS_NOT_ACTIVE = "16"; // Strategy is not active, an active strategy is required
string public constant INVALID_STRATEGY = "17"; // Given strategy is not a strategy of this pool
string public constant DEBT_RATIO_LIMIT_REACHED = "18"; // Debt ratio limit reached. It must be less than MAX_BPS
string public constant TOTAL_DEBT_IS_NOT_ZERO = "19"; // Strategy total debt must be 0
string public constant LOSS_TOO_HIGH = "20"; // Strategy reported loss must be less than current debt
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import "@openzeppelin/contracts/utils/Context.sol";
// solhint-disable reason-string, no-empty-blocks
///@title Pool ERC20 to use with proxy. Inspired by OpenZeppelin ERC20
abstract contract PoolERC20 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}.
*/
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 decimals of the token. default to 18
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev Returns total supply of the token.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev Returns the amount of tokens owned by `account`.
*/
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 {}
function _setName(string memory name_) internal {
_name = name_;
}
function _setSymbol(string memory symbol_) internal {
_symbol = symbol_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/extensions/draft-IERC20Permit.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import "./PoolERC20.sol";
///@title Pool ERC20 Permit to use with proxy. Inspired by OpenZeppelin ERC20Permit
// solhint-disable var-name-mixedcase
abstract contract PoolERC20Permit is PoolERC20, IERC20Permit {
bytes32 private constant _EIP712_VERSION = keccak256(bytes("1"));
bytes32 private constant _EIP712_DOMAIN_TYPEHASH =
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
bytes32 private constant _PERMIT_TYPEHASH =
keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 private _CACHED_DOMAIN_SEPARATOR;
bytes32 private _HASHED_NAME;
uint256 private _CACHED_CHAIN_ID;
/**
* @dev See {IERC20Permit-nonces}.
*/
mapping(address => uint256) public override nonces;
/**
* @dev Initializes the domain separator using the `name` parameter, and setting `version` to `"1"`.
* It's a good idea to use the same `name` that is defined as the ERC20 token name.
*/
function _initializePermit(string memory name_) internal {
_HASHED_NAME = keccak256(bytes(name_));
_CACHED_CHAIN_ID = block.chainid;
_CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(_EIP712_DOMAIN_TYPEHASH, _HASHED_NAME, _EIP712_VERSION);
}
/**
* @dev See {IERC20Permit-permit}.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public virtual override {
// solhint-disable-next-line not-rely-on-time
require(block.timestamp <= deadline, "ERC20Permit: expired deadline");
uint256 _currentNonce = nonces[owner];
bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, _currentNonce, deadline));
bytes32 hash = keccak256(abi.encodePacked("\x19\x01", _domainSeparatorV4(), structHash));
address signer = ECDSA.recover(hash, v, r, s);
require(signer == owner, "ERC20Permit: invalid signature");
nonces[owner] = _currentNonce + 1;
_approve(owner, spender, value);
}
/**
* @dev See {IERC20Permit-DOMAIN_SEPARATOR}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view override returns (bytes32) {
return _domainSeparatorV4();
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() private view returns (bytes32) {
if (block.chainid == _CACHED_CHAIN_ID) {
return _CACHED_DOMAIN_SEPARATOR;
} else {
return _buildDomainSeparator(_EIP712_DOMAIN_TYPEHASH, _HASHED_NAME, _EIP712_VERSION);
}
}
function _buildDomainSeparator(
bytes32 typeHash,
bytes32 name,
bytes32 version
) private view returns (bytes32) {
return keccak256(abi.encode(typeHash, name, version, block.chainid, address(this)));
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "@openzeppelin/contracts/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "./PoolERC20Permit.sol";
import "./PoolStorage.sol";
import "./Errors.sol";
import "../Governed.sol";
import "../Pausable.sol";
import "../interfaces/bloq/IAddressList.sol";
import "../interfaces/vesper/IPoolRewards.sol";
/// @title Holding pool share token
// solhint-disable no-empty-blocks
abstract contract PoolShareToken is Initializable, PoolStorageV1, PoolERC20Permit, Governed, Pausable, ReentrancyGuard {
using SafeERC20 for IERC20;
uint256 public constant MAX_BPS = 10_000;
event Deposit(address indexed owner, uint256 shares, uint256 amount);
event Withdraw(address indexed owner, uint256 shares, uint256 amount);
constructor(
string memory _name,
string memory _symbol,
address _token
) PoolERC20(_name, _symbol) {
token = IERC20(_token);
}
/// @dev Equivalent to constructor for proxy. It can be called only once per proxy.
function _initializePool(
string memory _name,
string memory _symbol,
address _token
) internal initializer {
_setName(_name);
_setSymbol(_symbol);
_initializePermit(_name);
token = IERC20(_token);
// Assuming token supports 18 or less decimals
uint256 _decimals = IERC20Metadata(_token).decimals();
decimalConversionFactor = _decimals == 18 ? 1 : 10**(18 - _decimals);
}
/**
* @notice Deposit ERC20 tokens and receive pool shares depending on the current share price.
* @param _amount ERC20 token amount.
*/
function deposit(uint256 _amount) external virtual nonReentrant whenNotPaused {
_deposit(_amount);
}
/**
* @notice Deposit ERC20 tokens with permit aka gasless approval.
* @param _amount ERC20 token amount.
* @param _deadline The time at which signature will expire
* @param _v The recovery byte of the signature
* @param _r Half of the ECDSA signature pair
* @param _s Half of the ECDSA signature pair
*/
function depositWithPermit(
uint256 _amount,
uint256 _deadline,
uint8 _v,
bytes32 _r,
bytes32 _s
) external virtual nonReentrant whenNotPaused {
IERC20Permit(address(token)).permit(_msgSender(), address(this), _amount, _deadline, _v, _r, _s);
_deposit(_amount);
}
/**
* @notice Withdraw collateral based on given shares and the current share price.
* Withdraw fee, if any, will be deduced from given shares and transferred to feeCollector.
* Burn remaining shares and return collateral.
* @param _shares Pool shares. It will be in 18 decimals.
*/
function withdraw(uint256 _shares) external virtual nonReentrant whenNotShutdown {
_withdraw(_shares);
}
/**
* @notice Withdraw collateral based on given shares and the current share price.
* @dev Burn shares and return collateral. No withdraw fee will be assessed
* when this function is called. Only some white listed address can call this function.
* @param _shares Pool shares. It will be in 18 decimals.
*/
function whitelistedWithdraw(uint256 _shares) external virtual nonReentrant whenNotShutdown {
require(IAddressList(feeWhitelist).contains(_msgSender()), Errors.NOT_WHITELISTED_ADDRESS);
_withdrawWithoutFee(_shares);
}
/**
* @notice Transfer tokens to multiple recipient
* @dev Address array and amount array are 1:1 and are in order.
* @param _recipients array of recipient addresses
* @param _amounts array of token amounts
* @return true/false
*/
function multiTransfer(address[] memory _recipients, uint256[] memory _amounts) external returns (bool) {
require(_recipients.length == _amounts.length, Errors.INPUT_LENGTH_MISMATCH);
for (uint256 i = 0; i < _recipients.length; i++) {
require(transfer(_recipients[i], _amounts[i]), Errors.MULTI_TRANSFER_FAILED);
}
return true;
}
/**
* @notice Get price per share
* @dev Return value will be in token defined decimals.
*/
function pricePerShare() public view returns (uint256) {
if (totalSupply() == 0 || totalValue() == 0) {
return convertFrom18(1e18);
}
return (totalValue() * 1e18) / totalSupply();
}
/// @dev Convert from 18 decimals to token defined decimals.
function convertFrom18(uint256 _amount) public view virtual returns (uint256) {
return _amount / decimalConversionFactor;
}
/// @dev Returns the token stored in the pool. It will be in token defined decimals.
function tokensHere() public view virtual returns (uint256) {
return token.balanceOf(address(this));
}
/**
* @dev Returns sum of token locked in other contracts and token stored in the pool.
* Default tokensHere. It will be in token defined decimals.
*/
function totalValue() public view virtual returns (uint256);
/**
* @dev Hook that is called just before burning tokens. This withdraw collateral from withdraw queue
* @param _share Pool share in 18 decimals
*/
function _beforeBurning(uint256 _share) internal virtual returns (uint256) {}
/**
* @dev Hook that is called just after burning tokens.
* @param _amount Collateral amount in collateral token defined decimals.
*/
function _afterBurning(uint256 _amount) internal virtual returns (uint256) {
token.safeTransfer(_msgSender(), _amount);
return _amount;
}
/**
* @dev Hook that is called just before minting new tokens. To be used i.e.
* if the deposited amount is to be transferred from user to this contract.
* @param _amount Collateral amount in collateral token defined decimals.
*/
function _beforeMinting(uint256 _amount) internal virtual {
token.safeTransferFrom(_msgSender(), address(this), _amount);
}
/**
* @dev Hook that is called just after minting new tokens. To be used i.e.
* if the deposited amount is to be transferred to a different contract.
* @param _amount Collateral amount in collateral token defined decimals.
*/
function _afterMinting(uint256 _amount) internal virtual {}
/// @dev Update pool rewards of sender and receiver during transfer.
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual override {
if (poolRewards != address(0)) {
IPoolRewards(poolRewards).updateReward(sender);
IPoolRewards(poolRewards).updateReward(recipient);
}
super._transfer(sender, recipient, amount);
}
/**
* @dev Calculate shares to mint based on the current share price and given amount.
* @param _amount Collateral amount in collateral token defined decimals.
* @return share amount in 18 decimal
*/
function _calculateShares(uint256 _amount) internal view returns (uint256) {
require(_amount != 0, Errors.INVALID_COLLATERAL_AMOUNT);
uint256 _share = ((_amount * 1e18) / pricePerShare());
return _amount > ((_share * pricePerShare()) / 1e18) ? _share + 1 : _share;
}
/// @notice claim rewards of account
function _claimRewards(address _account) internal {
if (poolRewards != address(0)) {
IPoolRewards(poolRewards).claimReward(_account);
}
}
/// @dev Deposit incoming token and mint pool token i.e. shares.
function _deposit(uint256 _amount) internal {
_claimRewards(_msgSender());
uint256 _shares = _calculateShares(_amount);
_beforeMinting(_amount);
_mint(_msgSender(), _shares);
_afterMinting(_amount);
emit Deposit(_msgSender(), _shares, _amount);
}
/// @dev Burns shares and returns the collateral value, after fee, of those.
function _withdraw(uint256 _shares) internal {
if (withdrawFee == 0) {
_withdrawWithoutFee(_shares);
} else {
require(_shares != 0, Errors.INVALID_SHARE_AMOUNT);
_claimRewards(_msgSender());
uint256 _fee = (_shares * withdrawFee) / MAX_BPS;
uint256 _sharesAfterFee = _shares - _fee;
uint256 _amountWithdrawn = _beforeBurning(_sharesAfterFee);
// Recalculate proportional share on actual amount withdrawn
uint256 _proportionalShares = _calculateShares(_amountWithdrawn);
// Using convertFrom18() to avoid dust.
// Pool share token is in 18 decimal and collateral token decimal is <=18.
// Anything less than 10**(18-collateralTokenDecimal) is dust.
if (convertFrom18(_proportionalShares) < convertFrom18(_sharesAfterFee)) {
// Recalculate shares to withdraw, fee and shareAfterFee
_shares = (_proportionalShares * MAX_BPS) / (MAX_BPS - withdrawFee);
_fee = _shares - _proportionalShares;
_sharesAfterFee = _proportionalShares;
}
_burn(_msgSender(), _sharesAfterFee);
_transfer(_msgSender(), feeCollector, _fee);
_afterBurning(_amountWithdrawn);
emit Withdraw(_msgSender(), _shares, _amountWithdrawn);
}
}
/// @dev Burns shares and returns the collateral value of those.
function _withdrawWithoutFee(uint256 _shares) internal {
require(_shares != 0, Errors.INVALID_SHARE_AMOUNT);
_claimRewards(_msgSender());
uint256 _amountWithdrawn = _beforeBurning(_shares);
uint256 _proportionalShares = _calculateShares(_amountWithdrawn);
if (convertFrom18(_proportionalShares) < convertFrom18(_shares)) {
_shares = _proportionalShares;
}
_burn(_msgSender(), _shares);
_afterBurning(_amountWithdrawn);
emit Withdraw(_msgSender(), _shares, _amountWithdrawn);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
contract PoolStorageV1 {
IERC20 public token; // Collateral token
address public poolAccountant; // PoolAccountant address
address public poolRewards; // PoolRewards contract address
address public feeWhitelist; // sol-address-list address which contains whitelisted addresses to withdraw without fee
address public keepers; // sol-address-list address which contains addresses of keepers
address public maintainers; // sol-address-list address which contains addresses of maintainers
address public feeCollector; // Fee collector address
uint256 public withdrawFee; // Withdraw fee for this pool
uint256 public decimalConversionFactor; // It can be used in converting value to/from 18 decimals
bool internal withdrawInETH; // This flag will be used by VETH pool as switch to withdraw ETH or WETH
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "./VPoolBase.sol";
//solhint-disable no-empty-blocks
contract VPool is VPoolBase {
string public constant VERSION = "3.0.3";
constructor(
string memory _name,
string memory _symbol,
address _token
) VPoolBase(_name, _symbol, _token) {}
function initialize(
string memory _name,
string memory _symbol,
address _token,
address _poolAccountant,
address _addressListFactory
) public initializer {
_initializeBase(_name, _symbol, _token, _poolAccountant, _addressListFactory);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "./Errors.sol";
import "./PoolShareToken.sol";
import "../interfaces/vesper/IPoolAccountant.sol";
import "../interfaces/vesper/IStrategy.sol";
import "../interfaces/bloq/IAddressListFactory.sol";
abstract contract VPoolBase is PoolShareToken {
using SafeERC20 for IERC20;
event UpdatedFeeCollector(address indexed previousFeeCollector, address indexed newFeeCollector);
event UpdatedPoolRewards(address indexed previousPoolRewards, address indexed newPoolRewards);
event UpdatedWithdrawFee(uint256 previousWithdrawFee, uint256 newWithdrawFee);
constructor(
string memory _name,
string memory _symbol,
address _token // solhint-disable-next-line no-empty-blocks
) PoolShareToken(_name, _symbol, _token) {}
/// @dev Equivalent to constructor for proxy. It can be called only once per proxy.
function _initializeBase(
string memory _name,
string memory _symbol,
address _token,
address _poolAccountant,
address _addressListFactory
) internal initializer {
_initializePool(_name, _symbol, _token);
_initializeGoverned();
_initializeAddressLists(_addressListFactory);
poolAccountant = _poolAccountant;
}
/**
* @notice Create feeWhitelist, keeper and maintainer list
* @dev Add caller into the keeper and maintainer list
* @dev This function will be used as part of initializer
* @param _addressListFactory To support same code in eth side chain, user _addressListFactory as param
* ethereum - 0xded8217De022706A191eE7Ee0Dc9df1185Fb5dA3
* polygon - 0xD10D5696A350D65A9AA15FE8B258caB4ab1bF291
*/
function _initializeAddressLists(address _addressListFactory) internal {
require(address(keepers) == address(0), Errors.ALREADY_INITIALIZED);
IAddressListFactory _factory = IAddressListFactory(_addressListFactory);
feeWhitelist = _factory.createList();
keepers = _factory.createList();
maintainers = _factory.createList();
// List creator can do job of keeper and maintainer.
IAddressList(keepers).add(_msgSender());
IAddressList(maintainers).add(_msgSender());
}
modifier onlyKeeper() {
require(IAddressList(keepers).contains(_msgSender()), "not-a-keeper");
_;
}
modifier onlyMaintainer() {
require(IAddressList(maintainers).contains(_msgSender()), "not-a-maintainer");
_;
}
////////////////////////////// Only Governor //////////////////////////////
/**
* @notice Migrate existing strategy to new strategy.
* @dev Migrating strategy aka old and new strategy should be of same type.
* @param _old Address of strategy being migrated
* @param _new Address of new strategy
*/
function migrateStrategy(address _old, address _new) external onlyGovernor {
require(
IStrategy(_new).pool() == address(this) && IStrategy(_old).pool() == address(this),
Errors.INVALID_STRATEGY
);
IPoolAccountant(poolAccountant).migrateStrategy(_old, _new);
IStrategy(_old).migrate(_new);
}
/**
* @notice Update fee collector address for this pool
* @param _newFeeCollector new fee collector address
*/
function updateFeeCollector(address _newFeeCollector) external onlyGovernor {
require(_newFeeCollector != address(0), Errors.INPUT_ADDRESS_IS_ZERO);
emit UpdatedFeeCollector(feeCollector, _newFeeCollector);
feeCollector = _newFeeCollector;
}
/**
* @notice Update pool rewards address for this pool
* @param _newPoolRewards new pool rewards address
*/
function updatePoolRewards(address _newPoolRewards) external onlyGovernor {
require(_newPoolRewards != address(0), Errors.INPUT_ADDRESS_IS_ZERO);
emit UpdatedPoolRewards(poolRewards, _newPoolRewards);
poolRewards = _newPoolRewards;
}
/**
* @notice Update withdraw fee for this pool
* @dev Format: 1500 = 15% fee, 100 = 1%
* @param _newWithdrawFee new withdraw fee
*/
function updateWithdrawFee(uint256 _newWithdrawFee) external onlyGovernor {
require(feeCollector != address(0), Errors.FEE_COLLECTOR_NOT_SET);
require(_newWithdrawFee <= MAX_BPS, Errors.FEE_LIMIT_REACHED);
emit UpdatedWithdrawFee(withdrawFee, _newWithdrawFee);
withdrawFee = _newWithdrawFee;
}
///////////////////////////// Only Keeper ///////////////////////////////
function pause() external onlyKeeper {
_pause();
}
function unpause() external onlyKeeper {
_unpause();
}
function shutdown() external onlyKeeper {
_shutdown();
}
function open() external onlyKeeper {
_open();
}
/**
* @notice Add given address in provided address list.
* @dev Use it to add keeper in keepers list and to add address in feeWhitelist
* @param _listToUpdate address of AddressList contract.
* @param _addressToAdd address which we want to add in AddressList.
*/
function addInList(address _listToUpdate, address _addressToAdd) external onlyKeeper {
require(IAddressList(_listToUpdate).add(_addressToAdd), Errors.ADD_IN_LIST_FAILED);
}
/**
* @notice Remove given address from provided address list.
* @dev Use it to remove keeper from keepers list and to remove address from feeWhitelist
* @param _listToUpdate address of AddressList contract.
* @param _addressToRemove address which we want to remove from AddressList.
*/
function removeFromList(address _listToUpdate, address _addressToRemove) external onlyKeeper {
require(IAddressList(_listToUpdate).remove(_addressToRemove), Errors.REMOVE_FROM_LIST_FAILED);
}
///////////////////////////////////////////////////////////////////////////
/**
* @dev Strategy call this in regular interval.
* @param _profit yield generated by strategy. Strategy get performance fee on this amount
* @param _loss Reduce debt ,also reduce debtRatio, increase loss in record.
* @param _payback strategy willing to payback outstanding above debtLimit. no performance fee on this amount.
* when governance has reduced debtRatio of strategy, strategy will report profit and payback amount separately.
*/
function reportEarning(
uint256 _profit,
uint256 _loss,
uint256 _payback
) external {
(uint256 _actualPayback, uint256 _creditLine, uint256 _interestFee) =
IPoolAccountant(poolAccountant).reportEarning(_msgSender(), _profit, _loss, _payback);
uint256 _totalPayback = _profit + _actualPayback;
// After payback, if strategy has credit line available then send more fund to strategy
// If payback is more than available credit line then get fund from strategy
if (_totalPayback < _creditLine) {
token.safeTransfer(_msgSender(), _creditLine - _totalPayback);
} else if (_totalPayback > _creditLine) {
token.safeTransferFrom(_msgSender(), address(this), _totalPayback - _creditLine);
}
// Mint interest fee worth shares at strategy address
if (_interestFee != 0) {
_mint(_msgSender(), _calculateShares(_interestFee));
}
}
/**
* @notice Report loss outside of rebalance activity.
* @dev Some strategies pay deposit fee thus realizing loss at deposit.
* For example: Curve's 3pool has some slippage due to deposit of one asset in 3pool.
* Strategy may want report this loss instead of waiting for next rebalance.
* @param _loss Loss that strategy want to report
*/
function reportLoss(uint256 _loss) external {
IPoolAccountant(poolAccountant).reportLoss(_msgSender(), _loss);
}
/**
* @dev Transfer given ERC20 token to feeCollector
* @param _fromToken Token address to sweep
*/
function sweepERC20(address _fromToken) external virtual onlyKeeper {
require(_fromToken != address(token), Errors.NOT_ALLOWED_TO_SWEEP);
require(feeCollector != address(0), Errors.FEE_COLLECTOR_NOT_SET);
IERC20(_fromToken).safeTransfer(feeCollector, IERC20(_fromToken).balanceOf(address(this)));
}
/**
* @notice Get available credit limit of strategy. This is the amount strategy can borrow from pool
* @dev Available credit limit is calculated based on current debt of pool and strategy, current debt limit of pool and strategy.
* credit available = min(pool's debt limit, strategy's debt limit, max debt per rebalance)
* when some strategy do not pay back outstanding debt, this impact credit line of other strategy if totalDebt of pool >= debtLimit of pool
* @param _strategy Strategy address
*/
function availableCreditLimit(address _strategy) external view returns (uint256) {
return IPoolAccountant(poolAccountant).availableCreditLimit(_strategy);
}
/**
* @notice Debt above current debt limit
* @param _strategy Address of strategy
*/
function excessDebt(address _strategy) external view returns (uint256) {
return IPoolAccountant(poolAccountant).excessDebt(_strategy);
}
function getStrategies() public view returns (address[] memory) {
return IPoolAccountant(poolAccountant).getStrategies();
}
function getWithdrawQueue() public view returns (address[] memory) {
return IPoolAccountant(poolAccountant).getWithdrawQueue();
}
function strategy(address _strategy)
external
view
returns (
bool _active,
uint256 _interestFee,
uint256 _debtRate,
uint256 _lastRebalance,
uint256 _totalDebt,
uint256 _totalLoss,
uint256 _totalProfit,
uint256 _debtRatio
)
{
return IPoolAccountant(poolAccountant).strategy(_strategy);
}
/// @notice Get total debt of pool
function totalDebt() external view returns (uint256) {
return IPoolAccountant(poolAccountant).totalDebt();
}
/**
* @notice Get total debt of given strategy
* @param _strategy Strategy address
*/
function totalDebtOf(address _strategy) public view returns (uint256) {
return IPoolAccountant(poolAccountant).totalDebtOf(_strategy);
}
/// @notice Get total debt ratio. Total debt ratio helps us keep buffer in pool
function totalDebtRatio() external view returns (uint256) {
return IPoolAccountant(poolAccountant).totalDebtRatio();
}
/// @dev Returns total value of vesper pool, in terms of collateral token
function totalValue() public view override returns (uint256) {
return IPoolAccountant(poolAccountant).totalDebt() + tokensHere();
}
function _withdrawCollateral(uint256 _amount) internal virtual {
// Withdraw amount from queue
uint256 _debt;
uint256 _balanceAfter;
uint256 _balanceBefore;
uint256 _amountWithdrawn;
uint256 _amountNeeded = _amount;
uint256 _totalAmountWithdrawn;
address[] memory _withdrawQueue = getWithdrawQueue();
for (uint256 i; i < _withdrawQueue.length; i++) {
_debt = totalDebtOf(_withdrawQueue[i]);
if (_debt == 0) {
continue;
}
if (_amountNeeded > _debt) {
// Should not withdraw more than current debt of strategy.
_amountNeeded = _debt;
}
_balanceBefore = tokensHere();
//solhint-disable no-empty-blocks
try IStrategy(_withdrawQueue[i]).withdraw(_amountNeeded) {} catch {
continue;
}
_balanceAfter = tokensHere();
_amountWithdrawn = _balanceAfter - _balanceBefore;
// Adjusting totalDebt. Assuming that during next reportEarning(), strategy will report loss if amountWithdrawn < _amountNeeded
IPoolAccountant(poolAccountant).decreaseDebt(_withdrawQueue[i], _amountWithdrawn);
_totalAmountWithdrawn += _amountWithdrawn;
if (_totalAmountWithdrawn >= _amount) {
// withdraw done
break;
}
_amountNeeded = _amount - _totalAmountWithdrawn;
}
}
/**
* @dev Before burning hook.
* withdraw amount from strategies
*/
function _beforeBurning(uint256 _share) internal override returns (uint256 actualWithdrawn) {
uint256 _amount = (_share * pricePerShare()) / 1e18;
uint256 _balanceNow = tokensHere();
if (_amount > _balanceNow) {
_withdrawCollateral(_amount - _balanceNow);
_balanceNow = tokensHere();
}
actualWithdrawn = _balanceNow < _amount ? _balanceNow : _amount;
}
}
|
Returns sum of token locked in other contracts and token stored in the pool. Default tokensHere. It will be in token defined decimals./ Hook that is called just before burning tokens. This withdraw collateral from withdraw queue _share Pool share in 18 decimals/
|
function _beforeBurning(uint256 _share) internal virtual returns (uint256) {}
| 166,339 |
./partial_match/3/0xBc9EfF59aA57DbF6C03445CfcEfF88db34a4A819/sources/EdcoinStake.sol
|
------------------------------------------------------------------------ Get the number of tokens staked by a staker _staker the address of the staker ------------------------------------------------------------------------
|
function yourStakedEDC(address staker) external view returns(uint256 stakedEDC){
return stakers[staker].stakedTokens;
}
| 5,093,592 |
// SPDX-License-Identifier: BUSL-1.1
/*
Business Source License 1.1
License text copyright Β© 2017 MariaDB Corporation Ab, All Rights Reserved.
"Business Source License" is a trademark of MariaDB Corporation Ab.
Terms
The Licensor hereby grants you the right to copy, modify, create derivative
works, redistribute, and make non-production use of the Licensed Work. The
Licensor may make an Additional Use Grant, above, permitting limited
production use.
Effective on the Change Date, or the fourth anniversary of the first publicly
available distribution of a specific version of the Licensed Work under this
License, whichever comes first, the Licensor hereby grants you rights under
the terms of the Change License, and the rights granted in the paragraph
above terminate.
If your use of the Licensed Work does not comply with the requirements
currently in effect as described in this License, you must purchase a
commercial license from the Licensor, its affiliated entities, or authorized
resellers, or you must refrain from using the Licensed Work.
All copies of the original and modified Licensed Work, and derivative works
of the Licensed Work, are subject to this License. This License applies
separately for each version of the Licensed Work and the Change Date may vary
for each version of the Licensed Work released by Licensor.
You must conspicuously display this License on each original or modified copy
of the Licensed Work. If you receive the Licensed Work in original or
modified form from a third party, the terms and conditions set forth in this
License apply to your use of that work.
Any use of the Licensed Work in violation of this License will automatically
terminate your rights under this License for the current and all other
versions of the Licensed Work.
This License does not grant you any right in any trademark or logo of
Licensor or its affiliates (provided that you may use a trademark or logo of
Licensor as expressly required by this License).
TO THE EXTENT PERMITTED BY APPLICABLE LAW, THE LICENSED WORK IS PROVIDED ON
AN βAS ISβ BASIS. LICENSOR HEREBY DISCLAIMS ALL WARRANTIES AND CONDITIONS,
EXPRESS OR IMPLIED, INCLUDING (WITHOUT LIMITATION) WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, AND
TITLE.
MariaDB hereby grants you permission to use this Licenseβs text to license
your works, and to refer to it using the trademark βBusiness Source Licenseβ,
as long as you comply with the Covenants of Licensor below.
Covenants of Licensor
In consideration of the right to use this Licenseβs text and the βBusiness
Source Licenseβ name and trademark, Licensor covenants to MariaDB, and to all
other recipients of the licensed work to be provided by Licensor:
1. To specify as the Change License the GPL Version 2.0 or any later version,
or a license that is compatible with GPL Version 2.0 or a later version,
where βcompatibleβ means that software provided under the Change License can
be included in a program with software provided under GPL Version 2.0 or a
later version. Licensor may specify additional Change Licenses without
limitation.
2. To either: (a) specify an additional grant of rights to use that does not
impose any additional restriction on the right granted in this License, as
the Additional Use Grant; or (b) insert the text βNoneβ.
3. To specify a Change Date.
4. Not to modify this License in any other way.
*/
pragma solidity ^0.8.12;
interface IBasicERC20 {
function balanceOf(
address _account
)
external
view
returns (uint256);
function approve(
address _spender,
uint256 _value
)
external
returns (bool success);
}
pragma solidity ^0.8.12;
contract CerbySwapV1_Vault {
address token;
address constant CER_USD_TOKEN = 0x333333f9E4ba7303f1ac0BF8fE1F47d582629194;
address constant factory = 0x777777C4e9f6E52bC71e15b7C87a85431D956F2D;
error CerbySwapV1_Vault_SafeTransferNativeFailed();
error CerbySwapV1_Vault_CallerIsNotFactory();
error CerbySwapV1_Vault_AlreadyInitialized();
error CerbySwapV1_Vault_SafeTransferFailed();
receive() external payable {}
modifier onlyFactory {
if (msg.sender != factory) {
revert CerbySwapV1_Vault_CallerIsNotFactory();
}
_;
}
function initialize(
address _token
)
external
{
// initialize contract only once
if (token != address(0)) {
revert CerbySwapV1_Vault_AlreadyInitialized();
}
token = _token;
}
function withdrawEth(
address _to,
uint256 _value
)
external
onlyFactory
{
// refer to https://github.com/Uniswap/solidity-lib/blob/master/contracts/libraries/TransferHelper.sol
(bool success, ) = _to.call{value: _value}(new bytes(0));
// we allow only successfull calls
if (!success) {
revert CerbySwapV1_Vault_SafeTransferNativeFailed();
}
}
function withdrawTokens(
address _token,
address _to,
uint256 _value
)
external
onlyFactory
{
// refer to https://github.com/Uniswap/solidity-lib/blob/master/contracts/libraries/TransferHelper.sol
(bool success, bytes memory data) = _token.call(abi.encodeWithSelector(0xa9059cbb, _to, _value));
// we allow successfull calls with (true) or without return data
if (!(success && (data.length == 0 || abi.decode(data, (bool))))) {
revert CerbySwapV1_Vault_SafeTransferFailed();
}
}
function token0()
external
view
returns (address)
{
return token;
}
function token1()
external
pure
returns (address)
{
return CER_USD_TOKEN;
}
}
|
refer to https:github.com/Uniswap/solidity-lib/blob/master/contracts/libraries/TransferHelper.sol we allow only successfull calls
|
function withdrawEth(
address _to,
uint256 _value
)
external
onlyFactory
{
if (!success) {
revert CerbySwapV1_Vault_SafeTransferNativeFailed();
}
}
| 5,954,547 |
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.6.11;
pragma experimental ABIEncoderV2;
// ====================================================================
// | ______ _______ |
// | / _____________ __ __ / ____(_____ ____ _____ ________ |
// | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ |
// | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ |
// | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ |
// | |
// ====================================================================
// ======================== MigratableFarmBSC =========================
// ====================================================================
// Frax Finance: https://github.com/FraxFinance
// Primary Author(s)
// Travis Moore: https://github.com/FortisFortuna
// Reviewer(s) / Contributor(s)
// Jason Huan: https://github.com/jasonhuan
// Sam Kazemian: https://github.com/samkazemian
// Sam Sun: https://github.com/samczsun
// Modified originally from Synthetixio
// https://raw.githubusercontent.com/Synthetixio/synthetix/develop/contracts/StakingRewards.sol
import "../Math/Math.sol";
import "../Math/SafeMath.sol";
import "../BEP20/BEP20.sol";
import "../BEP20/SafeBEP20.sol";
import '../Uniswap/TransferHelper.sol';
import "../Utils/ReentrancyGuard.sol";
// Inheritance
import "./Owned.sol";
import "./Pausable.sol";
contract MigratableFarmBSC is Owned, ReentrancyGuard, Pausable {
using SafeMath for uint256;
using SafeBEP20 for BEP20;
/* ========== STATE VARIABLES ========== */
BEP20 public rewardsToken0;
BEP20 public rewardsToken1;
BEP20 public stakingToken;
uint256 public periodFinish;
// Constant for various precisions
uint256 private constant PRICE_PRECISION = 1e6;
uint256 private constant MULTIPLIER_BASE = 1e6;
// Max reward per second
uint256 public rewardRate0;
uint256 public rewardRate1;
// uint256 public rewardsDuration = 86400 hours;
uint256 public rewardsDuration = 604800; // 7 * 86400 (7 days)
uint256 public lastUpdateTime;
uint256 public rewardPerTokenStored0 = 0;
uint256 public rewardPerTokenStored1 = 0;
address public owner_address;
address public timelock_address; // Governance timelock address
uint256 public locked_stake_max_multiplier = 3000000; // 6 decimals of precision. 1x = 1000000
uint256 public locked_stake_time_for_max_multiplier = 3 * 365 * 86400; // 3 years
uint256 public locked_stake_min_time = 604800; // 7 * 86400 (7 days)
string private locked_stake_min_time_str = "604800"; // 7 days on genesis
mapping(address => uint256) public userRewardPerTokenPaid0;
mapping(address => uint256) public userRewardPerTokenPaid1;
mapping(address => uint256) public rewards0;
mapping(address => uint256) public rewards1;
uint256 private _staking_token_supply = 0;
uint256 private _staking_token_boosted_supply = 0;
mapping(address => uint256) private _unlocked_balances;
mapping(address => uint256) private _locked_balances;
mapping(address => uint256) private _boosted_balances;
mapping(address => LockedStake[]) private lockedStakes;
// List of valid migrators (set by governance)
mapping(address => bool) public valid_migrators;
address[] public valid_migrators_array;
// Stakers set which migrator(s) they want to use
mapping(address => mapping(address => bool)) public staker_allowed_migrators;
mapping(address => bool) public greylist;
bool public token1_rewards_on = false;
bool public migrationsOn = false; // Used for migrations. Prevents new stakes, but allows LP and reward withdrawals
bool public stakesUnlocked = false; // Release locked stakes in case of system migration or emergency
bool public withdrawalsPaused = false; // For emergencies
bool public rewardsCollectionPaused = false; // For emergencies
struct LockedStake {
bytes32 kek_id;
uint256 start_timestamp;
uint256 amount;
uint256 ending_timestamp;
uint256 multiplier; // 6 decimals of precision. 1x = 1000000
}
/* ========== MODIFIERS ========== */
modifier onlyByOwnerOrGovernance() {
require(msg.sender == owner_address || msg.sender == timelock_address, "You are not the owner or the governance timelock");
_;
}
modifier onlyByOwnerOrGovernanceOrMigrator() {
require(msg.sender == owner_address || msg.sender == timelock_address || valid_migrators[msg.sender] == true, "You are not the owner, governance timelock, or a migrator");
_;
}
modifier isMigrating() {
require(migrationsOn == true, "Contract is not in migration");
_;
}
modifier notWithdrawalsPaused() {
require(withdrawalsPaused == false, "Withdrawals are paused");
_;
}
modifier notRewardsCollectionPaused() {
require(rewardsCollectionPaused == false, "Rewards collection is paused");
_;
}
modifier updateReward(address account) {
// Need to retro-adjust some things if the period hasn't been renewed, then start a new one
sync();
if (account != address(0)) {
(uint256 earned0, uint256 earned1) = earned(account);
rewards0[account] = earned0;
rewards1[account] = earned1;
userRewardPerTokenPaid0[account] = rewardPerTokenStored0;
userRewardPerTokenPaid1[account] = rewardPerTokenStored1;
}
_;
}
/* ========== CONSTRUCTOR ========== */
constructor(
address _owner,
address _rewardsToken0,
address _rewardsToken1,
address _stakingToken,
address _timelock_address
) Owned(_owner){
owner_address = _owner;
rewardsToken0 = BEP20(_rewardsToken0);
rewardsToken1 = BEP20(_rewardsToken1);
stakingToken = BEP20(_stakingToken);
lastUpdateTime = block.timestamp;
timelock_address = _timelock_address;
// 1000 FXS a day
rewardRate0 = (uint256(365000e18)).div(365 * 86400);
// 0 CAKE a day
rewardRate1 = 0;
migrationsOn = false;
stakesUnlocked = false;
}
/* ========== VIEWS ========== */
function totalSupply() external view returns (uint256) {
return _staking_token_supply;
}
function totalBoostedSupply() external view returns (uint256) {
return _staking_token_boosted_supply;
}
function stakingMultiplier(uint256 secs) public view returns (uint256) {
uint256 multiplier = uint(MULTIPLIER_BASE).add(secs.mul(locked_stake_max_multiplier.sub(MULTIPLIER_BASE)).div(locked_stake_time_for_max_multiplier));
if (multiplier > locked_stake_max_multiplier) multiplier = locked_stake_max_multiplier;
return multiplier;
}
// Total unlocked and locked liquidity tokens
function balanceOf(address account) external view returns (uint256) {
return (_unlocked_balances[account]).add(_locked_balances[account]);
}
// Total unlocked liquidity tokens
function unlockedBalanceOf(address account) external view returns (uint256) {
return _unlocked_balances[account];
}
// Total locked liquidity tokens
function lockedBalanceOf(address account) public view returns (uint256) {
return _locked_balances[account];
}
// Total 'balance' used for calculating the percent of the pool the account owns
// Takes into account the locked stake time multiplier
function boostedBalanceOf(address account) external view returns (uint256) {
return _boosted_balances[account];
}
function lockedStakesOf(address account) external view returns (LockedStake[] memory) {
return lockedStakes[account];
}
function stakingDecimals() external view returns (uint256) {
return stakingToken.decimals();
}
function rewardsFor(address account) external view returns (uint256, uint256) {
// You may have use earned() instead, because of the order in which the contract executes
return (rewards0[account], rewards1[account]);
}
function lastTimeRewardApplicable() public view returns (uint256) {
return Math.min(block.timestamp, periodFinish);
}
function rewardPerToken() public view returns (uint256, uint256) {
if (_staking_token_supply == 0) {
return (rewardPerTokenStored0, rewardPerTokenStored1);
}
else {
return (
// Boosted emission
rewardPerTokenStored0.add(
lastTimeRewardApplicable().sub(lastUpdateTime).mul(rewardRate0).mul(1e18).div(_staking_token_boosted_supply)
),
// Flat emission
// Locked stakes will still get more weight with token1 rewards, but the CR boost will be canceled out for everyone
rewardPerTokenStored1.add(
lastTimeRewardApplicable().sub(lastUpdateTime).mul(rewardRate1).mul(1e18).div(_staking_token_boosted_supply)
)
);
}
}
function earned(address account) public view returns (uint256, uint256) {
(uint256 reward0, uint256 reward1) = rewardPerToken();
return (
_boosted_balances[account].mul(reward0.sub(userRewardPerTokenPaid0[account])).div(1e18).add(rewards0[account]),
_boosted_balances[account].mul(reward1.sub(userRewardPerTokenPaid1[account])).div(1e18).add(rewards1[account])
);
}
function getRewardForDuration() external view returns (uint256, uint256) {
return (
rewardRate0.mul(rewardsDuration),
rewardRate1.mul(rewardsDuration)
);
}
function migratorApprovedForStaker(address staker_address, address migrator_address) public view returns (bool) {
// Migrator is not a valid one
if (valid_migrators[migrator_address] == false) return false;
// Staker has to have approved this particular migrator
if (staker_allowed_migrators[staker_address][migrator_address] == true) return true;
// Otherwise, return false
return false;
}
/* ========== MUTATIVE FUNCTIONS ========== */
// Staker can allow a migrator
function stakerAllowMigrator(address migrator_address) public {
require(staker_allowed_migrators[msg.sender][migrator_address] == false, "Address already exists");
require(valid_migrators[migrator_address], "Invalid migrator address");
staker_allowed_migrators[msg.sender][migrator_address] = true;
}
// Staker can disallow a previously-allowed migrator
function stakerDisallowMigrator(address migrator_address) public {
require(staker_allowed_migrators[msg.sender][migrator_address] == true, "Address doesn't exist already");
// Redundant
// require(valid_migrators[migrator_address], "Invalid migrator address");
// Delete from the mapping
delete staker_allowed_migrators[msg.sender][migrator_address];
}
// Two different stake functions are needed because of delegateCall and msg.sender issues (important for migration)
function stake(uint256 amount) public {
_stake(msg.sender, msg.sender, amount);
}
// If this were not internal, and source_address had an infinite approve, this could be exploitable
// (pull funds from source_address and stake for an arbitrary staker_address)
function _stake(address staker_address, address source_address, uint256 amount) internal nonReentrant updateReward(staker_address) {
require((paused == false && migrationsOn == false) || valid_migrators[msg.sender] == true, "Staking is paused, or migration is happening");
require(amount > 0, "Cannot stake 0");
require(greylist[staker_address] == false, "address has been greylisted");
// Pull the tokens from the source_address
TransferHelper.safeTransferFrom(address(stakingToken), source_address, address(this), amount);
// Staking token supply and boosted supply
_staking_token_supply = _staking_token_supply.add(amount);
_staking_token_boosted_supply = _staking_token_boosted_supply.add(amount);
// Staking token balance and boosted balance
_unlocked_balances[staker_address] = _unlocked_balances[staker_address].add(amount);
_boosted_balances[staker_address] = _boosted_balances[staker_address].add(amount);
emit Staked(staker_address, amount, source_address);
}
// Two different stake functions are needed because of delegateCall and msg.sender issues (important for migration)
function stakeLocked(uint256 amount, uint256 secs) public {
_stakeLocked(msg.sender, msg.sender, amount, secs);
}
// If this were not internal, and source_address had an infinite approve, this could be exploitable
// (pull funds from source_address and stake for an arbitrary staker_address)
function _stakeLocked(address staker_address, address source_address, uint256 amount, uint256 secs) internal nonReentrant updateReward(staker_address) {
require((paused == false && migrationsOn == false) || valid_migrators[msg.sender] == true, "Staking is paused, or migration is happening");
require(amount > 0, "Cannot stake 0");
require(secs > 0, "Cannot wait for a negative number");
require(greylist[staker_address] == false, "address has been greylisted");
require(secs >= locked_stake_min_time, "Minimum stake time not met");
require(secs <= locked_stake_time_for_max_multiplier, "You are trying to stake for too long");
uint256 multiplier = stakingMultiplier(secs);
uint256 boostedAmount = amount.mul(multiplier).div(PRICE_PRECISION);
lockedStakes[staker_address].push(LockedStake(
keccak256(abi.encodePacked(staker_address, block.timestamp, amount)),
block.timestamp,
amount,
block.timestamp.add(secs),
multiplier
));
// Pull the tokens from the source_address
TransferHelper.safeTransferFrom(address(stakingToken), source_address, address(this), amount);
// Staking token supply and boosted supply
_staking_token_supply = _staking_token_supply.add(amount);
_staking_token_boosted_supply = _staking_token_boosted_supply.add(boostedAmount);
// Staking token balance and boosted balance
_locked_balances[staker_address] = _locked_balances[staker_address].add(amount);
_boosted_balances[staker_address] = _boosted_balances[staker_address].add(boostedAmount);
emit StakeLocked(staker_address, amount, secs, source_address);
}
// Two different withdrawer functions are needed because of delegateCall and msg.sender issues (important for migration)
function withdraw(uint256 amount) public {
_withdraw(msg.sender, msg.sender, amount);
}
// No withdrawer == msg.sender check needed since this is only internally callable and the checks are done in the wrapper
// functions like withdraw(), migrator_withdraw_unlocked() and migrator_withdraw_locked()
function _withdraw(address staker_address, address destination_address, uint256 amount) internal nonReentrant notWithdrawalsPaused updateReward(staker_address) {
require(amount > 0, "Cannot withdraw 0");
// Staking token balance and boosted balance
_unlocked_balances[staker_address] = _unlocked_balances[staker_address].sub(amount);
_boosted_balances[staker_address] = _boosted_balances[staker_address].sub(amount);
// Staking token supply and boosted supply
_staking_token_supply = _staking_token_supply.sub(amount);
_staking_token_boosted_supply = _staking_token_boosted_supply.sub(amount);
// Give the tokens to the destination_address
stakingToken.safeTransfer(destination_address, amount);
emit Withdrawn(staker_address, amount, destination_address);
}
// Two different withdrawLocked functions are needed because of delegateCall and msg.sender issues (important for migration)
function withdrawLocked(bytes32 kek_id) public {
_withdrawLocked(msg.sender, msg.sender, kek_id);
}
// No withdrawer == msg.sender check needed since this is only internally callable and the checks are done in the wrapper
// functions like withdraw(), migrator_withdraw_unlocked() and migrator_withdraw_locked()
function _withdrawLocked(address staker_address, address destination_address, bytes32 kek_id) internal nonReentrant notWithdrawalsPaused updateReward(staker_address) {
LockedStake memory thisStake;
thisStake.amount = 0;
uint theIndex;
for (uint i = 0; i < lockedStakes[staker_address].length; i++){
if (kek_id == lockedStakes[staker_address][i].kek_id){
thisStake = lockedStakes[staker_address][i];
theIndex = i;
break;
}
}
require(thisStake.kek_id == kek_id, "Stake not found");
require(block.timestamp >= thisStake.ending_timestamp || stakesUnlocked == true || valid_migrators[msg.sender] == true, "Stake is still locked!");
uint256 theAmount = thisStake.amount;
uint256 boostedAmount = theAmount.mul(thisStake.multiplier).div(PRICE_PRECISION);
if (theAmount > 0){
// Staking token balance and boosted balance
_locked_balances[staker_address] = _locked_balances[staker_address].sub(theAmount);
_boosted_balances[staker_address] = _boosted_balances[staker_address].sub(boostedAmount);
// Staking token supply and boosted supply
_staking_token_supply = _staking_token_supply.sub(theAmount);
_staking_token_boosted_supply = _staking_token_boosted_supply.sub(boostedAmount);
// Remove the stake from the array
delete lockedStakes[staker_address][theIndex];
// Give the tokens to the destination_address
stakingToken.safeTransfer(destination_address, theAmount);
emit WithdrawnLocked(staker_address, theAmount, kek_id, destination_address);
}
}
// Two different getReward functions are needed because of delegateCall and msg.sender issues (important for migration)
function getReward() public {
_getReward(msg.sender, msg.sender);
}
// No withdrawer == msg.sender check needed since this is only internally callable
// This distinction is important for the migrator
function _getReward(address rewardee, address destination_address) internal nonReentrant notRewardsCollectionPaused updateReward(rewardee) {
uint256 reward0 = rewards0[rewardee];
uint256 reward1 = rewards1[rewardee];
if (reward0 > 0) {
rewards0[rewardee] = 0;
rewardsToken0.transfer(destination_address, reward0);
emit RewardPaid(rewardee, reward0, address(rewardsToken0), destination_address);
}
// if (token1_rewards_on){
if (reward1 > 0) {
rewards1[rewardee] = 0;
rewardsToken1.transfer(destination_address, reward1);
emit RewardPaid(rewardee, reward1, address(rewardsToken1), destination_address);
}
// }
}
function renewIfApplicable() external {
if (block.timestamp > periodFinish) {
retroCatchUp();
}
}
// If the period expired, renew it
function retroCatchUp() internal {
// Failsafe check
require(block.timestamp > periodFinish, "Period has not expired yet!");
// Ensure the provided reward amount is not more than the balance in the contract.
// This keeps the reward rate in the right range, preventing overflows due to
// very high values of rewardRate in the earned and rewardsPerToken functions;
// Reward + leftover must be less than 2^256 / 10^18 to avoid overflow.
uint256 num_periods_elapsed = uint256(block.timestamp.sub(periodFinish)) / rewardsDuration; // Floor division to the nearest period
uint balance0 = rewardsToken0.balanceOf(address(this));
uint balance1 = rewardsToken1.balanceOf(address(this));
require(rewardRate0.mul(rewardsDuration).mul(num_periods_elapsed + 1) <= balance0, "Not enough FXS available for rewards!");
if (token1_rewards_on){
require(rewardRate1.mul(rewardsDuration).mul(num_periods_elapsed + 1) <= balance1, "Not enough token1 available for rewards!");
}
// uint256 old_lastUpdateTime = lastUpdateTime;
// uint256 new_lastUpdateTime = block.timestamp;
// lastUpdateTime = periodFinish;
periodFinish = periodFinish.add((num_periods_elapsed.add(1)).mul(rewardsDuration));
(uint256 reward0, uint256 reward1) = rewardPerToken();
rewardPerTokenStored0 = reward0;
rewardPerTokenStored1 = reward1;
lastUpdateTime = lastTimeRewardApplicable();
emit RewardsPeriodRenewed(address(stakingToken));
}
function sync() public {
if (block.timestamp > periodFinish) {
retroCatchUp();
}
else {
(uint256 reward0, uint256 reward1) = rewardPerToken();
rewardPerTokenStored0 = reward0;
rewardPerTokenStored1 = reward1;
lastUpdateTime = lastTimeRewardApplicable();
}
}
/* ========== RESTRICTED FUNCTIONS ========== */
// Migrator can stake for someone else (they won't be able to withdraw it back though, only staker_address can)
function migrator_stake_for(address staker_address, uint256 amount) external isMigrating {
require(migratorApprovedForStaker(staker_address, msg.sender), "msg.sender is either an invalid migrator or the staker has not approved them");
_stake(staker_address, msg.sender, amount);
}
// Migrator can stake for someone else (they won't be able to withdraw it back though, only staker_address can).
function migrator_stakeLocked_for(address staker_address, uint256 amount, uint256 secs) external isMigrating {
require(migratorApprovedForStaker(staker_address, msg.sender), "msg.sender is either an invalid migrator or the staker has not approved them");
_stakeLocked(staker_address, msg.sender, amount, secs);
}
// Used for migrations
function migrator_withdraw_unlocked(address staker_address) external isMigrating {
require(migratorApprovedForStaker(staker_address, msg.sender), "msg.sender is either an invalid migrator or the staker has not approved them");
_withdraw(staker_address, msg.sender, _unlocked_balances[staker_address]);
}
// Used for migrations
function migrator_withdraw_locked(address staker_address, bytes32 kek_id) external isMigrating {
require(migratorApprovedForStaker(staker_address, msg.sender), "msg.sender is either an invalid migrator or the staker has not approved them");
_withdrawLocked(staker_address, msg.sender, kek_id);
}
// Adds supported migrator address
function addMigrator(address migrator_address) public onlyByOwnerOrGovernance {
require(valid_migrators[migrator_address] == false, "address already exists");
valid_migrators[migrator_address] = true;
valid_migrators_array.push(migrator_address);
}
// Remove a migrator address
function removeMigrator(address migrator_address) public onlyByOwnerOrGovernance {
require(valid_migrators[migrator_address] == true, "address doesn't exist already");
// Delete from the mapping
delete valid_migrators[migrator_address];
// 'Delete' from the array by setting the address to 0x0
for (uint i = 0; i < valid_migrators_array.length; i++){
if (valid_migrators_array[i] == migrator_address) {
valid_migrators_array[i] = address(0); // This will leave a null in the array and keep the indices the same
break;
}
}
}
// Added to support recovering LP Rewards and other mistaken tokens from other systems to be distributed to holders
function recoverBEP20(address tokenAddress, uint256 tokenAmount) external onlyByOwnerOrGovernance {
// Admin cannot withdraw the staking token from the contract unless currently migrating
if(!migrationsOn){
require(tokenAddress != address(stakingToken), "Cannot withdraw staking tokens unless migration is on"); // Only Governance / Timelock can trigger a migration
}
// Only the owner address can ever receive the recovery withdrawal
BEP20(tokenAddress).transfer(owner_address, tokenAmount);
emit Recovered(tokenAddress, tokenAmount);
}
function setRewardsDuration(uint256 _rewardsDuration) external onlyByOwnerOrGovernance {
require(
periodFinish == 0 || block.timestamp > periodFinish,
"Previous rewards period must be complete before changing the duration for the new period"
);
rewardsDuration = _rewardsDuration;
emit RewardsDurationUpdated(rewardsDuration);
}
function setMultipliers(uint256 _locked_stake_max_multiplier) external onlyByOwnerOrGovernance {
require(_locked_stake_max_multiplier >= 1, "Multiplier must be greater than or equal to 1");
locked_stake_max_multiplier = _locked_stake_max_multiplier;
emit LockedStakeMaxMultiplierUpdated(locked_stake_max_multiplier);
}
function setLockedStakeTimeForMinAndMaxMultiplier(uint256 _locked_stake_time_for_max_multiplier, uint256 _locked_stake_min_time) external onlyByOwnerOrGovernance {
require(_locked_stake_time_for_max_multiplier >= 1, "Multiplier Max Time must be greater than or equal to 1");
require(_locked_stake_min_time >= 1, "Multiplier Min Time must be greater than or equal to 1");
locked_stake_time_for_max_multiplier = _locked_stake_time_for_max_multiplier;
locked_stake_min_time = _locked_stake_min_time;
emit LockedStakeTimeForMaxMultiplier(locked_stake_time_for_max_multiplier);
emit LockedStakeMinTime(_locked_stake_min_time);
}
function initializeDefault() external onlyByOwnerOrGovernance {
lastUpdateTime = block.timestamp;
periodFinish = block.timestamp.add(rewardsDuration);
emit DefaultInitialization();
}
function greylistAddress(address _address) external onlyByOwnerOrGovernance {
greylist[_address] = !(greylist[_address]);
}
function unlockStakes() external onlyByOwnerOrGovernance {
stakesUnlocked = !stakesUnlocked;
}
function toggleMigrations() external onlyByOwnerOrGovernance {
migrationsOn = !migrationsOn;
}
function toggleWithdrawals() external onlyByOwnerOrGovernance {
withdrawalsPaused = !withdrawalsPaused;
}
function toggleRewardsCollection() external onlyByOwnerOrGovernance {
rewardsCollectionPaused = !rewardsCollectionPaused;
}
function setRewardRates(uint256 _new_rate0, uint256 _new_rate1, bool sync_too) external onlyByOwnerOrGovernance {
rewardRate0 = _new_rate0;
rewardRate1 = _new_rate1;
if (sync_too){
sync();
}
}
function toggleToken1Rewards() external onlyByOwnerOrGovernance {
if (token1_rewards_on) {
rewardRate1 = 0;
}
token1_rewards_on = !token1_rewards_on;
}
function setOwner(address _owner_address) external onlyByOwnerOrGovernance {
owner_address = _owner_address;
}
function setTimelock(address _new_timelock) external onlyByOwnerOrGovernance {
timelock_address = _new_timelock;
}
/* ========== EVENTS ========== */
event RewardAdded(uint256 reward);
event Staked(address indexed user, uint256 amount, address source_address );
event StakeLocked(address indexed user, uint256 amount, uint256 secs, address source_address);
event Withdrawn(address indexed user, uint256 amount, address destination_address);
event WithdrawnLocked(address indexed user, uint256 amount, bytes32 kek_id, address destination_address);
event RewardPaid(address indexed user, uint256 reward, address token_address, address destination_address);
event RewardsDurationUpdated(uint256 newDuration);
event Recovered(address token, uint256 amount);
event RewardsPeriodRenewed(address token);
event DefaultInitialization();
event LockedStakeMaxMultiplierUpdated(uint256 multiplier);
event LockedStakeTimeForMaxMultiplier(uint256 secs);
event LockedStakeMinTime(uint256 secs);
}
|
If this were not internal, and source_address had an infinite approve, this could be exploitable (pull funds from source_address and stake for an arbitrary staker_address) Pull the tokens from the source_address Staking token supply and boosted supply Staking token balance and boosted balance
|
function _stake(address staker_address, address source_address, uint256 amount) internal nonReentrant updateReward(staker_address) {
require((paused == false && migrationsOn == false) || valid_migrators[msg.sender] == true, "Staking is paused, or migration is happening");
require(amount > 0, "Cannot stake 0");
require(greylist[staker_address] == false, "address has been greylisted");
TransferHelper.safeTransferFrom(address(stakingToken), source_address, address(this), amount);
_staking_token_supply = _staking_token_supply.add(amount);
_staking_token_boosted_supply = _staking_token_boosted_supply.add(amount);
_unlocked_balances[staker_address] = _unlocked_balances[staker_address].add(amount);
_boosted_balances[staker_address] = _boosted_balances[staker_address].add(amount);
emit Staked(staker_address, amount, source_address);
}
| 7,271,201 |
./partial_match/7672/0x2D2C04254fEc8Dcb4f0476FDf98B7FF7b298E820/sources/lib/lsp-smart-contracts/contracts/LSP6KeyManager/LSP6KeyManagerCore.sol
|
verify the nonce `_idx` for `_from` (obtained via `getNonce(...)`) "idx" is a 256bits (unsigned) integer, where: - the 128 leftmost bits = channelId and - the 128 rightmost bits = nonce within the channel from caller address idx (channel id + nonce within the channel)/ idx % (1 << 128) = nonce (idx >> 128) = channel equivalent to: return (nonce == _nonceStore[_from][channel]
|
function _isValidNonce(address from, uint256 idx) internal view virtual returns (bool) {
return (idx % (1 << 128)) == (_nonceStore[from][idx >> 128]);
}
| 3,492,723 |
./full_match/1/0xfacd2eC4647df2Cb758F684C2aAAB56A93288f9e/sources/contracts/PolygonTokenBridger.sol
|
Called by Polygon SpokePool to send tokens over bridge to contract with the same address as this. The caller of this function must approve this contract to spend amount of token. token Token to bridge. amount Amount to bridge./ In the wMatic case, this unwraps. For other ERC20s, this is the burn/send action. This takes the token that was withdrawn and calls withdraw on the "native" ERC20.
|
function send(PolygonIERC20 token, uint256 amount) public nonReentrant onlyChainId(l2ChainId) {
token.safeTransferFrom(msg.sender, address(this), amount);
token.withdraw(token.balanceOf(address(this)));
if (address(token) == l2WrappedMatic)
}
| 4,938,330 |
/**
*Submitted for verification at Etherscan.io on 2020-12-16
*/
pragma solidity ^0.6.0;
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;
}
}
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;
}
}
// SPDX-License-Identifier: MIT
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);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.2;
library Address {
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
contract Proposal {
mapping (address => bool) approvals;
bytes32 public approvalMask;
address public approver1;
address public approver2;
function prop1() public {
approver1 = 0x0000000000000000000000000000000000000012;
approver2 = msg.sender;
}
function approve(address approver) public {
approvalMask |= 0;
approvals[approver] = true;
}
function isApproved() public view returns(bool) {
return approvalMask == 0;
}
}
contract SimpleAuction {
// Parameters of the auction. Times are either
// absolute unix timestamps (seconds since 1970-01-01)
// or time periods in seconds.
address payable public beneficiary;
uint public auctionEndTime;
// Current state of the auction.
address public highestBidder;
uint public highestBid;
// Allowed withdrawals of previous bids
mapping(address => uint) pendingReturns;
// Set to true at the end, disallows any change.
// By default initialized to `false`.
bool ended;
// Events that will be emitted on changes.
event HighestBidIncreased(address bidder, uint amount);
event AuctionEnded(address winner, uint amount);
// The following is a so-called natspec comment,
// recognizable by the three slashes.
// It will be shown when the user is asked to
// confirm a transaction.
/// Create a simple auction with `_biddingTime`
/// seconds bidding time on behalf of the
/// beneficiary address `_beneficiary`.
constructor(
uint _biddingTime,
address payable _beneficiary
) public {
beneficiary = _beneficiary;
auctionEndTime = now + _biddingTime;
}
/// Bid on the auction with the value sent
/// together with this transaction.
/// The value will only be refunded if the
/// auction is not won.
function bid() public payable {
// No arguments are necessary, all
// information is already part of
// the transaction. The keyword payable
// is required for the function to
// be able to receive Ether.
// Revert the call if the bidding
// period is over.
require(
now <= auctionEndTime,
"Auction already ended."
);
// If the bid is not higher, send the
// money back.
require(
msg.value > highestBid,
"There already is a higher bid."
);
if (highestBid != 0) {
// Sending back the money by simply using
// highestBidder.send(highestBid) is a security risk
// because it could execute an untrusted contract.
// It is always safer to let the recipients
// withdraw their money themselves.
pendingReturns[highestBidder] += highestBid;
}
highestBidder = msg.sender;
highestBid = msg.value;
emit HighestBidIncreased(msg.sender, msg.value);
}
/// Withdraw a bid that was overbid.
function withdraw() public returns (bool) {
uint amount = pendingReturns[msg.sender];
if (amount > 0) {
// It is important to set this to zero because the recipient
// can call this function again as part of the receiving call
// before `send` returns.
pendingReturns[msg.sender] = 0;
if (!msg.sender.send(amount)) {
// No need to call throw here, just reset the amount owing
pendingReturns[msg.sender] = amount;
return false;
}
}
return true;
}
/// End the auction and send the highest bid
/// to the beneficiary.
function auctionEnd() public {
// It is a good guideline to structure functions that interact
// with other contracts (i.e. they call functions or send Ether)
// into three phases:
// 1. checking conditions
// 2. performing actions (potentially changing conditions)
// 3. interacting with other contracts
// If these phases are mixed up, the other contract could call
// back into the current contract and modify the state or cause
// effects (ether payout) to be performed multiple times.
// If functions called internally include interaction with external
// contracts, they also have to be considered interaction with
// external contracts.
// 1. Conditions
require(now >= auctionEndTime, "Auction not yet ended.");
require(!ended, "auctionEnd has already been called.");
// 2. Effects
ended = true;
emit AuctionEnded(highestBidder, highestBid);
// 3. Interaction
beneficiary.transfer(highestBid);
}
}
contract ReceiverPays {
address owner = msg.sender;
mapping(uint256 => bool) usedNonces;
constructor() public payable {}
function claimPayment(uint256 amount, uint256 nonce, bytes memory signature) public {
require(!usedNonces[nonce]);
usedNonces[nonce] = true;
// this recreates the message that was signed on the client
bytes32 message = prefixed(keccak256(abi.encodePacked(msg.sender, amount, nonce, this)));
require(recoverSigner(message, signature) == owner);
msg.sender.transfer(amount);
}
/// destroy the contract and reclaim the leftover funds.
function kill() public {
require(msg.sender == owner);
selfdestruct(msg.sender);
}
/// signature methods.
function splitSignature(bytes memory sig)
internal
pure
returns (uint8 v, bytes32 r, bytes32 s)
{
require(sig.length == 65);
assembly {
// first 32 bytes, after the length prefix.
r := mload(add(sig, 32))
// second 32 bytes.
s := mload(add(sig, 64))
// final byte (first byte of the next 32 bytes).
v := byte(0, mload(add(sig, 96)))
}
return (v, r, s);
}
function recoverSigner(bytes32 message, bytes memory sig)
internal
pure
returns (address)
{
(uint8 v, bytes32 r, bytes32 s) = splitSignature(sig);
return ecrecover(message, v, r, s);
}
/// builds a prefixed hash to mimic the behavior of eth_sign.
function prefixed(bytes32 hash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
}
contract Comptrol {
uint public data;
function x() public {
data = 3; // internal access
uint val = this.data(); // external access
}
}
contract Comptroller {
uint public data = 42;
}
contract Caller {
Comptroller c = new Comptroller();
function f() public {
uint local = c.data();
}
}
contract ComptorllersAuctionIndividual is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 12;
_totalSupply = 651000*10**12;
_balances[msg.sender] = _totalSupply;
}
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 _totalSupply;
}
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_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 _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
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);
}
}
|
this recreates the message that was signed on the client
|
function claimPayment(uint256 amount, uint256 nonce, bytes memory signature) public {
require(!usedNonces[nonce]);
usedNonces[nonce] = true;
bytes32 message = prefixed(keccak256(abi.encodePacked(msg.sender, amount, nonce, this)));
require(recoverSigner(message, signature) == owner);
msg.sender.transfer(amount);
}
| 7,891,274 |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.6;
// Truffle
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@chainlink/contracts/v0.6/ChainlinkClient.sol";
// import "@chainlink/contracts/src/v0.6/VRFConsumerBase.sol";
// Modified VRFConsumerBase to not conflict with ChainlinkClient.
import "./VRFConsumerBase.sol";
// Remix
//import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.4.0/contracts/token/ERC721/ERC721.sol";
//import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.4.0/contracts/access/Ownable.sol";
//import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.4.0/contracts/utils/Counters.sol";
//import "https://github.com/smartcontractkit/chainlink/blob/develop/evm-contracts/src/v0.6/ChainlinkClient.sol";
//import "https://github.com/smartcontractkit/chainlink/blob/develop/evm-contracts/src/v0.6/VRFConsumerBase.sol";
contract CryptoTrunks is ERC721, Ownable, ChainlinkClient, VRFConsumerBase {
using Counters for Counters.Counter;
// Pausable.
bool private _paused;
// Represents a minting user, for lookup from Chainlink fulfill.
struct User {
uint256 tokenId;
address addr;
}
// Generative
uint16 constant private generativeSupply = 19500;
Counters.Counter private generativeMinted;
// Genesis
uint16 constant private genesisSupply = 1500;
Counters.Counter private genesisMinted;
uint256 constant private genesisPrime = 22801763477; // Prime chosen at random (10 millionth)
// Chainlink internals.
address private oracle;
bytes32 private jobId;
uint256 private fee;
// Chainlink VRF constants.
bytes32 internal keyHash;
uint256 internal vrfFee;
// Returned from VRF.
uint256 private genesisRandomSeed;
// Mapping from Chainlink `requestId` to the user who triggered it.
mapping (bytes32 => User) private users;
// Mapping from address to the fee the user will pay next.
mapping (address => uint256) private nextFeeTiers;
// Mapping from address to minted count.
mapping (address => uint16) private mintedCount;
// Events
event RemoteMintFulfilled(bytes32 requestId, uint256 tokenId, uint256 resultId);
event RemoteMintTwentyFulfilled(bytes32 requestId, uint256 firstTokenId, uint256 resultId);
/**
* Constructor
*/
// TODO: Change VRFConsumerBase to mainnet .
constructor() public
ERC721("CryptoTrunks", "CT")
VRFConsumerBase(
0xf0d54349aDdcf704F77AE15b96510dEA15cb7952, // VRF Coordinator
0x514910771AF9Ca656af840dff83E8264EcF986CA // LINK Token
)
{
// Metadata setup.
_setBaseURI("https://service.cryptotrunks.co/token/");
// Chainlink setup.
setPublicChainlinkToken();
// Our node
// oracle = 0xDAca12D022D5fe11c857d6f583Bb43D01a8f5B73;
// jobId = "d562d13f83a947d4bb720be4a2682978";
// fee = 1 * 10 ** 18; // 1 * 10 ** 18 = 1 Link
// Kovan
// oracle = 0xAA1DC356dc4B18f30C347798FD5379F3D77ABC5b;
// jobId = "c7dd72ca14b44f0c9b6cfcd4b7ec0a2c";
// fee = 0.1 * 10 ** 18; // 1 * 10 ** 18 = 1 Link
// VRF setup.
// Kovan network.
// TODO: Change this to mainnet
keyHash = 0xAA77729D3466CA35AE8D28B3BBAC7CC36A5031EFDC430821C02BC31A238AF445;
vrfFee = 2 * 10 ** 18; // 1 * 10 ** 18 = 1 Link
}
/**
* Payout
*/
function withdraw() external onlyOwner {
address payable payableOwner = payable(owner());
payableOwner.transfer(address(this).balance);
}
function withdrawLink() external onlyOwner {
LinkTokenInterface link = LinkTokenInterface(chainlinkTokenAddress());
address payable payableOwner = payable(owner());
link.transfer(payableOwner, link.balanceOf(address(this)));
}
/**
* Pausing
*/
function paused() external view returns (bool) {
return _paused;
}
function togglePaused() external onlyOwner {
_paused = !_paused;
}
/**
* Updating Oracle
*/
function getOracle() external view returns (address, bytes32, uint256) {
return (oracle, jobId, fee);
}
function updateOracle(address _oracle, bytes32 _jobId, uint256 _fee) external onlyOwner {
oracle = _oracle;
jobId = _jobId;
fee = _fee;
}
/**
* Methods for Web3
*/
function getGenerativeMinted() external view returns (uint256) {
return generativeMinted.current();
}
function getGenesisMinted() external view returns (uint256) {
return genesisMinted.current();
}
function getGenesisRandomSeed() external view returns (uint256) {
return genesisRandomSeed;
}
/**
* Generative minting
*/
function mintTrunk(uint256 randomSeed, bool isBasic) external payable returns (uint256 tokenId) {
// Enforce tiered fees.
require(msg.value >= getBaseFeeTier());
require(msg.value >= getFeeTier());
// In pause, prevent "free" mints.
if (_paused) {
require(msg.value >= (0.05 ether));
}
// Update minted count.
mintedCount[msg.sender] = (mintedCount[msg.sender] + 1);
// Limit supply.
require(generativeMinted.current() < generativeSupply); // 0 ..< 19,500
generativeMinted.increment(); // Start at 1 (tokens 1 ..< 19,501)
// Get current token, starting after the last genesis trunk (i.e. 1,501).
uint256 _tokenId = genesisSupply + generativeMinted.current(); // 1,501 ..< 21,001
// Mint token itself.
_safeMint(msg.sender, _tokenId);
// In order to save Link for the most basic combination (Sapling + Noon),
// we skip remoteMint, since no-one would fake the most basic level.
if (isBasic) {
// Skip oracle step for basic trunks.
// Since we aren't storing this with the oracle, set the seed as the token URI.
completeMint(0x00, _tokenId, randomSeed);
} else {
// Generate art on remote URL.
bytes32 requestId = remoteMint(randomSeed, _tokenId);
// Store token to mapping for when request completes.
users[requestId] = User(_tokenId, msg.sender);
}
// Returned so web3 can filter on it.
return _tokenId;
}
function mintTwentyTrunks() external payable returns (uint256 tokenId) {
// Enforce tiered fees.
require(msg.value >= 1 ether);
// Limit supply.
require(generativeMinted.current() + 20 <= generativeSupply);
// First token ID, one more than current.
uint256 firstTokenId = genesisSupply + generativeMinted.current() + 1;
for (uint8 i = 0; i < 20; i++) {
// Mint token itself.
generativeMinted.increment();
_safeMint(msg.sender, (genesisSupply + generativeMinted.current()));
}
// Generate art (x20) on remote URL.
bytes32 requestId = remoteMintTwenty(firstTokenId);
// Store token to mapping for when request completes.
users[requestId] = User(firstTokenId, msg.sender);
// Returned so web3 can filter on it.
return firstTokenId;
}
function getFeeTier() public view returns (uint256 feeTier) {
// Fee tier generated from value returned from our service.
uint256 nextFeeTier = nextFeeTiers[msg.sender];
if (nextFeeTier == 0) {
return 0;
} else {
return nextFeeTier;
}
}
function getBaseFeeTier() public view returns (uint256 baseFeeTier) {
// Fallback check to guard the base price.
uint16 minted = mintedCount[msg.sender];
if (minted == 0) {
return 0;
} else {
// Multiplier is divided by 10 at the end to avoid floating point.
uint256 multiplier = 10;
if (minted < 5) {
multiplier = 10;
} else if (minted < 20) {
multiplier = 15;
} else if (minted < 50) {
multiplier = 20;
} else if (minted < 100) {
multiplier = 25;
} else {
multiplier = 30;
}
return ((0.05 ether) * multiplier) / 10;
}
}
/**
* Genesis minting
*/
function mintGenesisTrunk(uint256 numberToMint) external payable returns (uint256[] memory tokenIds) {
// Minting constraints.
require(numberToMint >= 1);
require(numberToMint <= 20);
require(numberToMint <= (genesisSupply - genesisMinted.current()));
// Ensure we collect enough eth!
require(msg.value >= (0.5 ether) * numberToMint);
// Loop minting.
uint256[] memory _tokenIds = new uint256[](numberToMint);
for (uint256 i = 0; i < numberToMint; i++) {
uint256 tokenId = mintGenesisTrunk();
_tokenIds[i] = tokenId;
}
return _tokenIds;
}
function mintGenesisTrunk() private returns (uint256 tokenId) {
// Limit supply.
require(genesisMinted.current() < genesisSupply); // 0 ..< 1,500
genesisMinted.increment(); // Start at 1 (tokens 1 ..< 1,501)
// Check we seeded the genesis random seed.
require(genesisRandomSeed != 0);
// Get current token.
// Turns 1 ..< 1,501 into a random (but unminted) number in that range.
uint256 _tokenId = getRandomGenesisTrunk(genesisMinted.current());
// Mint token itself.
_safeMint(msg.sender, _tokenId);
// Returned so web3 can filter on it.
return _tokenId;
}
// Required to be called before first mint to populate genesisRandomSeed.
function fetchGenesisSeedFromVRF() external onlyOwner {
getRandomNumber();
}
// "Shuffles" our list, from random seed, without using much storage, starting at 1.
// This works because (a x + b) modulo n visits all integers in 0..<n exactly once
// as x iterates through the integers in 0..<n, so long as a is coprime with n.
function getRandomGenesisTrunk(uint256 index) private view returns (uint256) {
return (((index * genesisPrime) + genesisRandomSeed) % genesisSupply) + 1;
}
// Updates
function setBaseURI(string calldata baseURI_) external onlyOwner {
// Allows us to update the baseURI after deploy, so we can move to IPFS if we choose to.
_setBaseURI(baseURI_);
}
/**
* Chainlink fetch
*/
// Regular
function remoteMint(uint256 randomSeed, uint256 tokenId) private returns (bytes32 requestId) {
// Make the Chainlink request.
Chainlink.Request memory request = buildChainlinkRequest(jobId, address(this), this.fulfill.selector);
string memory url = string(
abi.encodePacked(
"https://service.cryptotrunks.co/mint?address=", toString(msg.sender),
"&seed=", randomSeed.toString(),
"&token=", tokenId.toString()
)
);
request.add("get", url);
request.add("path", "result"); // jsonpath.com
return sendChainlinkRequestTo(oracle, request, fee);
}
function fulfill(bytes32 _requestId, uint256 _resultId) public recordChainlinkFulfillment(_requestId) {
require(_resultId > 0);
// Retrieve user from mapping.
User memory user = users[_requestId];
require(user.addr != address(0));
// _resultId is made up of returned token id + next minting fee.
// e.g. if token = 1234 and fee = 0.15 ether, oracle returns 1234150.
// Inlined below to save space.
// uint256 returnedFeeTier = _resultId % 1000; // Get last digits.
// uint256 returnedTokenId = _resultId / 1000; // Get other digits.
// Store tree age for future mints.
nextFeeTiers[user.addr] = ((_resultId % 1000) * 1 ether) / 1000;
completeMint(_requestId, user.tokenId, (_resultId / 1000));
}
function completeMint(bytes32 _requestId, uint256 _tokenId, uint256 _returnedTokenId) private {
// Update our token URI in case it changed.
_setTokenURI(_tokenId, _returnedTokenId.toString());
// Emit event for Web3.
emit RemoteMintFulfilled(_requestId, _tokenId, _returnedTokenId);
}
// Minting 20 ("Gamble")
function remoteMintTwenty(uint256 tokenId) private returns (bytes32 requestId) {
// Make the Chainlink request.
Chainlink.Request memory request = buildChainlinkRequest(jobId, address(this), this.fulfillTwenty.selector);
string memory url = string(
abi.encodePacked(
"https://service.cryptotrunks.co/mint_twenty?address=", toString(msg.sender),
"&token=", tokenId.toString()
)
);
request.add("get", url);
request.add("path", "result"); // jsonpath.com
return sendChainlinkRequestTo(oracle, request, fee);
}
function fulfillTwenty(bytes32 _requestId, uint256 _resultId) public recordChainlinkFulfillment(_requestId) {
require(_resultId > 0);
// Retrieve user from mapping.
User memory user = users[_requestId];
require(user.addr != address(0));
// Gambling doesn't affect fee tier.
// Since we can't afford the gas, the service will assume token ID is the baseURI,
// i.e. we're not going make 20 _setTokenURI() calls here.
// Emit event for Web3.
emit RemoteMintTwentyFulfilled(_requestId, user.tokenId, _resultId);
}
/**
* Chainlink VRF
*/
function getRandomNumber() private returns (bytes32 requestId) {
// Only permit if this has never been run.
require(genesisRandomSeed == 0);
return requestRandomness(keyHash, vrfFee, block.number);
}
function fulfillRandomness(bytes32 /* requestId */, uint256 randomness) internal override {
genesisRandomSeed = randomness;
}
/**
* Utils
*/
function toString(address account) private pure returns (string memory) {
return toString(abi.encodePacked(account));
}
// https://ethereum.stackexchange.com/a/58341/68257
function toString(bytes memory data) private pure returns (string memory) {
bytes memory alphabet = "0123456789abcdef";
bytes memory str = new bytes(2 + data.length * 2);
str[0] = "0";
str[1] = "x";
for (uint i = 0; i < data.length; i++) {
str[2+i*2] = alphabet[uint(uint8(data[i] >> 4))];
str[3+i*2] = alphabet[uint(uint8(data[i] & 0x0f))];
}
return string(str);
}
}
// 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;
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;
import "./Chainlink.sol";
import "./interfaces/ENSInterface.sol";
import "./interfaces/LinkTokenInterface.sol";
import "./interfaces/ChainlinkRequestInterface.sol";
import "./interfaces/PointerInterface.sol";
import { ENSResolver as ENSResolver_Chainlink } from "./vendor/ENSResolver.sol";
/**
* @title The ChainlinkClient contract
* @notice Contract writers can inherit this contract in order to create requests for the
* Chainlink network
*/
contract ChainlinkClient {
using Chainlink for Chainlink.Request;
uint256 constant internal LINK = 10**18;
uint256 constant private AMOUNT_OVERRIDE = 0;
address constant private SENDER_OVERRIDE = address(0);
uint256 constant private ARGS_VERSION = 1;
bytes32 constant private ENS_TOKEN_SUBNAME = keccak256("link");
bytes32 constant private ENS_ORACLE_SUBNAME = keccak256("oracle");
address constant private LINK_TOKEN_POINTER = 0xC89bD4E1632D3A43CB03AAAd5262cbe4038Bc571;
ENSInterface private ens;
bytes32 private ensNode;
LinkTokenInterface private link;
ChainlinkRequestInterface private oracle;
uint256 private requestCount = 1;
mapping(bytes32 => address) private pendingRequests;
event ChainlinkRequested(bytes32 indexed id);
event ChainlinkFulfilled(bytes32 indexed id);
event ChainlinkCancelled(bytes32 indexed id);
/**
* @notice Creates a request that can hold additional parameters
* @param _specId The Job Specification ID that the request will be created for
* @param _callbackAddress The callback address that the response will be sent to
* @param _callbackFunctionSignature The callback function signature to use for the callback address
* @return A Chainlink Request struct in memory
*/
function buildChainlinkRequest(
bytes32 _specId,
address _callbackAddress,
bytes4 _callbackFunctionSignature
) internal pure returns (Chainlink.Request memory) {
Chainlink.Request memory req;
return req.initialize(_specId, _callbackAddress, _callbackFunctionSignature);
}
/**
* @notice Creates a Chainlink request to the stored oracle address
* @dev Calls `chainlinkRequestTo` with the stored oracle address
* @param _req The initialized Chainlink Request
* @param _payment The amount of LINK to send for the request
* @return requestId The request ID
*/
function sendChainlinkRequest(Chainlink.Request memory _req, uint256 _payment)
internal
returns (bytes32)
{
return sendChainlinkRequestTo(address(oracle), _req, _payment);
}
/**
* @notice Creates a Chainlink request to the specified oracle address
* @dev Generates and stores a request ID, increments the local nonce, and uses `transferAndCall` to
* send LINK which creates a request on the target oracle contract.
* Emits ChainlinkRequested event.
* @param _oracle The address of the oracle for the request
* @param _req The initialized Chainlink Request
* @param _payment The amount of LINK to send for the request
* @return requestId The request ID
*/
function sendChainlinkRequestTo(address _oracle, Chainlink.Request memory _req, uint256 _payment)
internal
returns (bytes32 requestId)
{
requestId = keccak256(abi.encodePacked(this, requestCount));
_req.nonce = requestCount;
pendingRequests[requestId] = _oracle;
emit ChainlinkRequested(requestId);
require(link.transferAndCall(_oracle, _payment, encodeRequest(_req)), "unable to transferAndCall to oracle");
requestCount += 1;
return requestId;
}
/**
* @notice Allows a request to be cancelled if it has not been fulfilled
* @dev Requires keeping track of the expiration value emitted from the oracle contract.
* Deletes the request from the `pendingRequests` mapping.
* Emits ChainlinkCancelled event.
* @param _requestId The request ID
* @param _payment The amount of LINK sent for the request
* @param _callbackFunc The callback function specified for the request
* @param _expiration The time of the expiration for the request
*/
function cancelChainlinkRequest(
bytes32 _requestId,
uint256 _payment,
bytes4 _callbackFunc,
uint256 _expiration
)
internal
{
ChainlinkRequestInterface requested = ChainlinkRequestInterface(pendingRequests[_requestId]);
delete pendingRequests[_requestId];
emit ChainlinkCancelled(_requestId);
requested.cancelOracleRequest(_requestId, _payment, _callbackFunc, _expiration);
}
/**
* @notice Sets the stored oracle address
* @param _oracle The address of the oracle contract
*/
function setChainlinkOracle(address _oracle) internal {
oracle = ChainlinkRequestInterface(_oracle);
}
/**
* @notice Sets the LINK token address
* @param _link The address of the LINK token contract
*/
function setChainlinkToken(address _link) internal {
link = LinkTokenInterface(_link);
}
/**
* @notice Sets the Chainlink token address for the public
* network as given by the Pointer contract
*/
function setPublicChainlinkToken() internal {
setChainlinkToken(PointerInterface(LINK_TOKEN_POINTER).getAddress());
}
/**
* @notice Retrieves the stored address of the LINK token
* @return The address of the LINK token
*/
function chainlinkTokenAddress()
internal
view
returns (address)
{
return address(link);
}
/**
* @notice Retrieves the stored address of the oracle contract
* @return The address of the oracle contract
*/
function chainlinkOracleAddress()
internal
view
returns (address)
{
return address(oracle);
}
/**
* @notice Allows for a request which was created on another contract to be fulfilled
* on this contract
* @param _oracle The address of the oracle contract that will fulfill the request
* @param _requestId The request ID used for the response
*/
function addChainlinkExternalRequest(address _oracle, bytes32 _requestId)
internal
notPendingRequest(_requestId)
{
pendingRequests[_requestId] = _oracle;
}
/**
* @notice Sets the stored oracle and LINK token contracts with the addresses resolved by ENS
* @dev Accounts for subnodes having different resolvers
* @param _ens The address of the ENS contract
* @param _node The ENS node hash
*/
function useChainlinkWithENS(address _ens, bytes32 _node)
internal
{
ens = ENSInterface(_ens);
ensNode = _node;
bytes32 linkSubnode = keccak256(abi.encodePacked(ensNode, ENS_TOKEN_SUBNAME));
ENSResolver_Chainlink resolver = ENSResolver_Chainlink(ens.resolver(linkSubnode));
setChainlinkToken(resolver.addr(linkSubnode));
updateChainlinkOracleWithENS();
}
/**
* @notice Sets the stored oracle contract with the address resolved by ENS
* @dev This may be called on its own as long as `useChainlinkWithENS` has been called previously
*/
function updateChainlinkOracleWithENS()
internal
{
bytes32 oracleSubnode = keccak256(abi.encodePacked(ensNode, ENS_ORACLE_SUBNAME));
ENSResolver_Chainlink resolver = ENSResolver_Chainlink(ens.resolver(oracleSubnode));
setChainlinkOracle(resolver.addr(oracleSubnode));
}
/**
* @notice Encodes the request to be sent to the oracle contract
* @dev The Chainlink node expects values to be in order for the request to be picked up. Order of types
* will be validated in the oracle contract.
* @param _req The initialized Chainlink Request
* @return The bytes payload for the `transferAndCall` method
*/
function encodeRequest(Chainlink.Request memory _req)
private
view
returns (bytes memory)
{
return abi.encodeWithSelector(
oracle.oracleRequest.selector,
SENDER_OVERRIDE, // Sender value - overridden by onTokenTransfer by the requesting contract's address
AMOUNT_OVERRIDE, // Amount value - overridden by onTokenTransfer by the actual amount of LINK sent
_req.id,
_req.callbackAddress,
_req.callbackFunctionId,
_req.nonce,
ARGS_VERSION,
_req.buf.buf);
}
/**
* @notice Ensures that the fulfillment is valid for this contract
* @dev Use if the contract developer prefers methods instead of modifiers for validation
* @param _requestId The request ID for fulfillment
*/
function validateChainlinkCallback(bytes32 _requestId)
internal
recordChainlinkFulfillment(_requestId)
// solhint-disable-next-line no-empty-blocks
{}
/**
* @dev Reverts if the sender is not the oracle of the request.
* Emits ChainlinkFulfilled event.
* @param _requestId The request ID for fulfillment
*/
modifier recordChainlinkFulfillment(bytes32 _requestId) {
require(msg.sender == pendingRequests[_requestId],
"Source must be the oracle of the request");
delete pendingRequests[_requestId];
emit ChainlinkFulfilled(_requestId);
_;
}
/**
* @dev Reverts if the request is already pending
* @param _requestId The request ID for fulfillment
*/
modifier notPendingRequest(bytes32 _requestId) {
require(pendingRequests[_requestId] == address(0), "Request is already pending");
_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "@chainlink/contracts/v0.6/vendor/SafeMathChainlink.sol";
import "@chainlink/contracts/v0.6/interfaces/LinkTokenInterface.sol";
import "@chainlink/contracts/v0.6/VRFRequestIDBase.sol";
// import "./vendor/SafeMathChainlink.sol";
// import "./interfaces/LinkTokenInterface.sol";
// import "./VRFRequestIDBase.sol";
/** ****************************************************************************
* @notice Interface for contracts using VRF randomness
* *****************************************************************************
* @dev PURPOSE
*
* @dev Reggie the Random Oracle (not his real job) wants to provide randomness
* @dev to Vera the verifier in such a way that Vera can be sure he's not
* @dev making his output up to suit himself. Reggie provides Vera a public key
* @dev to which he knows the secret key. Each time Vera provides a seed to
* @dev Reggie, he gives back a value which is computed completely
* @dev deterministically from the seed and the secret key.
*
* @dev Reggie provides a proof by which Vera can verify that the output was
* @dev correctly computed once Reggie tells it to her, but without that proof,
* @dev the output is indistinguishable to her from a uniform random sample
* @dev from the output space.
*
* @dev The purpose of this contract is to make it easy for unrelated contracts
* @dev to talk to Vera the verifier about the work Reggie is doing, to provide
* @dev simple access to a verifiable source of randomness.
* *****************************************************************************
* @dev USAGE
*
* @dev Calling contracts must inherit from VRFConsumerBase, and can
* @dev initialize VRFConsumerBase's attributes in their constructor as
* @dev shown:
*
* @dev contract VRFConsumer {
* @dev constuctor(<other arguments>, address _vrfCoordinator, address _link)
* @dev VRFConsumerBase(_vrfCoordinator, _link) public {
* @dev <initialization with other arguments goes here>
* @dev }
* @dev }
*
* @dev The oracle will have given you an ID for the VRF keypair they have
* @dev committed to (let's call it keyHash), and have told you the minimum LINK
* @dev price for VRF service. Make sure your contract has sufficient LINK, and
* @dev call requestRandomness(keyHash, fee, seed), where seed is the input you
* @dev want to generate randomness from.
*
* @dev Once the VRFCoordinator has received and validated the oracle's response
* @dev to your request, it will call your contract's fulfillRandomness method.
*
* @dev The randomness argument to fulfillRandomness is the actual random value
* @dev generated from your seed.
*
* @dev The requestId argument is generated from the keyHash and the seed by
* @dev makeRequestId(keyHash, seed). If your contract could have concurrent
* @dev requests open, you can use the requestId to track which seed is
* @dev associated with which randomness. See VRFRequestIDBase.sol for more
* @dev details. (See "SECURITY CONSIDERATIONS" for principles to keep in mind,
* @dev if your contract could have multiple requests in flight simultaneously.)
*
* @dev Colliding `requestId`s are cryptographically impossible as long as seeds
* @dev differ. (Which is critical to making unpredictable randomness! See the
* @dev next section.)
*
* *****************************************************************************
* @dev SECURITY CONSIDERATIONS
*
* @dev A method with the ability to call your fulfillRandomness method directly
* @dev could spoof a VRF response with any random value, so it's critical that
* @dev it cannot be directly called by anything other than this base contract
* @dev (specifically, by the VRFConsumerBase.rawFulfillRandomness method).
*
* @dev For your users to trust that your contract's random behavior is free
* @dev from malicious interference, it's best if you can write it so that all
* @dev behaviors implied by a VRF response are executed *during* your
* @dev fulfillRandomness method. If your contract must store the response (or
* @dev anything derived from it) and use it later, you must ensure that any
* @dev user-significant behavior which depends on that stored value cannot be
* @dev manipulated by a subsequent VRF request.
*
* @dev Similarly, both miners and the VRF oracle itself have some influence
* @dev over the order in which VRF responses appear on the blockchain, so if
* @dev your contract could have multiple VRF requests in flight simultaneously,
* @dev you must ensure that the order in which the VRF responses arrive cannot
* @dev be used to manipulate your contract's user-significant behavior.
*
* @dev Since the ultimate input to the VRF is mixed with the block hash of the
* @dev block in which the request is made, user-provided seeds have no impact
* @dev on its economic security properties. They are only included for API
* @dev compatability with previous versions of this contract.
*
* @dev Since the block hash of the block which contains the requestRandomness
* @dev call is mixed into the input to the VRF *last*, a sufficiently powerful
* @dev miner could, in principle, fork the blockchain to evict the block
* @dev containing the request, forcing the request to be included in a
* @dev different block with a different hash, and therefore a different input
* @dev to the VRF. However, such an attack would incur a substantial economic
* @dev cost. This cost scales with the number of blocks the VRF oracle waits
* @dev until it calls responds to a request.
*/
abstract contract VRFConsumerBase is VRFRequestIDBase {
using SafeMathChainlink for uint256;
/**
* @notice fulfillRandomness handles the VRF response. Your contract must
* @notice implement it. See "SECURITY CONSIDERATIONS" above for important
* @notice principles to keep in mind when implementing your fulfillRandomness
* @notice method.
*
* @dev VRFConsumerBase expects its subcontracts to have a method with this
* @dev signature, and will call it once it has verified the proof
* @dev associated with the randomness. (It is triggered via a call to
* @dev rawFulfillRandomness, below.)
*
* @param requestId The Id initially returned by requestRandomness
* @param randomness the VRF output
*/
function fulfillRandomness(bytes32 requestId, uint256 randomness)
internal virtual;
/**
* @notice requestRandomness initiates a request for VRF output given _seed
*
* @dev The fulfillRandomness method receives the output, once it's provided
* @dev by the Oracle, and verified by the vrfCoordinator.
*
* @dev The _keyHash must already be registered with the VRFCoordinator, and
* @dev the _fee must exceed the fee specified during registration of the
* @dev _keyHash.
*
* @dev The _seed parameter is vestigial, and is kept only for API
* @dev compatibility with older versions. It can't *hurt* to mix in some of
* @dev your own randomness, here, but it's not necessary because the VRF
* @dev oracle will mix the hash of the block containing your request into the
* @dev VRF seed it ultimately uses.
*
* @param _keyHash ID of public key against which randomness is generated
* @param _fee The amount of LINK to send with the request
* @param _seed seed mixed into the input of the VRF.
*
* @return requestId unique ID for this request
*
* @dev The returned requestId can be used to distinguish responses to
* @dev concurrent requests. It is passed as the first argument to
* @dev fulfillRandomness.
*/
function requestRandomness(bytes32 _keyHash, uint256 _fee, uint256 _seed)
internal returns (bytes32 requestId)
{
LINK_TOKEN_INTERFACE.transferAndCall(vrfCoordinator, _fee, abi.encode(_keyHash, _seed));
// This is the seed passed to VRFCoordinator. The oracle will mix this with
// the hash of the block containing this request to obtain the seed/input
// which is finally passed to the VRF cryptographic machinery.
uint256 vRFSeed = makeVRFInputSeed(_keyHash, _seed, address(this), nonces[_keyHash]);
// nonces[_keyHash] must stay in sync with
// VRFCoordinator.nonces[_keyHash][this], which was incremented by the above
// successful LINK_TOKEN_INTERFACE.transferAndCall (in VRFCoordinator.randomnessRequest).
// This provides protection against the user repeating their input seed,
// which would result in a predictable/duplicate output, if multiple such
// requests appeared in the same block.
nonces[_keyHash] = nonces[_keyHash].add(1);
return makeRequestId(_keyHash, vRFSeed);
}
LinkTokenInterface immutable internal LINK_TOKEN_INTERFACE;
address immutable private vrfCoordinator;
// Nonces for each VRF key from which randomness has been requested.
//
// Must stay in sync with VRFCoordinator[_keyHash][this]
mapping(bytes32 /* keyHash */ => uint256 /* nonce */) private nonces;
/**
* @param _vrfCoordinator address of VRFCoordinator contract
* @param _link address of LINK token contract
*
* @dev https://docs.chain.link/docs/link-token-contracts
*/
constructor(address _vrfCoordinator, address _link) public {
vrfCoordinator = _vrfCoordinator;
LINK_TOKEN_INTERFACE = LinkTokenInterface(_link);
}
// rawFulfillRandomness is called by VRFCoordinator when it receives a valid VRF
// proof. rawFulfillRandomness then calls fulfillRandomness, after validating
// the origin of the call
function rawFulfillRandomness(bytes32 requestId, uint256 randomness) external {
require(msg.sender == vrfCoordinator, "Only VRFCoordinator can fulfill");
fulfillRandomness(requestId, randomness);
}
}
// 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.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.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);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import { CBORChainlink } from "./vendor/CBORChainlink.sol";
import { BufferChainlink } from "./vendor/BufferChainlink.sol";
/**
* @title Library for common Chainlink functions
* @dev Uses imported CBOR library for encoding to buffer
*/
library Chainlink {
uint256 internal constant defaultBufferSize = 256; // solhint-disable-line const-name-snakecase
using CBORChainlink for BufferChainlink.buffer;
struct Request {
bytes32 id;
address callbackAddress;
bytes4 callbackFunctionId;
uint256 nonce;
BufferChainlink.buffer buf;
}
/**
* @notice Initializes a Chainlink request
* @dev Sets the ID, callback address, and callback function signature on the request
* @param self The uninitialized request
* @param _id The Job Specification ID
* @param _callbackAddress The callback address
* @param _callbackFunction The callback function signature
* @return The initialized request
*/
function initialize(
Request memory self,
bytes32 _id,
address _callbackAddress,
bytes4 _callbackFunction
) internal pure returns (Chainlink.Request memory) {
BufferChainlink.init(self.buf, defaultBufferSize);
self.id = _id;
self.callbackAddress = _callbackAddress;
self.callbackFunctionId = _callbackFunction;
return self;
}
/**
* @notice Sets the data for the buffer without encoding CBOR on-chain
* @dev CBOR can be closed with curly-brackets {} or they can be left off
* @param self The initialized request
* @param _data The CBOR data
*/
function setBuffer(Request memory self, bytes memory _data)
internal pure
{
BufferChainlink.init(self.buf, _data.length);
BufferChainlink.append(self.buf, _data);
}
/**
* @notice Adds a string value to the request with a given key name
* @param self The initialized request
* @param _key The name of the key
* @param _value The string value to add
*/
function add(Request memory self, string memory _key, string memory _value)
internal pure
{
self.buf.encodeString(_key);
self.buf.encodeString(_value);
}
/**
* @notice Adds a bytes value to the request with a given key name
* @param self The initialized request
* @param _key The name of the key
* @param _value The bytes value to add
*/
function addBytes(Request memory self, string memory _key, bytes memory _value)
internal pure
{
self.buf.encodeString(_key);
self.buf.encodeBytes(_value);
}
/**
* @notice Adds a int256 value to the request with a given key name
* @param self The initialized request
* @param _key The name of the key
* @param _value The int256 value to add
*/
function addInt(Request memory self, string memory _key, int256 _value)
internal pure
{
self.buf.encodeString(_key);
self.buf.encodeInt(_value);
}
/**
* @notice Adds a uint256 value to the request with a given key name
* @param self The initialized request
* @param _key The name of the key
* @param _value The uint256 value to add
*/
function addUint(Request memory self, string memory _key, uint256 _value)
internal pure
{
self.buf.encodeString(_key);
self.buf.encodeUInt(_value);
}
/**
* @notice Adds an array of strings to the request with a given key name
* @param self The initialized request
* @param _key The name of the key
* @param _values The array of string values to add
*/
function addStringArray(Request memory self, string memory _key, string[] memory _values)
internal pure
{
self.buf.encodeString(_key);
self.buf.startArray();
for (uint256 i = 0; i < _values.length; i++) {
self.buf.encodeString(_values[i]);
}
self.buf.endSequence();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
interface ENSInterface {
// Logged when the owner of a node assigns a new owner to a subnode.
event NewOwner(bytes32 indexed node, bytes32 indexed label, address owner);
// Logged when the owner of a node transfers ownership to a new account.
event Transfer(bytes32 indexed node, address owner);
// Logged when the resolver for a node changes.
event NewResolver(bytes32 indexed node, address resolver);
// Logged when the TTL of a node changes
event NewTTL(bytes32 indexed node, uint64 ttl);
function setSubnodeOwner(bytes32 node, bytes32 label, address _owner) external;
function setResolver(bytes32 node, address _resolver) external;
function setOwner(bytes32 node, address _owner) external;
function setTTL(bytes32 node, uint64 _ttl) external;
function owner(bytes32 node) external view returns (address);
function resolver(bytes32 node) external view returns (address);
function ttl(bytes32 node) external view returns (uint64);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
interface LinkTokenInterface {
function allowance(address owner, address spender) external view returns (uint256 remaining);
function approve(address spender, uint256 value) external returns (bool success);
function balanceOf(address owner) external view returns (uint256 balance);
function decimals() external view returns (uint8 decimalPlaces);
function decreaseApproval(address spender, uint256 addedValue) external returns (bool success);
function increaseApproval(address spender, uint256 subtractedValue) external;
function name() external view returns (string memory tokenName);
function symbol() external view returns (string memory tokenSymbol);
function totalSupply() external view returns (uint256 totalTokensIssued);
function transfer(address to, uint256 value) external returns (bool success);
function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool success);
function transferFrom(address from, address to, uint256 value) external returns (bool success);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
interface ChainlinkRequestInterface {
function oracleRequest(
address sender,
uint256 requestPrice,
bytes32 serviceAgreementID,
address callbackAddress,
bytes4 callbackFunctionId,
uint256 nonce,
uint256 dataVersion,
bytes calldata data
) external;
function cancelOracleRequest(
bytes32 requestId,
uint256 payment,
bytes4 callbackFunctionId,
uint256 expiration
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
interface PointerInterface {
function getAddress() external view returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
abstract contract ENSResolver {
function addr(bytes32 node) public view virtual returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity >= 0.4.19 < 0.7.0;
import { BufferChainlink } from "./BufferChainlink.sol";
library CBORChainlink {
using BufferChainlink for BufferChainlink.buffer;
uint8 private constant MAJOR_TYPE_INT = 0;
uint8 private constant MAJOR_TYPE_NEGATIVE_INT = 1;
uint8 private constant MAJOR_TYPE_BYTES = 2;
uint8 private constant MAJOR_TYPE_STRING = 3;
uint8 private constant MAJOR_TYPE_ARRAY = 4;
uint8 private constant MAJOR_TYPE_MAP = 5;
uint8 private constant MAJOR_TYPE_TAG = 6;
uint8 private constant MAJOR_TYPE_CONTENT_FREE = 7;
uint8 private constant TAG_TYPE_BIGNUM = 2;
uint8 private constant TAG_TYPE_NEGATIVE_BIGNUM = 3;
function encodeType(BufferChainlink.buffer memory buf, uint8 major, uint value) private pure {
if(value <= 23) {
buf.appendUint8(uint8((major << 5) | value));
} else if(value <= 0xFF) {
buf.appendUint8(uint8((major << 5) | 24));
buf.appendInt(value, 1);
} else if(value <= 0xFFFF) {
buf.appendUint8(uint8((major << 5) | 25));
buf.appendInt(value, 2);
} else if(value <= 0xFFFFFFFF) {
buf.appendUint8(uint8((major << 5) | 26));
buf.appendInt(value, 4);
} else if(value <= 0xFFFFFFFFFFFFFFFF) {
buf.appendUint8(uint8((major << 5) | 27));
buf.appendInt(value, 8);
}
}
function encodeIndefiniteLengthType(BufferChainlink.buffer memory buf, uint8 major) private pure {
buf.appendUint8(uint8((major << 5) | 31));
}
function encodeUInt(BufferChainlink.buffer memory buf, uint value) internal pure {
encodeType(buf, MAJOR_TYPE_INT, value);
}
function encodeInt(BufferChainlink.buffer memory buf, int value) internal pure {
if(value < -0x10000000000000000) {
encodeSignedBigNum(buf, value);
} else if(value > 0xFFFFFFFFFFFFFFFF) {
encodeBigNum(buf, value);
} else if(value >= 0) {
encodeType(buf, MAJOR_TYPE_INT, uint(value));
} else {
encodeType(buf, MAJOR_TYPE_NEGATIVE_INT, uint(-1 - value));
}
}
function encodeBytes(BufferChainlink.buffer memory buf, bytes memory value) internal pure {
encodeType(buf, MAJOR_TYPE_BYTES, value.length);
buf.append(value);
}
function encodeBigNum(BufferChainlink.buffer memory buf, int value) internal pure {
buf.appendUint8(uint8((MAJOR_TYPE_TAG << 5) | TAG_TYPE_BIGNUM));
encodeBytes(buf, abi.encode(uint(value)));
}
function encodeSignedBigNum(BufferChainlink.buffer memory buf, int input) internal pure {
buf.appendUint8(uint8((MAJOR_TYPE_TAG << 5) | TAG_TYPE_NEGATIVE_BIGNUM));
encodeBytes(buf, abi.encode(uint(-1 - input)));
}
function encodeString(BufferChainlink.buffer memory buf, string memory value) internal pure {
encodeType(buf, MAJOR_TYPE_STRING, bytes(value).length);
buf.append(bytes(value));
}
function startArray(BufferChainlink.buffer memory buf) internal pure {
encodeIndefiniteLengthType(buf, MAJOR_TYPE_ARRAY);
}
function startMap(BufferChainlink.buffer memory buf) internal pure {
encodeIndefiniteLengthType(buf, MAJOR_TYPE_MAP);
}
function endSequence(BufferChainlink.buffer memory buf) internal pure {
encodeIndefiniteLengthType(buf, MAJOR_TYPE_CONTENT_FREE);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev A library for working with mutable byte buffers in Solidity.
*
* Byte buffers are mutable and expandable, and provide a variety of primitives
* for writing to them. At any time you can fetch a bytes object containing the
* current contents of the buffer. The bytes object should not be stored between
* operations, as it may change due to resizing of the buffer.
*/
library BufferChainlink {
/**
* @dev Represents a mutable buffer. Buffers have a current value (buf) and
* a capacity. The capacity may be longer than the current value, in
* which case it can be extended without the need to allocate more memory.
*/
struct buffer {
bytes buf;
uint capacity;
}
/**
* @dev Initializes a buffer with an initial capacity.
* @param buf The buffer to initialize.
* @param capacity The number of bytes of space to allocate the buffer.
* @return The buffer, for chaining.
*/
function init(buffer memory buf, uint capacity) internal pure returns(buffer memory) {
if (capacity % 32 != 0) {
capacity += 32 - (capacity % 32);
}
// Allocate space for the buffer data
buf.capacity = capacity;
assembly {
let ptr := mload(0x40)
mstore(buf, ptr)
mstore(ptr, 0)
mstore(0x40, add(32, add(ptr, capacity)))
}
return buf;
}
/**
* @dev Initializes a new buffer from an existing bytes object.
* Changes to the buffer may mutate the original value.
* @param b The bytes object to initialize the buffer with.
* @return A new buffer.
*/
function fromBytes(bytes memory b) internal pure returns(buffer memory) {
buffer memory buf;
buf.buf = b;
buf.capacity = b.length;
return buf;
}
function resize(buffer memory buf, uint capacity) private pure {
bytes memory oldbuf = buf.buf;
init(buf, capacity);
append(buf, oldbuf);
}
function max(uint a, uint b) private pure returns(uint) {
if (a > b) {
return a;
}
return b;
}
/**
* @dev Sets buffer length to 0.
* @param buf The buffer to truncate.
* @return The original buffer, for chaining..
*/
function truncate(buffer memory buf) internal pure returns (buffer memory) {
assembly {
let bufptr := mload(buf)
mstore(bufptr, 0)
}
return buf;
}
/**
* @dev Writes a byte string to a buffer. Resizes if doing so would exceed
* the capacity of the buffer.
* @param buf The buffer to append to.
* @param off The start offset to write to.
* @param data The data to append.
* @param len The number of bytes to copy.
* @return The original buffer, for chaining.
*/
function write(buffer memory buf, uint off, bytes memory data, uint len) internal pure returns(buffer memory) {
require(len <= data.length);
if (off + len > buf.capacity) {
resize(buf, max(buf.capacity, len + off) * 2);
}
uint dest;
uint src;
assembly {
// Memory address of the buffer data
let bufptr := mload(buf)
// Length of existing buffer data
let buflen := mload(bufptr)
// Start address = buffer address + offset + sizeof(buffer length)
dest := add(add(bufptr, 32), off)
// Update buffer length if we're extending it
if gt(add(len, off), buflen) {
mstore(bufptr, add(len, off))
}
src := add(data, 32)
}
// Copy word-length chunks while possible
for (; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
// Copy remaining bytes
uint mask = 256 ** (32 - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
return buf;
}
/**
* @dev Appends a byte string to a buffer. Resizes if doing so would exceed
* the capacity of the buffer.
* @param buf The buffer to append to.
* @param data The data to append.
* @param len The number of bytes to copy.
* @return The original buffer, for chaining.
*/
function append(buffer memory buf, bytes memory data, uint len) internal pure returns (buffer memory) {
return write(buf, buf.buf.length, data, len);
}
/**
* @dev Appends a byte string to a buffer. Resizes if doing so would exceed
* the capacity of the buffer.
* @param buf The buffer to append to.
* @param data The data to append.
* @return The original buffer, for chaining.
*/
function append(buffer memory buf, bytes memory data) internal pure returns (buffer memory) {
return write(buf, buf.buf.length, data, data.length);
}
/**
* @dev Writes a byte to the buffer. Resizes if doing so would exceed the
* capacity of the buffer.
* @param buf The buffer to append to.
* @param off The offset to write the byte at.
* @param data The data to append.
* @return The original buffer, for chaining.
*/
function writeUint8(buffer memory buf, uint off, uint8 data) internal pure returns(buffer memory) {
if (off >= buf.capacity) {
resize(buf, buf.capacity * 2);
}
assembly {
// Memory address of the buffer data
let bufptr := mload(buf)
// Length of existing buffer data
let buflen := mload(bufptr)
// Address = buffer address + sizeof(buffer length) + off
let dest := add(add(bufptr, off), 32)
mstore8(dest, data)
// Update buffer length if we extended it
if eq(off, buflen) {
mstore(bufptr, add(buflen, 1))
}
}
return buf;
}
/**
* @dev Appends a byte to the buffer. Resizes if doing so would exceed the
* capacity of the buffer.
* @param buf The buffer to append to.
* @param data The data to append.
* @return The original buffer, for chaining.
*/
function appendUint8(buffer memory buf, uint8 data) internal pure returns(buffer memory) {
return writeUint8(buf, buf.buf.length, data);
}
/**
* @dev Writes up to 32 bytes to the buffer. Resizes if doing so would
* exceed the capacity of the buffer.
* @param buf The buffer to append to.
* @param off The offset to write at.
* @param data The data to append.
* @param len The number of bytes to write (left-aligned).
* @return The original buffer, for chaining.
*/
function write(buffer memory buf, uint off, bytes32 data, uint len) private pure returns(buffer memory) {
if (len + off > buf.capacity) {
resize(buf, (len + off) * 2);
}
uint mask = 256 ** len - 1;
// Right-align data
data = data >> (8 * (32 - len));
assembly {
// Memory address of the buffer data
let bufptr := mload(buf)
// Address = buffer address + sizeof(buffer length) + off + len
let dest := add(add(bufptr, off), len)
mstore(dest, or(and(mload(dest), not(mask)), data))
// Update buffer length if we extended it
if gt(add(off, len), mload(bufptr)) {
mstore(bufptr, add(off, len))
}
}
return buf;
}
/**
* @dev Writes a bytes20 to the buffer. Resizes if doing so would exceed the
* capacity of the buffer.
* @param buf The buffer to append to.
* @param off The offset to write at.
* @param data The data to append.
* @return The original buffer, for chaining.
*/
function writeBytes20(buffer memory buf, uint off, bytes20 data) internal pure returns (buffer memory) {
return write(buf, off, bytes32(data), 20);
}
/**
* @dev Appends a bytes20 to the buffer. Resizes if doing so would exceed
* the capacity of the buffer.
* @param buf The buffer to append to.
* @param data The data to append.
* @return The original buffer, for chhaining.
*/
function appendBytes20(buffer memory buf, bytes20 data) internal pure returns (buffer memory) {
return write(buf, buf.buf.length, bytes32(data), 20);
}
/**
* @dev Appends a bytes32 to the buffer. Resizes if doing so would exceed
* the capacity of the buffer.
* @param buf The buffer to append to.
* @param data The data to append.
* @return The original buffer, for chaining.
*/
function appendBytes32(buffer memory buf, bytes32 data) internal pure returns (buffer memory) {
return write(buf, buf.buf.length, data, 32);
}
/**
* @dev Writes an integer to the buffer. Resizes if doing so would exceed
* the capacity of the buffer.
* @param buf The buffer to append to.
* @param off The offset to write at.
* @param data The data to append.
* @param len The number of bytes to write (right-aligned).
* @return The original buffer, for chaining.
*/
function writeInt(buffer memory buf, uint off, uint data, uint len) private pure returns(buffer memory) {
if (len + off > buf.capacity) {
resize(buf, (len + off) * 2);
}
uint mask = 256 ** len - 1;
assembly {
// Memory address of the buffer data
let bufptr := mload(buf)
// Address = buffer address + off + sizeof(buffer length) + len
let dest := add(add(bufptr, off), len)
mstore(dest, or(and(mload(dest), not(mask)), data))
// Update buffer length if we extended it
if gt(add(off, len), mload(bufptr)) {
mstore(bufptr, add(off, len))
}
}
return buf;
}
/**
* @dev Appends a byte to the end of the buffer. Resizes if doing so would
* exceed the capacity of the buffer.
* @param buf The buffer to append to.
* @param data The data to append.
* @return The original buffer.
*/
function appendInt(buffer memory buf, uint data, uint len) internal pure returns(buffer memory) {
return writeInt(buf, buf.buf.length, data, len);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMathChainlink {
/**
* @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;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
contract VRFRequestIDBase {
/**
* @notice returns the seed which is actually input to the VRF coordinator
*
* @dev To prevent repetition of VRF output due to repetition of the
* @dev user-supplied seed, that seed is combined in a hash with the
* @dev user-specific nonce, and the address of the consuming contract. The
* @dev risk of repetition is mostly mitigated by inclusion of a blockhash in
* @dev the final seed, but the nonce does protect against repetition in
* @dev requests which are included in a single block.
*
* @param _userSeed VRF seed input provided by user
* @param _requester Address of the requesting contract
* @param _nonce User-specific nonce at the time of the request
*/
function makeVRFInputSeed(bytes32 _keyHash, uint256 _userSeed,
address _requester, uint256 _nonce)
internal pure returns (uint256)
{
return uint256(keccak256(abi.encode(_keyHash, _userSeed, _requester, _nonce)));
}
/**
* @notice Returns the id for this request
* @param _keyHash The serviceAgreement ID to be used for this request
* @param _vRFInputSeed The seed to be passed directly to the VRF
* @return The id for this request
*
* @dev Note that _vRFInputSeed is not the seed passed by the consuming
* @dev contract, but the one generated by makeVRFInputSeed
*/
function makeRequestId(
bytes32 _keyHash, uint256 _vRFInputSeed) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(_keyHash, _vRFInputSeed));
}
}
|
Make the Chainlink request.
|
function remoteMintTwenty(uint256 tokenId) private returns (bytes32 requestId) {
Chainlink.Request memory request = buildChainlinkRequest(jobId, address(this), this.fulfillTwenty.selector);
string memory url = string(
abi.encodePacked(
"&token=", tokenId.toString()
)
);
request.add("get", url);
return sendChainlinkRequestTo(oracle, request, fee);
}
| 921,102 |
pragma solidity ^0.8.10;
// interfaces
import "./interfaces/IERC20.sol";
import "./interfaces/ITreasury.sol";
import "./interfaces/IAllocator.sol";
import "./interfaces/ITreasuryExtender.sol";
// types
import "./types/OlympusAccessControlledV2.sol";
// libraries
import "./libraries/SafeERC20.sol";
error TreasuryExtender_AllocatorOffline();
error TreasuryExtender_AllocatorNotActivated();
error TreasuryExtender_AllocatorNotOffline();
error TreasuryExtender_AllocatorRegistered(uint256 id);
error TreasuryExtender_OnlyAllocator(uint256 id, address sender);
error TreasuryExtender_MaxAllocation(uint256 allocated, uint256 limit);
/**
* @title Treasury Extender
* @notice
* This contract serves as an accounting and management contract which
* will interact with the Olympus Treasury to fund Allocators.
*
* Accounting:
* For each Allocator there are multiple deposit IDs referring to individual tokens,
* for each deposit ID we record 5 distinct values grouped into 3 fields,
* together grouped as AllocatorData:
*
* AllocatorLimits { allocated, loss } - This is the maximum amount
* an Allocator should have allocated at any point, and also the maximum
* loss an allocator should experience without automatically shutting down.
*
* AllocatorPerformance { gain, loss } - This is the current gain (total - allocated)
* and the loss the Allocator sustained over its time of operation.
*
* AllocatorHoldings { allocated } - This is the amount of tokens an Allocator
* has currently been allocated by the Extender.
*
* Important: The above is only tracked in the underlying token specified by the ID,
* (see BaseAllocator.sol) while rewards are retrievable by the standard ERC20 functions.
* The point is that we only exactly track that which exits the Treasury.
*/
contract TreasuryExtender is OlympusAccessControlledV2, ITreasuryExtender {
using SafeERC20 for IERC20;
// The Olympus Treasury.
ITreasury public immutable treasury;
// Enumerable Allocators according to deposit IDs.
/// @dev NOTE: Allocator enumeration starts from index 1.
IAllocator[] public allocators;
// Get an an Allocator's Data for for an Allocator and deposit ID
mapping(IAllocator => mapping(uint256 => AllocatorData)) public allocatorData;
constructor(address treasuryAddress, address authorityAddress)
OlympusAccessControlledV2(IOlympusAuthority(authorityAddress))
{
treasury = ITreasury(treasuryAddress);
// This nonexistent allocator at address(0) is pushed
// as a placeholder so enumeration may start from index 1.
allocators.push(IAllocator(address(0)));
}
//// CHECKS
function _allocatorActivated(AllocatorStatus status) internal pure {
if (AllocatorStatus.ACTIVATED != status) revert TreasuryExtender_AllocatorNotActivated();
}
function _allocatorOffline(AllocatorStatus status) internal pure {
if (AllocatorStatus.OFFLINE != status) revert TreasuryExtender_AllocatorNotOffline();
}
function _onlyAllocator(
IAllocator byStatedId,
address sender,
uint256 id
) internal pure {
if (IAllocator(sender) != byStatedId) revert TreasuryExtender_OnlyAllocator(id, sender);
}
//// FUNCTIONS
/**
* @notice
* Registers an Allocator. Adds a deposit id and prepares storage slots for writing.
* Does not activate the Allocator.
* @dev
* Calls `addId` from `IAllocator` with the index of the deposit in `allocators`
* @param newAllocator the Allocator to be registered
*/
function registerDeposit(address newAllocator) external override onlyGuardian {
// reads
IAllocator allocator = IAllocator(newAllocator);
// effects
allocators.push(allocator);
uint256 id = allocators.length - 1;
// interactions
allocator.addId(id);
// events
emit NewDepositRegistered(newAllocator, address(allocator.tokens()[allocator.tokenIds(id)]), id);
}
/**
* @notice
* Sets an Allocators AllocatorLimits.
* AllocatorLimits is part of AllocatorData, variable meanings follow:
* allocated - The maximum amount a Guardian may allocate this Allocator from Treasury.
* loss - The maximum loss amount this Allocator can take.
* @dev
* Can only be called while the Allocator is offline.
* @param id the deposit id to set AllocatorLimits for
* @param limits the AllocatorLimits to set
*/
function setAllocatorLimits(uint256 id, AllocatorLimits calldata limits) external override onlyGuardian {
IAllocator allocator = allocators[id];
// checks
_allocatorOffline(allocator.status());
// effects
allocatorData[allocator][id].limits = limits;
// events
emit AllocatorLimitsChanged(id, limits.allocated, limits.loss);
}
/**
* @notice
* Reports an Allocators status to the Extender.
* Updates Extender state accordingly.
* @dev
* Can only be called while the Allocator is activated or migrating.
* The idea is that first the Allocator updates its own state, then
* it reports this state to the Extender, which then updates its own state.
*
* There is 3 different combinations the Allocator may report:
*
* (gain + loss) == 0, the Allocator will NEVER report this state
* gain > loss, gain is reported and incremented but allocated not.
* loss > gain, loss is reported, allocated and incremented.
* loss == gain == type(uint128).max , migration case, zero out gain, loss, allocated
*
* NOTE: please take care to properly calculate loss by, say, only reporting loss above a % threshold
* of allocated. This is to serve as a low pass filter of sorts to ignore noise in price movements.
* NOTE: when migrating the next Allocator should report his state to the Extender, in say an `_activate` call.
*
* @param id the deposit id of the token to report state for
* @param gain the gain the Allocator has made in allocated token
* @param loss the loss the Allocator has sustained in allocated token
*/
function report(
uint256 id,
uint128 gain,
uint128 loss
) external override {
// reads
IAllocator allocator = allocators[id];
AllocatorData storage data = allocatorData[allocator][id];
AllocatorPerformance memory perf = data.performance;
AllocatorStatus status = allocator.status();
// checks
_onlyAllocator(allocator, msg.sender, id);
if (status == AllocatorStatus.OFFLINE) revert TreasuryExtender_AllocatorOffline();
// EFFECTS
if (gain >= loss) {
// MIGRATION
// according to above gain must equal loss because
// gain can't be larger than max uint128 value
if (loss == type(uint128).max) {
AllocatorData storage newAllocatorData = allocatorData[allocators[allocators.length - 1]][id];
newAllocatorData.holdings.allocated = data.holdings.allocated;
newAllocatorData.performance.gain = data.performance.gain;
data.holdings.allocated = 0;
perf.gain = 0;
perf.loss = 0;
emit AllocatorReportedMigration(id);
// GAIN
} else {
perf.gain += gain;
emit AllocatorReportedGain(id, gain);
}
// LOSS
} else {
data.holdings.allocated -= loss;
perf.loss += loss;
emit AllocatorReportedLoss(id, loss);
}
data.performance = perf;
}
/**
* @notice
* Requests funds from the Olympus Treasury to fund an Allocator.
* @dev
* Can only be called while the Allocator is activated.
* Can only be called by the Guardian.
*
* This function is going to allocate an `amount` of deposit id tokens to the Allocator and
* properly record this in storage. This done so that at any point, we know exactly
* how much was initially allocated and also how much value is allocated in total.
*
* The related functions are `getAllocatorAllocated` and `getTotalValueAllocated`.
*
* To note is also the `_allocatorBelowLimit` check.
* @param id the deposit id of the token to fund allocator with
* @param amount the amount of token to withdraw, the token is known in the Allocator
*/
function requestFundsFromTreasury(uint256 id, uint256 amount) external override onlyGuardian {
// reads
IAllocator allocator = allocators[id];
AllocatorData memory data = allocatorData[allocator][id];
address token = address(allocator.tokens()[allocator.tokenIds(id)]);
uint256 value = treasury.tokenValue(token, amount);
// checks
_allocatorActivated(allocator.status());
_allocatorBelowLimit(data, amount);
// interaction (withdrawing)
treasury.manage(token, amount);
// effects
allocatorData[allocator][id].holdings.allocated += amount;
// interaction (depositing)
IERC20(token).safeTransfer(address(allocator), amount);
// events
emit AllocatorFunded(id, amount, value);
}
/**
* @notice
* Returns funds from an Allocator to the Treasury.
* @dev
* External hook: Logic is handled in the internal function.
* Can only be called by the Guardian.
*
* This function is going to withdraw `amount` of allocated token from an Allocator
* back to the Treasury. Prior to calling this function, `deallocate` should be called,
* in order to prepare the funds for withdrawal.
*
* The maximum amount which can be withdrawn is `gain` + `allocated`.
* `allocated` is decremented first after which `gain` is decremented in the case
* that `allocated` is not sufficient.
* @param id the deposit id of the token to fund allocator with
* @param amount the amount of token to withdraw, the token is known in the Allocator
*/
function returnFundsToTreasury(uint256 id, uint256 amount) external override onlyGuardian {
// reads
IAllocator allocator = allocators[id];
uint256 allocated = allocatorData[allocator][id].holdings.allocated;
uint128 gain = allocatorData[allocator][id].performance.gain;
address token = address(allocator.tokens()[allocator.tokenIds(id)]);
if (amount > allocated) {
amount -= allocated;
if (amount > gain) {
amount = allocated + gain;
gain = 0;
} else {
// yes, amount should never > gain, we have safemath
gain -= uint128(amount);
amount += allocated;
}
allocated = 0;
} else {
allocated -= amount;
}
uint256 value = treasury.tokenValue(token, amount);
// checks
_allowTreasuryWithdrawal(IERC20(token));
// interaction (withdrawing)
IERC20(token).safeTransferFrom(address(allocator), address(this), amount);
// effects
allocatorData[allocator][id].holdings.allocated = allocated;
if (allocated == 0) allocatorData[allocator][id].performance.gain = gain;
// interaction (depositing)
assert(treasury.deposit(amount, token, value) == 0);
// events
emit AllocatorWithdrawal(id, amount, value);
}
/**
* @notice
* Returns rewards from an Allocator to the Treasury.
* Also see `_returnRewardsToTreasury`.
* @dev
* External hook: Logic is handled in the internal function.
* Can only be called by the Guardian.
* @param id the deposit id of the token to fund allocator with
* @param token the address of the reward token to withdraw
* @param amount the amount of the reward token to withdraw
*/
function returnRewardsToTreasury(
uint256 id,
address token,
uint256 amount
) external {
_returnRewardsToTreasury(allocators[id], IERC20(token), amount);
}
/**
* @notice
* Returns rewards from an Allocator to the Treasury.
* Also see `_returnRewardsToTreasury`.
* @dev
* External hook: Logic is handled in the internal function.
* Can only be called by the Guardian.
* @param allocatorAddress the address of the Allocator to returns rewards from
* @param token the address of the reward token to withdraw
* @param amount the amount of the reward token to withdraw
*/
function returnRewardsToTreasury(
address allocatorAddress,
address token,
uint256 amount
) external {
_returnRewardsToTreasury(IAllocator(allocatorAddress), IERC20(token), amount);
}
/**
* @notice
* Get an Allocators address by it's ID.
* @dev
* Our first Allocator is at index 1, NOTE: 0 is a placeholder.
* @param id the id of the allocator, NOTE: valid interval: 1 =< id < allocators.length
* @return allocatorAddress the allocator's address
*/
function getAllocatorByID(uint256 id) external view override returns (address allocatorAddress) {
allocatorAddress = address(allocators[id]);
}
/**
* @notice
* Get the total number of Allocators ever registered.
* @dev
* Our first Allocator is at index 1, 0 is a placeholder.
* @return total number of allocators ever registered
*/
function getTotalAllocatorCount() external view returns (uint256) {
return allocators.length;
}
/**
* @notice
* Get an Allocators limits.
* @dev
* For an explanation of AllocatorLimits, see `setAllocatorLimits`
* @return the Allocator's limits
*/
function getAllocatorLimits(uint256 id) external view override returns (AllocatorLimits memory) {
return allocatorData[allocators[id]][id].limits;
}
/**
* @notice
* Get an Allocators performance.
* @dev
* An Allocator's performance is the amount of `gain` and `loss` it has sustained in its
* lifetime. `gain` is the amount of allocated tokens (underlying) acquired, while
* `loss` is the amount lost. `gain` and `loss` are incremented separately.
* Thus, overall performance can be gauged as gain - loss
* @return the Allocator's performance
*/
function getAllocatorPerformance(uint256 id) external view override returns (AllocatorPerformance memory) {
return allocatorData[allocators[id]][id].performance;
}
/**
* @notice
* Get an Allocators amount allocated.
* @dev
* This is simply the amount of `token` which was allocated to the allocator.
* @return the Allocator's amount allocated
*/
function getAllocatorAllocated(uint256 id) external view override returns (uint256) {
return allocatorData[allocators[id]][id].holdings.allocated;
}
/**
* @notice
* Returns rewards from an Allocator to the Treasury.
* @dev
* External hook: Logic is handled in the internal function.
* Can only be called by the Guardian.
*
* The assumption is that the reward tokens being withdrawn are going to be
* either deposited into the contract OR harvested into allocated (underlying).
*
* For this reason we don't need anything other than `balanceOf`.
* @param allocator the Allocator to returns rewards from
* @param token the reward token to withdraw
* @param amount the amount of the reward token to withdraw
*/
function _returnRewardsToTreasury(
IAllocator allocator,
IERC20 token,
uint256 amount
) internal onlyGuardian {
// reads
uint256 balance = token.balanceOf(address(allocator));
amount = (balance < amount) ? balance : amount;
uint256 value = treasury.tokenValue(address(token), amount);
// checks
_allowTreasuryWithdrawal(token);
// interactions
token.safeTransferFrom(address(allocator), address(this), amount);
assert(treasury.deposit(amount, address(token), value) == 0);
// events
emit AllocatorRewardsWithdrawal(address(allocator), amount, value);
}
/**
* @notice
* Approve treasury for withdrawing if token has not been approved.
* @param token Token to approve.
*/
function _allowTreasuryWithdrawal(IERC20 token) internal {
if (token.allowance(address(this), address(treasury)) == 0) token.approve(address(treasury), type(uint256).max);
}
/**
* @notice
* Check if token is below limit for allocation and if not approve it.
* @param data allocator data to check limits and amount allocated
* @param amount amount of tokens to allocate
*/
function _allocatorBelowLimit(AllocatorData memory data, uint256 amount) internal pure {
uint256 newAllocated = data.holdings.allocated + amount;
if (newAllocated > data.limits.allocated)
revert TreasuryExtender_MaxAllocation(newAllocated, data.limits.allocated);
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity >=0.7.5;
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);
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity >=0.7.5;
interface ITreasury {
function deposit(
uint256 _amount,
address _token,
uint256 _profit
) external returns (uint256);
function withdraw(uint256 _amount, address _token) external;
function tokenValue(address _token, uint256 _amount) external view returns (uint256 value_);
function mint(address _recipient, uint256 _amount) external;
function manage(address _token, uint256 _amount) external;
function incurDebt(uint256 amount_, address token_) external;
function repayDebtWithReserve(uint256 amount_, address token_) external;
function excessReserves() external view returns (uint256);
function baseSupply() external view returns (uint256);
}
pragma solidity >=0.8.0;
// interfaces
import "./IERC20.sol";
import "./ITreasuryExtender.sol";
import "./IOlympusAuthority.sol";
enum AllocatorStatus {
OFFLINE,
ACTIVATED,
MIGRATING
}
struct AllocatorInitData {
IOlympusAuthority authority;
ITreasuryExtender extender;
IERC20[] tokens;
}
/**
* @title Interface for the BaseAllocator
* @dev
* These are the standard functions that an Allocator should implement. A subset of these functions
* is implemented in the `BaseAllocator`. Similar to those implemented, if for some reason the developer
* decides to implement a dedicated base contract, or not at all and rather a dedicated Allocator contract
* without base, imitate the functionalities implemented in it.
*/
interface IAllocator {
/**
* @notice
* Emitted when the Allocator is deployed.
*/
event AllocatorDeployed(address authority, address extender);
/**
* @notice
* Emitted when the Allocator is activated.
*/
event AllocatorActivated();
/**
* @notice
* Emitted when the Allocator is deactivated.
*/
event AllocatorDeactivated(bool panic);
/**
* @notice
* Emitted when the Allocators loss limit is violated.
*/
event LossLimitViolated(uint128 lastLoss, uint128 dloss, uint256 estimatedTotalAllocated);
/**
* @notice
* Emitted when a Migration is executed.
* @dev
* After this also `AllocatorDeactivated` should follow.
*/
event MigrationExecuted(address allocator);
/**
* @notice
* Emitted when Ether is received by the contract.
* @dev
* Only the Guardian is able to send the ether.
*/
event EtherReceived(uint256 amount);
function update(uint256 id) external;
function deallocate(uint256[] memory amounts) external;
function prepareMigration() external;
function migrate() external;
function activate() external;
function deactivate(bool panic) external;
function addId(uint256 id) external;
function name() external view returns (string memory);
function ids() external view returns (uint256[] memory);
function tokenIds(uint256 id) external view returns (uint256);
function version() external view returns (string memory);
function status() external view returns (AllocatorStatus);
function tokens() external view returns (IERC20[] memory);
function utilityTokens() external view returns (IERC20[] memory);
function rewardTokens() external view returns (IERC20[] memory);
function amountAllocated(uint256 id) external view returns (uint256);
}
pragma solidity ^0.8.10;
struct AllocatorPerformance {
uint128 gain;
uint128 loss;
}
struct AllocatorLimits {
uint128 allocated;
uint128 loss;
}
struct AllocatorHoldings {
uint256 allocated;
}
struct AllocatorData {
AllocatorHoldings holdings;
AllocatorLimits limits;
AllocatorPerformance performance;
}
/**
* @title Interface for the TreasuryExtender
*/
interface ITreasuryExtender {
/**
* @notice
* Emitted when a new Deposit is registered.
*/
event NewDepositRegistered(address allocator, address token, uint256 id);
/**
* @notice
* Emitted when an Allocator is funded
*/
event AllocatorFunded(uint256 id, uint256 amount, uint256 value);
/**
* @notice
* Emitted when allocated funds are withdrawn from an Allocator
*/
event AllocatorWithdrawal(uint256 id, uint256 amount, uint256 value);
/**
* @notice
* Emitted when rewards are withdrawn from an Allocator
*/
event AllocatorRewardsWithdrawal(address allocator, uint256 amount, uint256 value);
/**
* @notice
* Emitted when an Allocator reports a gain
*/
event AllocatorReportedGain(uint256 id, uint128 gain);
/**
* @notice
* Emitted when an Allocator reports a loss
*/
event AllocatorReportedLoss(uint256 id, uint128 loss);
/**
* @notice
* Emitted when an Allocator reports a migration
*/
event AllocatorReportedMigration(uint256 id);
/**
* @notice
* Emitted when an Allocator limits are modified
*/
event AllocatorLimitsChanged(uint256 id, uint128 allocationLimit, uint128 lossLimit);
function registerDeposit(address newAllocator) external;
function setAllocatorLimits(uint256 id, AllocatorLimits memory limits) external;
function report(
uint256 id,
uint128 gain,
uint128 loss
) external;
function requestFundsFromTreasury(uint256 id, uint256 amount) external;
function returnFundsToTreasury(uint256 id, uint256 amount) external;
function returnRewardsToTreasury(
uint256 id,
address token,
uint256 amount
) external;
function getTotalAllocatorCount() external view returns (uint256);
function getAllocatorByID(uint256 id) external view returns (address);
function getAllocatorAllocated(uint256 id) external view returns (uint256);
function getAllocatorLimits(uint256 id) external view returns (AllocatorLimits memory);
function getAllocatorPerformance(uint256 id) external view returns (AllocatorPerformance memory);
}
pragma solidity ^0.8.10;
import "../interfaces/IOlympusAuthority.sol";
error UNAUTHORIZED();
error AUTHORITY_INITIALIZED();
/// @dev Reasoning for this contract = modifiers literaly copy code
/// instead of pointing towards the logic to execute. Over many
/// functions this bloats contract size unnecessarily.
/// imho modifiers are a meme.
abstract contract OlympusAccessControlledV2 {
/* ========== EVENTS ========== */
event AuthorityUpdated(IOlympusAuthority authority);
/* ========== STATE VARIABLES ========== */
IOlympusAuthority public authority;
/* ========== Constructor ========== */
constructor(IOlympusAuthority _authority) {
authority = _authority;
emit AuthorityUpdated(_authority);
}
/* ========== "MODIFIERS" ========== */
modifier onlyGovernor {
_onlyGovernor();
_;
}
modifier onlyGuardian {
_onlyGuardian();
_;
}
modifier onlyPolicy {
_onlyPolicy();
_;
}
modifier onlyVault {
_onlyVault();
_;
}
/* ========== GOV ONLY ========== */
function initializeAuthority(IOlympusAuthority _newAuthority) internal {
if (authority != IOlympusAuthority(address(0))) revert AUTHORITY_INITIALIZED();
authority = _newAuthority;
emit AuthorityUpdated(_newAuthority);
}
function setAuthority(IOlympusAuthority _newAuthority) external {
_onlyGovernor();
authority = _newAuthority;
emit AuthorityUpdated(_newAuthority);
}
/* ========== INTERNAL CHECKS ========== */
function _onlyGovernor() internal view {
if (msg.sender != authority.governor()) revert UNAUTHORIZED();
}
function _onlyGuardian() internal view {
if (msg.sender != authority.guardian()) revert UNAUTHORIZED();
}
function _onlyPolicy() internal view {
if (msg.sender != authority.policy()) revert UNAUTHORIZED();
}
function _onlyVault() internal view {
if (msg.sender != authority.vault()) revert UNAUTHORIZED();
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.7.5;
import {IERC20} from "../interfaces/IERC20.sol";
/// @notice Safe IERC20 and ETH transfer library that safely handles missing return values.
/// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v3-periphery/blob/main/contracts/libraries/TransferHelper.sol)
/// Taken from Solmate
library SafeERC20 {
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 amount
) internal {
(bool success, bytes memory data) = address(token).call(
abi.encodeWithSelector(IERC20.transferFrom.selector, from, to, amount)
);
require(success && (data.length == 0 || abi.decode(data, (bool))), "TRANSFER_FROM_FAILED");
}
function safeTransfer(
IERC20 token,
address to,
uint256 amount
) internal {
(bool success, bytes memory data) = address(token).call(
abi.encodeWithSelector(IERC20.transfer.selector, to, amount)
);
require(success && (data.length == 0 || abi.decode(data, (bool))), "TRANSFER_FAILED");
}
function safeApprove(
IERC20 token,
address to,
uint256 amount
) internal {
(bool success, bytes memory data) = address(token).call(
abi.encodeWithSelector(IERC20.approve.selector, to, amount)
);
require(success && (data.length == 0 || abi.decode(data, (bool))), "APPROVE_FAILED");
}
function safeTransferETH(address to, uint256 amount) internal {
(bool success, ) = to.call{value: amount}(new bytes(0));
require(success, "ETH_TRANSFER_FAILED");
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity >=0.7.5;
interface IOlympusAuthority {
/* ========== EVENTS ========== */
event GovernorPushed(address indexed from, address indexed to, bool _effectiveImmediately);
event GuardianPushed(address indexed from, address indexed to, bool _effectiveImmediately);
event PolicyPushed(address indexed from, address indexed to, bool _effectiveImmediately);
event VaultPushed(address indexed from, address indexed to, bool _effectiveImmediately);
event GovernorPulled(address indexed from, address indexed to);
event GuardianPulled(address indexed from, address indexed to);
event PolicyPulled(address indexed from, address indexed to);
event VaultPulled(address indexed from, address indexed to);
/* ========== VIEW ========== */
function governor() external view returns (address);
function guardian() external view returns (address);
function policy() external view returns (address);
function vault() external view returns (address);
}
|
Returns funds from an Allocator to the Treasury. External hook: Logic is handled in the internal function. Can only be called by the Guardian. This function is going to withdraw `amount` of allocated token from an Allocator back to the Treasury. Prior to calling this function, `deallocate` should be called, in order to prepare the funds for withdrawal. The maximum amount which can be withdrawn is `gain` + `allocated`. `allocated` is decremented first after which `gain` is decremented in the case that `allocated` is not sufficient. id the deposit id of the token to fund allocator with amount the amount of token to withdraw, the token is known in the Allocator/ reads yes, amount should never > gain, we have safemath
|
function returnFundsToTreasury(uint256 id, uint256 amount) external override onlyGuardian {
IAllocator allocator = allocators[id];
uint256 allocated = allocatorData[allocator][id].holdings.allocated;
uint128 gain = allocatorData[allocator][id].performance.gain;
address token = address(allocator.tokens()[allocator.tokenIds(id)]);
if (amount > allocated) {
amount -= allocated;
if (amount > gain) {
amount = allocated + gain;
gain = 0;
gain -= uint128(amount);
amount += allocated;
}
allocated = 0;
allocated -= amount;
}
uint256 value = treasury.tokenValue(token, amount);
if (allocated == 0) allocatorData[allocator][id].performance.gain = gain;
}
| 377,221 |
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "./utils/ReentrancyGuard.sol";
import "./libraries/TransferHelper.sol";
import "./utils/Ownable.sol";
import "./interfaces/IERC20.sol";
import "./interfaces/OracleWrapper.sol";
contract CHBPublicSale is Ownable, ReentrancyGuard {
uint256 public totalTokenSold;
uint256 public totalUSDTRaised;
uint256 public tokenDecimal;
uint8 public defaultPhase;
uint8 public totalPhases;
address public tokenAddress;
address public receiverAddress = 0xABDe245ef6F5875c3F19d5f699c7A787050cAF5f;
address public USDTAddress = 0xdAC17F958D2ee523a2206206994597C13D831ec7;
address public USDTOracleAddress =
0x3E7d1eAB13ad0104d2750B8863b489D65364e32D;
address public BNBorETHOracleAddress =
0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419;
/* ================ STRUCT SECTION ================ */
// Stores phases
struct Phases {
uint256 tokenSold;
uint256 tokenLimit;
uint32 startTime;
uint32 expirationTimestamp;
uint32 price; // 10 ** 2
bool isComplete;
}
mapping(uint256 => Phases) public phaseInfo;
/* ================ EVENT SECTION ================ */
// Emits when tokens are bought
event TokensBought(
address buyerAddress,
uint256 buyAmount,
uint256 tokenAmount,
uint32 buyTime
);
/* ================ CONSTRUCTOR SECTION ================ */
constructor(address _tokenAddress) {
tokenAddress = _tokenAddress;
totalPhases = 6;
tokenDecimal = uint256(10**Token(tokenAddress).decimals());
uint32 currenTimeStamp = uint32(block.timestamp);
phaseInfo[0] = Phases({
tokenLimit: 200_000_000 * tokenDecimal,
tokenSold: 0,
startTime: currenTimeStamp,
expirationTimestamp: currenTimeStamp + 60 days, // 2 Months
price: 1,
isComplete: false
});
phaseInfo[1] = Phases({
tokenLimit: 100_000_000 * tokenDecimal,
tokenSold: 0,
startTime: phaseInfo[0].expirationTimestamp,
expirationTimestamp: phaseInfo[0].expirationTimestamp + 15 days, // 15 Days
isComplete: false,
price: 2
});
phaseInfo[2] = Phases({
tokenLimit: 100_000_000 * tokenDecimal,
tokenSold: 0,
startTime: phaseInfo[1].expirationTimestamp,
expirationTimestamp: phaseInfo[1].expirationTimestamp + 15 days, // 15 Days
isComplete: false,
price: 3
});
phaseInfo[3] = Phases({
tokenLimit: 100_000_000 * tokenDecimal,
tokenSold: 0,
startTime: phaseInfo[2].expirationTimestamp,
expirationTimestamp: phaseInfo[2].expirationTimestamp + 15 days, // 15 Days
isComplete: false,
price: 4
});
phaseInfo[4] = Phases({
tokenLimit: 100_000_000 * tokenDecimal,
tokenSold: 0,
startTime: phaseInfo[3].expirationTimestamp,
expirationTimestamp: phaseInfo[3].expirationTimestamp + 15 days, // 15 Days
isComplete: false,
price: 5
});
phaseInfo[5] = Phases({
tokenLimit: 100_000_000 * tokenDecimal,
tokenSold: 0,
startTime: phaseInfo[4].expirationTimestamp,
expirationTimestamp: phaseInfo[4].expirationTimestamp + 15 days, // 15 Days
isComplete: false,
price: 6
});
}
/* ================ BUYING TOKENS SECTION ================ */
// Receive Function
receive() external payable {
// Sending deposited currency to the receiver address
payable(receiverAddress).transfer(msg.value);
}
// Function lets user buy CHB tokens || Type 1 = BNB or ETH, Type = 2 for USDT
function buyTokens(uint8 _type, uint256 _usdtAmount)
external
payable
nonReentrant
{
require(
block.timestamp < phaseInfo[(totalPhases - 1)].expirationTimestamp,
"Buying Phases are over"
);
uint256 _buyAmount;
// If type == 1
if (_type == 1) {
_buyAmount = msg.value;
}
// If type == 2
else {
_buyAmount = _usdtAmount;
// Balance Check
require(
Token(USDTAddress).balanceOf(msg.sender) >= _buyAmount,
"User doesn't have enough balance"
);
// Allowance Check
require(
Token(USDTAddress).allowance(msg.sender, address(this)) >=
_buyAmount,
"Allowance provided is low"
);
}
// Token calculation
(uint256 _tokenAmount, uint8 _phaseNo) = calculateTokens(
_type,
_buyAmount
);
// Phase info setting
setPhaseInfo(_tokenAmount, defaultPhase);
// Transfers CHB to user
TransferHelper.safeTransfer(tokenAddress, msg.sender, _tokenAmount);
// Update Phase number and add token amount
defaultPhase = _phaseNo;
totalTokenSold += _tokenAmount;
// Calculated total USDT raised in the platform
(uint256 _amountToUSD, uint256 _typeDecimal) = cryptoValues(_type);
totalUSDTRaised += uint256((_buyAmount * _amountToUSD) / _typeDecimal);
if (_type == 1) {
// Sending deposited currency to the receiver address
payable(receiverAddress).transfer(_buyAmount);
} else {
// Sending deposited currency to the receiver address
TransferHelper.safeTransferFrom(
USDTAddress,
msg.sender,
receiverAddress,
_buyAmount
);
}
// Emits event
emit TokensBought(
msg.sender,
_buyAmount,
_tokenAmount,
uint32(block.timestamp)
);
}
// Function calculates tokens according to user's given amount
function calculateTokens(uint8 _type, uint256 _amount)
public
view
returns (uint256, uint8)
{
(uint256 _amountToUSD, uint256 _typeDecimal) = cryptoValues(_type);
uint256 _amountGivenInUsd = ((_amount * _amountToUSD) / _typeDecimal);
return
calculateTokensInternal(_type, _amountGivenInUsd, defaultPhase, 0);
}
// Internal function to calculatye tokens
function calculateTokensInternal(
uint8 _type,
uint256 _amount,
uint8 _phaseNo,
uint256 _previousTokens
) internal view returns (uint256, uint8) {
// Phases cannot exceed totalPhases
require(
_phaseNo < totalPhases,
"Not enough tokens in the contract or Phase expired"
);
Phases memory pInfo = phaseInfo[_phaseNo];
// If phase is still going on
if (pInfo.expirationTimestamp > block.timestamp) {
uint256 _tokensAmount = tokensUserWillGet(_amount, pInfo.price);
uint256 _tokensLeftToSell = (pInfo.tokenLimit + _previousTokens) -
pInfo.tokenSold;
// If token left are 0. Next phase will be executed
if (_tokensLeftToSell == 0) {
return
calculateTokensInternal(
_type,
_amount,
_phaseNo + 1,
_previousTokens
);
}
// If the phase have enough tokens left
else if (_tokensLeftToSell >= _tokensAmount) {
return (_tokensAmount, _phaseNo);
}
// If the phase doesn't have enough tokens
else {
_tokensAmount =
pInfo.tokenLimit +
_previousTokens -
pInfo.tokenSold;
uint256 _tokenPriceInPhase = tokenValueInPhase(
pInfo.price,
_tokensAmount
);
(
uint256 _remainingTokens,
uint8 _newPhase
) = calculateTokensInternal(
_type,
_amount - _tokenPriceInPhase,
_phaseNo + 1,
0
);
return (_remainingTokens + _tokensAmount, _newPhase);
}
}
// In case the phase is expired. New will begin after sending the left tokens to the next phase
else {
uint256 _remainingTokens = pInfo.tokenLimit - pInfo.tokenSold;
return
calculateTokensInternal(
_type,
_amount,
_phaseNo + 1,
_remainingTokens + _previousTokens
);
}
}
// Returns the value of tokens in the phase in dollors
function tokenValueInPhase(uint32 _price, uint256 _tokenAmount)
internal
view
returns (uint256)
{
return ((_tokenAmount * uint256(_price) * (10**8)) /
(100 * tokenDecimal));
}
// Tokens user will get according to the price
function tokensUserWillGet(uint256 _amount, uint32 _price)
internal
view
returns (uint256)
{
return ((_amount * tokenDecimal * 100) / ((10**8) * uint256(_price)));
}
// Returns the crypto values used
function cryptoValues(uint8 _type)
internal
view
returns (uint256, uint256)
{
uint256 _amountToUSD;
uint256 _typeDecimal;
if (_type == 1) {
_amountToUSD = OracleWrapper(BNBorETHOracleAddress).latestAnswer();
_typeDecimal = 10**18;
} else {
_amountToUSD = OracleWrapper(USDTOracleAddress).latestAnswer();
_typeDecimal = uint256(10**Token(USDTAddress).decimals());
}
return (_amountToUSD, _typeDecimal);
}
// Sets phase info according to the tokens bought
function setPhaseInfo(uint256 _tokensUserWillGet, uint8 _phaseNo) internal {
require(_phaseNo < totalPhases, "All tokens have been exhausted");
Phases storage pInfo = phaseInfo[_phaseNo];
if (block.timestamp < pInfo.expirationTimestamp) {
// when phase has more tokens than reuired
if ((pInfo.tokenLimit - pInfo.tokenSold) > _tokensUserWillGet) {
pInfo.tokenSold += _tokensUserWillGet;
}
// when phase has equal tokens as reuired
else if (
(pInfo.tokenLimit - pInfo.tokenSold) == _tokensUserWillGet
) {
pInfo.tokenSold = pInfo.tokenLimit;
pInfo.isComplete = true;
}
// when tokens required are more than left tokens in phase
else {
uint256 tokensLeft = _tokensUserWillGet -
(pInfo.tokenLimit - pInfo.tokenSold);
pInfo.tokenSold = pInfo.tokenLimit;
pInfo.isComplete = true;
setPhaseInfo(tokensLeft, _phaseNo + 1);
}
}
// if tokens left in phase afterb completion of expiration time
else {
uint256 remainingTokens = pInfo.tokenLimit - pInfo.tokenSold;
pInfo.tokenSold = pInfo.tokenLimit;
pInfo.isComplete = true;
phaseInfo[_phaseNo + 1].tokenLimit += remainingTokens;
setPhaseInfo(_tokensUserWillGet, _phaseNo + 1);
}
}
// Function sends the left over tokens to the receiving address, only after phases are over
function sendLeftoverTokensToReceiver() external onlyOwner {
require(
block.timestamp > phaseInfo[(totalPhases - 1)].expirationTimestamp,
"Phases are not over yet"
);
uint256 _balance = Token(tokenAddress).balanceOf(address(this));
require(_balance > 0, "No tokens left to send");
TransferHelper.safeTransfer(tokenAddress, receiverAddress, _balance);
}
/* ================ OTHER FUNCTIONS SECTION ================ */
// Updates USDT Address
function updateUSDTAddress(address _USDTAddress) external onlyOwner {
USDTAddress = _USDTAddress;
}
// Updates USDT Oracle Address
function updateUSDTOracleAddress(address _USDTOracleAddress)
external
onlyOwner
{
USDTOracleAddress = _USDTOracleAddress;
}
// Updates USDT Oracle Address
function updateBNBorETHOracleAddress(address _BNBorETHOracleAddress)
external
onlyOwner
{
BNBorETHOracleAddress = _BNBorETHOracleAddress;
}
// Updates Receiver Address
function updateReceiverAddress(address _receiverAddress)
external
onlyOwner
{
receiverAddress = _receiverAddress;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(
abi.encodeWithSelector(0x095ea7b3, to, value)
);
require(
success && (data.length == 0 || abi.decode(data, (bool))),
"TransferHelper::safeApprove: approve failed"
);
}
function safeTransfer(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(
abi.encodeWithSelector(0xa9059cbb, to, value)
);
require(
success && (data.length == 0 || abi.decode(data, (bool))),
"TransferHelper::safeTransfer: transfer failed"
);
}
function safeTransferFrom(
address token,
address from,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(
abi.encodeWithSelector(0x23b872dd, from, to, value)
);
require(
success && (data.length == 0 || abi.decode(data, (bool))),
"TransferHelper::transferFrom: transferFrom failed"
);
}
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(
success,
"TransferHelper::safeTransferETH: ETH transfer failed"
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
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.
*/
constructor() {
_setOwner(msg.sender);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner, "Ownable: caller is not the owner");
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
function _setOwner(address newOwner) internal {
owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
interface Token {
function decimals() external view returns (uint8);
function symbol() external view returns (string memory);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool);
function allowance(address owner, address spender)
external
view
returns (uint256);
function transferFrom(
address from,
address to,
uint256 value
) external returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
interface OracleWrapper {
function latestAnswer() external view returns (uint128);
}
|
Updates USDT Oracle Address
|
function updateBNBorETHOracleAddress(address _BNBorETHOracleAddress)
external
onlyOwner
{
BNBorETHOracleAddress = _BNBorETHOracleAddress;
}
| 10,108,055 |
./partial_match/1/0x695264D984A5E45C2d89f261C8668d6C1F7D214c/sources/IporProtocolRouter.sol
|
Gets IPOR Protocol Owner on Router return IPOR Protocol Owner address
|
function owner() external view returns (address) {
return OwnerManager.getOwner();
}
| 16,153,384 |
pragma solidity ^0.4.25;
import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol";
contract FlightSuretyData {
using SafeMath for uint256;
/********************************************************************************************/
/* DATA VARIABLES */
/********************************************************************************************/
// EMG - A mapping to have the authorized contracts that can call the Data contract.
mapping(address => uint256) authorizedCallers;
// EMG - Initial funding for the insurance is 10 ether
uint private constant INITIAL_FUNDING = 10 ether;
address private contractOwner; // Account used to deploy contract
bool private operational = true; // Blocks all state changes throughout the contract if false
// EMG - data structure for the airlines
struct Airline {
address airline;
bool isRegistered;
uint256 fundsProvided;
}
mapping(address => Airline) private airlines;
// EMG - array to store the registered airlines
address[] private registeredAirlines = new address[](0);
struct Flight {
bool isRegistered;
uint8 statusCode;
// EMG - These are the passengers of the flight that have bought an insurance
address[] passengers;
}
mapping(bytes32 => Flight) private flights;
// EMG - data structure for the insurances
struct Insurance {
bool isRegistered;
bool hasBeenPaid;
uint256 amountBought;
uint256 amountPaid;
}
// EMG - mapping from passenger-flight to insurance
mapping(bytes32 => Insurance) private insurances;
/********************************************************************************************/
/* EVENT DEFINITIONS */
/********************************************************************************************/
/**
* @dev Constructor
* The deploying account becomes contractOwner
*/
constructor
(
)
public
{
contractOwner = msg.sender;
// EMG - The first airline is registered as part of the initial deployment of the contract
airlines[msg.sender] = Airline({
airline: msg.sender,
isRegistered: true,
fundsProvided: 0
});
registeredAirlines.push(msg.sender);
}
/********************************************************************************************/
/* FUNCTION MODIFIERS */
/********************************************************************************************/
// Modifiers help avoid duplication of code. They are typically used to validate something
// before a function is allowed to be executed.
/**
* @dev Modifier that requires the "operational" boolean variable to be "true"
* This is used on all state changing functions to pause the contract in
* the event there is an issue that needs to be fixed
*/
modifier requireIsOperational()
{
require(operational, "Contract is currently not operational");
_; // All modifiers require an "_" which indicates where the function body will be added
}
/**
* @dev Modifier that requires the "ContractOwner" account to be the function caller
*/
modifier requireContractOwner()
{
require(msg.sender == contractOwner, "Caller is not contract owner");
_;
}
// EMG - A modifier to make sure the caller is authorized to call functions that require that
modifier isCallerAuthorized()
{
require(authorizedCallers[msg.sender] == 1, "Caller is not authorized");
_;
}
/********************************************************************************************/
/* UTILITY FUNCTIONS */
/********************************************************************************************/
// EMG - A function to authorize a contract to call the Data contract, and another one to deauthorize
function authorizeCaller(address dataContract) external requireContractOwner {
authorizedCallers[dataContract] = 1;
}
function deauthorizeCaller(address dataContract) external requireContractOwner {
delete authorizedCallers[dataContract];
}
/**
* @dev Get operating status of contract
*
* @return A bool that is the current operating status
*/
function isOperational()
public
view
isCallerAuthorized()
returns(bool)
{
return operational;
}
/**
* @dev Sets contract operations on/off
*
* When operational mode is disabled, all write transactions except for this one will fail
*/
function setOperatingStatus
(
bool mode
)
external
requireContractOwner()
{
operational = mode;
}
function getDataContractOwner
(
)
external
view
isCallerAuthorized()
returns(address)
{
return contractOwner;
}
// EMG - This is a helper function that can be used for such purposes as testing modifiers
function setTestingMode
(
)
public
view
requireIsOperational()
{
}
/**
* @dev Sets contract operations on/off
*
* When operational mode is disabled, all write transactions except for this one will fail
*/
// EMG - This function returns the number of airlines currently registered
function numberOfRegisteredAirlines
(
)
external
view
isCallerAuthorized()
returns(uint256)
{
return registeredAirlines.length;
}
// EMG - This function returns whether an airline is registered
function airlineIsRegistered
(
address airline
)
external
view
isCallerAuthorized()
returns(bool)
{
return airlines[airline].isRegistered;
}
// EMG - This function returns whether an airline is funded (i.e., whether it has already provided the contract
// with 10 ether or more
function airlineIsFunded
(
address airline
)
external
view
isCallerAuthorized()
returns(bool)
{
return (airlines[airline].fundsProvided >= INITIAL_FUNDING);
}
// EMG - This function returns whether a flight is registered
function flightIsRegistered
(
address airline,
string flightNumber,
uint256 timestamp
)
external
view
isCallerAuthorized()
returns(bool)
{
bytes32 flightKey = getFlightKey(airline, flightNumber, timestamp);
return (flights[flightKey].isRegistered);
}
// EMG - This function returns whether an insurance is registered
function insuranceIsRegistered
(
address passenger,
address airline,
string flightNumber,
uint256 timestamp
)
external
view
isCallerAuthorized()
returns(bool)
{
bytes32 insuranceKey = getInsuranceKey(passenger, airline, flightNumber, timestamp);
return (insurances[insuranceKey].isRegistered);
}
// EMG - This function returns whether an insurance has been paid
function insuranceHasBeenPaid
(
address passenger,
address airline,
string flightNumber,
uint256 timestamp
)
external
view
isCallerAuthorized()
returns(bool)
{
bytes32 insuranceKey = getInsuranceKey(passenger, airline, flightNumber, timestamp);
return (insurances[insuranceKey].hasBeenPaid);
}
/********************************************************************************************/
/* SMART CONTRACT FUNCTIONS */
/********************************************************************************************/
/**
* @dev Add an airline to the registration queue
* Can only be called from FlightSuretyApp contract
*
*/
function registerAirline
(
address airline
)
external
// EMG - Can only be called from FlightSuretyApp contract
isCallerAuthorized()
{
airlines[airline] = Airline({
airline: airline,
isRegistered: true,
fundsProvided: 0
});
registeredAirlines.push(airline);
}
/**
* @dev Initial funding for the insurance. Unless there are too many delayed flights
* resulting in insurance payouts, the contract should be self-sustaining
*
*/
// EMG - A registered airline can provide as many funds as it wants. However, it is not going to be
// considered funded until the amount provided is greater than or equal to 10 ether
function fund
(
address airline
)
public
payable
isCallerAuthorized()
{
require(airlines[airline].isRegistered, "Airline is not registered");
airlines[airline].fundsProvided = airlines[airline].fundsProvided.add(msg.value);
}
function registerFlight
(
address airline,
string flightNumber,
uint256 timestamp
)
external
isCallerAuthorized()
{
bytes32 flightKey = getFlightKey(airline, flightNumber, timestamp);
// EMG - STATUS_CODE_UNKNOWN = 0
flights[flightKey] = Flight({
isRegistered: true,
statusCode: 0,
passengers: new address[](0)
});
}
/**
* @dev Buy insurance for a flight
*
*/
function buy
(
address passenger,
address airline,
string flightNumber,
uint256 timestamp
)
external
payable
isCallerAuthorized()
{
bytes32 insuranceKey = getInsuranceKey(passenger, airline, flightNumber, timestamp);
insurances[insuranceKey] = Insurance({
isRegistered: true,
hasBeenPaid: false,
amountBought: msg.value,
amountPaid: 0
});
// The insured passenger is included within the list of insured passengers of the flight
bytes32 flightKey = getFlightKey(airline, flightNumber, timestamp);
flights[flightKey].passengers.push(passenger);
}
/**
* @dev Called after oracle has updated flight status
*
*/
function processFlightStatus
(
address airline,
string flightNumber,
uint256 timestamp
)
external
isCallerAuthorized()
{
creditInsurees(airline, flightNumber, timestamp);
}
/**
* @dev Credits payouts to insurees
*/
function creditInsurees
(
address airline,
string memory flightNumber,
uint256 timestamp
)
internal
{
bytes32 flightKey = getFlightKey(airline, flightNumber, timestamp);
for(uint c = 0; c < flights[flightKey].passengers.length; c++) {
bytes32 insuranceKey = getInsuranceKey(flights[flightKey].passengers[c], airline,
flightNumber, timestamp);
// The passenger is credited 1.5X the amount they paid
insurances[insuranceKey].amountPaid = insurances[insuranceKey].amountBought.mul(3).div(2);
}
}
/**
* @dev Transfers eligible payout funds to insuree
*
*/
function pay
(
address passenger,
address airline,
string flightNumber,
uint256 timestamp
)
external
isCallerAuthorized()
{
bytes32 insuranceKey = getInsuranceKey(passenger, airline, flightNumber, timestamp);
insurances[insuranceKey].hasBeenPaid = true;
passenger.transfer(insurances[insuranceKey].amountPaid);
}
function getFlightKey
(
address airline,
string memory flightNumber,
uint256 timestamp
)
internal
pure
returns(bytes32)
{
return keccak256(abi.encodePacked(airline, flightNumber, timestamp));
}
// EMG - Calculation of the key of the insurances mapping
function getInsuranceKey
(
address passenger,
address airline,
string memory flightNumber,
uint256 timestamp
)
internal
pure
returns(bytes32)
{
return keccak256(abi.encodePacked(passenger, airline, flightNumber, timestamp));
}
/**
* @dev Fallback function for funding smart contract.
*
*/
// EMG - Even though it is not the intended procedure to provide funds to the Data contract,
// it is possible to call the fallback function in the Data Contract. This will cause the fund
// function to be executed
function()
external
payable
{
fund(msg.sender);
}
}
|
Get operating status of contract return A bool that is the current operating status/
|
function isOperational()
public
view
isCallerAuthorized()
returns(bool)
{
return operational;
}
| 13,019,180 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IStakingRewardsVault.sol";
import "../commons/MetaTransactionsMixin.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
/**
* @dev {StakingManager}:
*/
contract StakingManager is Ownable, MetaTransactionsMixin {
using SafeERC20 for IERC20;
// Info for each user.
struct UserInfo {
uint256 amount; // LP token amount the user has provided.
int256 rewardDebt; // The amount of TSX entitled to the user.
}
// Info of each staking pool.
struct PoolInfo {
uint256 relativeWeight; // Weight of the staking pool.
uint256 accTSXPerShare; // Accumulated TSX per share, times 1e18. See below.
uint256 lastRewardTime; // Last block ts that TSX distribution occurs
}
// Address of Rewards Vault.
IStakingRewardsVault public rewardsVault;
// Info of each pool.
PoolInfo[] public poolInfo;
// Address of the LP token for each pool.
IERC20[] public lpToken;
// Info of each user that stakes LP tokens.
mapping (uint256 => mapping (address => UserInfo)) public userInfo;
// Tokens added
mapping (address => bool) public addedTokens;
// Total weight. Must be the sum of all relative weight in all pools.
uint256 public totalWeight;
uint256 public claimablePerSecond;
uint256 private constant ACC_TSX_PRECISION = 1e18;
// Events
event Stake(
address indexed user,
uint256 indexed pid,
uint256 amount
);
event Unstake(
address indexed user,
uint256 indexed pid,
uint256 amount
);
event EmergencyUnstake(
address indexed user,
uint256 indexed pid,
uint256 amount
);
event Claim(
address indexed user,
uint256 indexed pid,
uint256 amount
);
event LogAddPool(
uint256 indexed pid,
uint256 relativeWeight,
address indexed lpToken
);
event LogSetPoolWeight(
uint256 indexed pid,
uint256 relativeWeight
);
event LogUpdatePool(
uint256 indexed pid,
uint256 lastRewardTime,
uint256 lpSupply,
uint256 accTSXPerShare
);
event LogClaimablePerSecond(uint256 claimablePerSecond);
/**
* @dev constructor
* @param _rewardsVault reward token address
*/
constructor(address _rewardsVault) Ownable() {
rewardsVault = IStakingRewardsVault(_rewardsVault);
}
/**
* @dev Returns the number of pools.
*/
function poolLength() public view returns (uint256) {
return poolInfo.length;
}
/**
* @dev Sets RewardVault
* @param _rewardsVault reward token address
*/
function setStakingRewardsVault(address _rewardsVault) external onlyOwner {
rewardsVault = IStakingRewardsVault(_rewardsVault);
}
/**
* @dev Adds a new LP. 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 _relativeWeight amount of TSX to distribute per block.
* @param _lpToken Address of the LP ERC-20 token.
*/
function addPool(uint256 _relativeWeight, address _lpToken) external onlyOwner {
require(
addedTokens[_lpToken] == false,
"StakingManager(): Token already added"
);
totalWeight += _relativeWeight;
lpToken.push(IERC20(_lpToken));
poolInfo.push(
PoolInfo({
relativeWeight: _relativeWeight,
lastRewardTime: block.timestamp,
accTSXPerShare: 0
})
);
addedTokens[_lpToken] = true;
emit LogAddPool(
lpToken.length - 1,
_relativeWeight,
_lpToken
);
}
/**
* @dev Update the given pool's TSX allocation point.
* Can only be called by the owner.
* @param _pid The index of the pool. See `poolInfo`.
* @param _relativeWeight New AP of the pool.
*/
function setPoolWeight(uint256 _pid, uint256 _relativeWeight) external onlyOwner {
totalWeight -= poolInfo[_pid].relativeWeight;
totalWeight += _relativeWeight;
poolInfo[_pid].relativeWeight = _relativeWeight;
emit LogSetPoolWeight(
_pid,
_relativeWeight
);
}
/**
* @dev Sets the tsx per second to be distributed. Can only be called by the owner.
* @param _claimablePerSecond The amount of TSX to be distributed per second.
*/
function setClaimablePerSecond(uint256 _claimablePerSecond) external onlyOwner {
claimablePerSecond = _claimablePerSecond;
emit LogClaimablePerSecond(_claimablePerSecond);
}
/**
* @dev 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.timestamp <= pool.lastRewardTime) {
return pool;
}
uint256 lpSupply = lpToken[_pid].balanceOf(address(this));
if (lpSupply > 0) {
uint256 time = block.timestamp - pool.lastRewardTime;
uint256 tsxReward = time * claimablePerSecond * pool.relativeWeight / totalWeight;
pool.accTSXPerShare += tsxReward * ACC_TSX_PRECISION / lpSupply;
}
pool.lastRewardTime = block.timestamp;
poolInfo[_pid] = pool;
emit LogUpdatePool(
_pid,
pool.lastRewardTime,
lpSupply,
pool.accTSXPerShare
);
}
/**
* @dev 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]);
}
}
/**
* @dev Stake LP tokens for TSX allocation.
* @param _pid The index of the pool. See `poolInfo`.
* @param _amount LP token amount to deposit.
*/
function stake(uint256 _pid, uint256 _amount) public {
address senderAddr = msgSender();
PoolInfo memory pool = updatePool(_pid);
UserInfo storage user = userInfo[_pid][senderAddr];
// Effects
user.amount += _amount;
user.rewardDebt += int256(_amount * pool.accTSXPerShare / ACC_TSX_PRECISION);
// Transfer LP tokens
lpToken[_pid].safeTransferFrom(
senderAddr,
address(this),
_amount
);
emit Stake(senderAddr, _pid, _amount);
}
/**
* @dev Unstake LP tokens.
* @param _pid The index of the pool. See `poolInfo`.
* @param _amount LP token amount to unstake.
*/
function unstake(uint256 _pid, uint256 _amount) public {
address senderAddr = msgSender();
PoolInfo memory pool = updatePool(_pid);
UserInfo storage user = userInfo[_pid][senderAddr];
// Effects
user.rewardDebt -= int256(_amount * pool.accTSXPerShare / ACC_TSX_PRECISION);
user.amount -= _amount;
// Unstake LP tokens
lpToken[_pid].safeTransfer(senderAddr, _amount);
emit Unstake(senderAddr, _pid, _amount);
}
/**
* @dev Claim proceeds for transaction sender to `to`.
* @param _pid The index of the pool. See `poolInfo`.
*/
function claim(uint256 _pid) public {
address senderAddr = msgSender();
PoolInfo memory pool = updatePool(_pid);
UserInfo storage user = userInfo[_pid][senderAddr];
int256 accumulatedTSX = int256(user.amount * pool.accTSXPerShare / ACC_TSX_PRECISION);
uint256 pendingTSX = uint256(accumulatedTSX - user.rewardDebt);
// Effects
user.rewardDebt = accumulatedTSX;
// Rewards
rewardsVault.sendRewards(senderAddr, pendingTSX);
emit Claim(senderAddr, _pid, pendingTSX);
}
/**
* @dev Unstake LP tokens and claim proceeds for transaction sender to `to`.
* @param _pid The index of the pool. See `poolInfo`.
* @param _amount LP token amount to unstake.
*/
function unstakeAndClaim(uint256 _pid, uint256 _amount) public {
address senderAddr = msgSender();
PoolInfo memory pool = updatePool(_pid);
UserInfo storage user = userInfo[_pid][senderAddr];
int256 accumulatedTSX = int256(user.amount * pool.accTSXPerShare / ACC_TSX_PRECISION);
uint256 pendingTSX = uint256(accumulatedTSX - user.rewardDebt);
// Effects
user.rewardDebt = accumulatedTSX - int256(_amount * pool.accTSXPerShare / ACC_TSX_PRECISION);
user.amount -= _amount;
// Reward
rewardsVault.sendRewards(senderAddr, pendingTSX);
// Unstake LP tokens
lpToken[_pid].safeTransfer(senderAddr, _amount);
emit Unstake(senderAddr, _pid, _amount);
emit Claim(senderAddr, _pid, pendingTSX);
}
/**
* @dev Unstake without caring about rewards. EMERGENCY ONLY.
* @param _pid The index of the pool. See `poolInfo`.
*/
function emergencyUnstake(uint256 _pid) public {
address senderAddr = msgSender();
UserInfo storage user = userInfo[_pid][senderAddr];
uint256 amount = user.amount;
user.amount = 0;
user.rewardDebt = 0;
// Unstake LP tokens
lpToken[_pid].safeTransfer(senderAddr, amount);
emit EmergencyUnstake(senderAddr, _pid, amount);
}
/**
* @dev View function to see pending TSX on frontend.
* @param _pid The index of the pool. See `poolInfo`.
* @param _user Address of user.
* @return pending TSX reward for a given user.
*/
function pendingRewards(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo memory pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accTSXPerShare = pool.accTSXPerShare;
uint256 lpSupply = lpToken[_pid].balanceOf(address(this));
if (block.timestamp > pool.lastRewardTime && lpSupply != 0) {
uint256 time = block.timestamp - pool.lastRewardTime;
uint256 tsxReward = time * claimablePerSecond * pool.relativeWeight / totalWeight;
accTSXPerShare += tsxReward * ACC_TSX_PRECISION / lpSupply;
}
return uint256(
int256(user.amount * accTSXPerShare / ACC_TSX_PRECISION) - user.rewardDebt
);
}
}
|
Update reward variables of the given pool. _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.timestamp <= pool.lastRewardTime) {
return pool;
}
uint256 lpSupply = lpToken[_pid].balanceOf(address(this));
if (lpSupply > 0) {
uint256 time = block.timestamp - pool.lastRewardTime;
uint256 tsxReward = time * claimablePerSecond * pool.relativeWeight / totalWeight;
pool.accTSXPerShare += tsxReward * ACC_TSX_PRECISION / lpSupply;
}
pool.lastRewardTime = block.timestamp;
poolInfo[_pid] = pool;
emit LogUpdatePool(
_pid,
pool.lastRewardTime,
lpSupply,
pool.accTSXPerShare
);
}
| 13,138,813 |
./partial_match/97/0xd2d39bC20A430Fa8CB4bFdF87A2E253Aa444Fc7C/sources/BondV2.sol
|
============================== HELPERS ================================
|
function assetListedCount() public view returns (uint256 count){
return listedBondAssets.length;
}
| 11,437,630 |
./full_match/44787/0x50167A410307aF7c7fCC05aD97c4B35B1E757Aae/sources/src/SpiralsStaking.sol
|
Helper function for locking CELO
|
function lock(uint256 _value) internal {
require(_value > 0, "LOCKING_ZERO");
}
| 13,242,876 |
pragma solidity ^0.4.24;
/** ----------------------MonetaryCoin V1.0.0 ------------------------*/
/**
* Homepage: https://MonetaryCoin.org Distribution: https://MonetaryCoin.io
*
* Full source code: https://github.com/Monetary-Foundation/MonetaryCoin
*
* Licenced MIT - The Monetary Foundation 2018
*
*/
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender)
public view returns (uint256);
function transferFrom(address from, address to, uint256 value)
public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(
address _spender,
uint _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(
address _spender,
uint _subtractedValue
)
public
returns (bool)
{
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* @title 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;
}
}
/**
* @title MineableToken
* @dev ERC20 Token with Pos mining.
* The blockReward_ is controlled by a GDP oracle tied to the national identity or currency union identity of the subject MonetaryCoin.
* This type of mining will be used during both the initial distribution period and when GDP growth is positive.
* For mining during negative growth period please refer to MineableM5Token.sol.
* Unlike standard erc20 token, the totalSupply is sum(all user balances) + totalStake instead of sum(all user balances).
*/
contract MineableToken is MintableToken {
event Commit(address indexed from, uint value,uint atStake, int onBlockReward);
event Withdraw(address indexed from, uint reward, uint commitment);
uint256 totalStake_ = 0;
int256 blockReward_; //could be positive or negative according to GDP
struct Commitment {
uint256 value; // value commited to mining
uint256 onBlockNumber; // commitment done on block
uint256 atStake; // stake during commitment
int256 onBlockReward;
}
mapping( address => Commitment ) miners;
/**
* @dev commit _value for minning
* @notice the _value will be substructed from user balance and added to the stake.
* if user previously commited, add to an existing commitment.
* this is done by calling withdraw() then commit back previous commit + reward + new commit
* @param _value The amount to be commited.
* @return the commit value: _value OR prevCommit + reward + _value
*/
function commit(uint256 _value) public returns (uint256 commitmentValue) {
require(0 < _value);
require(_value <= balances[msg.sender]);
commitmentValue = _value;
uint256 prevCommit = miners[msg.sender].value;
//In case user already commited, withdraw and recommit
// new commitment value: prevCommit + reward + _value
if (0 < prevCommit) {
// withdraw Will revert if reward is negative
uint256 prevReward;
(prevReward, prevCommit) = withdraw();
commitmentValue = prevReward.add(prevCommit).add(_value);
}
// sub will revert if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(commitmentValue);
emit Transfer(msg.sender, address(0), commitmentValue);
totalStake_ = totalStake_.add(commitmentValue);
miners[msg.sender] = Commitment(
commitmentValue, // Commitment.value
block.number, // onBlockNumber
totalStake_, // atStake = current stake + commitments value
blockReward_ // onBlockReward
);
emit Commit(msg.sender, commitmentValue, totalStake_, blockReward_); // solium-disable-line
return commitmentValue;
}
/**
* @dev withdraw reward
* @return {
"uint256 reward": the new supply
"uint256 commitmentValue": the commitment to be returned
}
*/
function withdraw() public returns (uint256 reward, uint256 commitmentValue) {
require(miners[msg.sender].value > 0);
//will revert if reward is negative:
reward = getReward(msg.sender);
Commitment storage commitment = miners[msg.sender];
commitmentValue = commitment.value;
uint256 withdrawnSum = commitmentValue.add(reward);
totalStake_ = totalStake_.sub(commitmentValue);
totalSupply_ = totalSupply_.add(reward);
balances[msg.sender] = balances[msg.sender].add(withdrawnSum);
emit Transfer(address(0), msg.sender, commitmentValue.add(reward));
delete miners[msg.sender];
emit Withdraw(msg.sender, reward, commitmentValue); // solium-disable-line
return (reward, commitmentValue);
}
/**
* @dev Calculate the reward if withdraw() happans on this block
* @notice The reward is calculated by the formula:
* (numberOfBlocks) * (effectiveBlockReward) * (commitment.value) / (effectiveStake)
* effectiveBlockReward is the average between the block reward during commit and the block reward during the call
* effectiveStake is the average between the stake during the commit and the stake during call (liniar aproximation)
* @return An uint256 representing the reward amount
*/
function getReward(address _miner) public view returns (uint256) {
if (miners[_miner].value == 0) {
return 0;
}
Commitment storage commitment = miners[_miner];
int256 averageBlockReward = signedAverage(commitment.onBlockReward, blockReward_);
require(0 <= averageBlockReward);
uint256 effectiveBlockReward = uint256(averageBlockReward);
uint256 effectiveStake = average(commitment.atStake, totalStake_);
uint256 numberOfBlocks = block.number.sub(commitment.onBlockNumber);
uint256 miningReward = numberOfBlocks.mul(effectiveBlockReward).mul(commitment.value).div(effectiveStake);
return miningReward;
}
/**
* @dev Calculate the average of two integer numbers
* @notice 1.5 will be rounded toward zero
* @return An uint256 representing integer average
*/
function average(uint256 a, uint256 b) public pure returns (uint256) {
return a.add(b).div(2);
}
/**
* @dev Calculate the average of two signed integers numbers
* @notice 1.5 will be toward zero
* @return An int256 representing integer average
*/
function signedAverage(int256 a, int256 b) public pure returns (int256) {
int256 ans = a + b;
if (a > 0 && b > 0 && ans <= 0) {
require(false);
}
if (a < 0 && b < 0 && ans >= 0) {
require(false);
}
return ans / 2;
}
/**
* @dev Gets the commitment of the specified address.
* @param _miner The address to query the the commitment Of
* @return the amount commited.
*/
function commitmentOf(address _miner) public view returns (uint256) {
return miners[_miner].value;
}
/**
* @dev Gets the all fields for the commitment of the specified address.
* @param _miner The address to query the the commitment Of
* @return {
"uint256 value": the amount commited.
"uint256 onBlockNumber": block number of commitment.
"uint256 atStake": stake when commited.
"int256 onBlockReward": block reward when commited.
}
*/
function getCommitment(address _miner) public view
returns (
uint256 value, // value commited to mining
uint256 onBlockNumber, // commited on block
uint256 atStake, // stake during commit
int256 onBlockReward // block reward during commit
)
{
value = miners[_miner].value;
onBlockNumber = miners[_miner].onBlockNumber;
atStake = miners[_miner].atStake;
onBlockReward = miners[_miner].onBlockReward;
}
/**
* @dev the total stake
* @return the total stake
*/
function totalStake() public view returns (uint256) {
return totalStake_;
}
/**
* @dev the block reward
* @return the current block reward
*/
function blockReward() public view returns (int256) {
return blockReward_;
}
}
/**
* @title GDPOraclizedToken
* @dev This is an interface for the GDP Oracle to control the mining rate.
* For security reasons, two distinct functions were created:
* setPositiveGrowth() and setNegativeGrowth()
*/
contract GDPOraclizedToken is MineableToken {
event GDPOracleTransferred(address indexed previousOracle, address indexed newOracle);
event BlockRewardChanged(int oldBlockReward, int newBlockReward);
address GDPOracle_;
address pendingGDPOracle_;
/**
* @dev Modifier Throws if called by any account other than the GDPOracle.
*/
modifier onlyGDPOracle() {
require(msg.sender == GDPOracle_);
_;
}
/**
* @dev Modifier throws if called by any account other than the pendingGDPOracle.
*/
modifier onlyPendingGDPOracle() {
require(msg.sender == pendingGDPOracle_);
_;
}
/**
* @dev Allows the current GDPOracle to transfer control to a newOracle.
* The new GDPOracle need to call claimOracle() to finalize
* @param newOracle The address to transfer ownership to.
*/
function transferGDPOracle(address newOracle) public onlyGDPOracle {
pendingGDPOracle_ = newOracle;
}
/**
* @dev Allows the pendingGDPOracle_ address to finalize the transfer.
*/
function claimOracle() onlyPendingGDPOracle public {
emit GDPOracleTransferred(GDPOracle_, pendingGDPOracle_);
GDPOracle_ = pendingGDPOracle_;
pendingGDPOracle_ = address(0);
}
/**
* @dev Chnage block reward according to GDP
* @param newBlockReward the new block reward in case of possible growth
*/
function setPositiveGrowth(int256 newBlockReward) public onlyGDPOracle returns(bool) {
// protect against error / overflow
require(0 <= newBlockReward);
emit BlockRewardChanged(blockReward_, newBlockReward);
blockReward_ = newBlockReward;
}
/**
* @dev Chnage block reward according to GDP
* @param newBlockReward the new block reward in case of negative growth
*/
function setNegativeGrowth(int256 newBlockReward) public onlyGDPOracle returns(bool) {
require(newBlockReward < 0);
emit BlockRewardChanged(blockReward_, newBlockReward);
blockReward_ = newBlockReward;
}
/**
* @dev get GDPOracle
* @return the address of the GDPOracle
*/
function GDPOracle() public view returns (address) { // solium-disable-line mixedcase
return GDPOracle_;
}
/**
* @dev get GDPOracle
* @return the address of the GDPOracle
*/
function pendingGDPOracle() public view returns (address) { // solium-disable-line mixedcase
return pendingGDPOracle_;
}
}
/**
* @title MineableM5Token
* @notice This contract adds the ability to mine for M5 tokens when growth is negative.
* The M5 token is a distinct ERC20 token that may be obtained only following a period of negative GDP growth.
* The logic for M5 mining will be finalized in advance of the close of the initial distribution period β see the White Paper for additional details.
* After upgrading this contract with the final M5 logic, finishUpgrade() will be called to permanently seal the upgradeability of the contract.
*/
contract MineableM5Token is GDPOraclizedToken {
event M5TokenUpgrade(address indexed oldM5Token, address indexed newM5Token);
event M5LogicUpgrade(address indexed oldM5Logic, address indexed newM5Logic);
event FinishUpgrade();
// The M5 token contract
address M5Token_;
// The contract to manage M5 mining logic.
address M5Logic_;
// The address which controls the upgrade process
address upgradeManager_;
// When isUpgradeFinished_ is true, no more upgrades is allowed
bool isUpgradeFinished_ = false;
/**
* @dev get the M5 token address
* @return M5 token address
*/
function M5Token() public view returns (address) {
return M5Token_;
}
/**
* @dev get the M5 logic contract address
* @return M5 logic contract address
*/
function M5Logic() public view returns (address) {
return M5Logic_;
}
/**
* @dev get the upgrade manager address
* @return the upgrade manager address
*/
function upgradeManager() public view returns (address) {
return upgradeManager_;
}
/**
* @dev get the upgrade status
* @return the upgrade status. if true, no more upgrades are possible.
*/
function isUpgradeFinished() public view returns (bool) {
return isUpgradeFinished_;
}
/**
* @dev Throws if called by any account other than the GDPOracle.
*/
modifier onlyUpgradeManager() {
require(msg.sender == upgradeManager_);
require(!isUpgradeFinished_);
_;
}
/**
* @dev Allows to set the M5 token contract
* @param newM5Token The address of the new contract
*/
function upgradeM5Token(address newM5Token) public onlyUpgradeManager { // solium-disable-line
require(newM5Token != address(0));
emit M5TokenUpgrade(M5Token_, newM5Token);
M5Token_ = newM5Token;
}
/**
* @dev Allows the upgrade the M5 logic contract
* @param newM5Logic The address of the new contract
*/
function upgradeM5Logic(address newM5Logic) public onlyUpgradeManager { // solium-disable-line
require(newM5Logic != address(0));
emit M5LogicUpgrade(M5Logic_, newM5Logic);
M5Logic_ = newM5Logic;
}
/**
* @dev Allows the upgrade the M5 logic contract and token at the same transaction
* @param newM5Token The address of a new M5 token
* @param newM5Logic The address of the new contract
*/
function upgradeM5(address newM5Token, address newM5Logic) public onlyUpgradeManager { // solium-disable-line
require(newM5Token != address(0));
require(newM5Logic != address(0));
emit M5TokenUpgrade(M5Token_, newM5Token);
emit M5LogicUpgrade(M5Logic_, newM5Logic);
M5Token_ = newM5Token;
M5Logic_ = newM5Logic;
}
/**
* @dev Function to dismiss the upgrade capability
* @return True if the operation was successful.
*/
function finishUpgrade() onlyUpgradeManager public returns (bool) {
isUpgradeFinished_ = true;
emit FinishUpgrade();
return true;
}
/**
* @dev Calculate the reward if withdrawM5() happans on this block
* @notice This is a wrapper, which calls and return result from M5Logic
* the actual logic is found in the M5Logic contract
* @param _miner The address of the _miner
* @return An uint256 representing the reward amount
*/
function getM5Reward(address _miner) public view returns (uint256) {
require(M5Logic_ != address(0));
if (miners[_miner].value == 0) {
return 0;
}
// check that effective block reward is indeed negative
require(signedAverage(miners[_miner].onBlockReward, blockReward_) < 0);
// return length (bytes)
uint32 returnSize = 32;
// target contract
address target = M5Logic_;
// method signeture for target contract
bytes32 signature = keccak256("getM5Reward(address)");
// size of calldata for getM5Reward function: 4 for signeture and 32 for one variable (address)
uint32 inputSize = 4 + 32;
// variable to check delegatecall result (success or failure)
uint8 callResult;
// result from target.getM5Reward()
uint256 result;
assembly { // solium-disable-line
// return _dest.delegatecall(msg.data)
mstore(0x0, signature) // 4 bytes of method signature
mstore(0x4, _miner) // 20 bytes of address
// delegatecall(g, a, in, insize, out, outsize) - call contract at address a with input mem[in..(in+insize))
// providing g gas and v wei and output area mem[out..(out+outsize)) returning 0 on error (eg. out of gas) and 1 on success
// keep caller and callvalue
callResult := delegatecall(sub(gas, 10000), target, 0x0, inputSize, 0x0, returnSize)
switch callResult
case 0
{ revert(0,0) }
default
{ result := mload(0x0) }
}
return result;
}
event WithdrawM5(address indexed from,uint commitment, uint M5Reward);
/**
* @dev withdraw M5 reward, only appied to mining when GDP is negative
* @return {
"uint256 reward": the new M5 supply
"uint256 commitmentValue": the commitment to be returned
}
*/
function withdrawM5() public returns (uint256 reward, uint256 commitmentValue) {
require(M5Logic_ != address(0));
require(M5Token_ != address(0));
require(miners[msg.sender].value > 0);
// will revert if reward is positive
reward = getM5Reward(msg.sender);
commitmentValue = miners[msg.sender].value;
require(M5Logic_.delegatecall(bytes4(keccak256("withdrawM5()")))); // solium-disable-line
return (reward,commitmentValue);
}
//triggered when user swaps m5Value of M5 tokens for value of regular tokens.
event Swap(address indexed from, uint256 M5Value, uint256 value);
/**
* @dev swap M5 tokens back to regular tokens when GDP is back to positive
* @param _value The amount of M5 tokens to swap for regular tokens
* @return true
*/
function swap(uint256 _value) public returns (bool) {
require(M5Logic_ != address(0));
require(M5Token_ != address(0));
require(M5Logic_.delegatecall(bytes4(keccak256("swap(uint256)")),_value)); // solium-disable-line
return true;
}
}
/**
* @title MCoin
* @dev The MonetaryCoin contract
* The MonetaryCoin contract allows for the creation of a new monetary coin.
* The supply of a minable coin in a period is defined by an oracle that reports GDP data from the country related to that coin.
* Example: If the GDP of a given country grows by 3%, then 3% more coins will be available for forging (i.e. mining) in the next period.
* Coins will be distributed by the proof of stake forging mechanism both during and after the initial distribution period.
* The Proof of stake forging is defined by the MineableToken.sol contract.
*/
contract MCoin is MineableM5Token {
string public name; // solium-disable-line uppercase
string public symbol; // solium-disable-line uppercase
uint8 public constant decimals = 18; // solium-disable-line uppercase
constructor(
string tokenName,
string tokenSymbol,
uint256 blockReward, // will be transformed using toDecimals()
address GDPOracle,
address upgradeManager
) public
{
require(GDPOracle != address(0));
require(upgradeManager != address(0));
name = tokenName;
symbol = tokenSymbol;
blockReward_ = toDecimals(blockReward);
emit BlockRewardChanged(0, blockReward_);
GDPOracle_ = GDPOracle;
emit GDPOracleTransferred(0x0, GDPOracle_);
M5Token_ = address(0);
M5Logic_ = address(0);
upgradeManager_ = upgradeManager;
}
function toDecimals(uint256 _value) pure internal returns (int256 value) {
value = int256 (
_value.mul(10 ** uint256(decimals))
);
assert(0 < value);
return value;
}
}
|
Allows the current GDPOracle to transfer control to a newOracle. The new GDPOracle need to call claimOracle() to finalize newOracle The address to transfer ownership to./
|
function transferGDPOracle(address newOracle) public onlyGDPOracle {
pendingGDPOracle_ = newOracle;
}
| 911,000 |
./partial_match/3/0xd3443DCf2670c153f4959A2B557810cD68E73680/sources/PopChef.sol
|
Update pending info
|
function updatePendingInfo(address[] memory _addresses, uint16[] memory _multiplier) public {
require(msg.sender == devaddr, "dev: wut?");
require(_addresses.length == _multiplier.length, "pendingInfo: length?");
require(startTime + 365 days >= now, "pendingInfo: rewards over");
if ( startTime <= now && now < startTime + 90 days && popPerBlock != popPerBlockCycleOne) {
popPerBlock = popPerBlockCycleOne;
popPerBlock = popPerBlockCycleTwo;
popPerBlock = popPerBlockCycleThree;
popPerBlock = popPerBlockCycleFour;
}
for (uint i = 0; i < _addresses.length; i++) {
UserInfo storage user = userInfo[_addresses[i]];
user.rewardMultiplier = user.rewardMultiplier.add(_multiplier[i]);
}
claimableBlock = block.number;
}
| 5,167,699 |
./full_match/137/0x1f83a91719983136B7F281e778AcFf6b1186c0CB/sources/contracts/prebuilts/unaudited/airdrop/MigrateERC721.sol
|
Initiliazes the contract, like a constructor.
|
function initialize(address[] memory _trustedForwarders) external initializer {
__ERC2771Context_init_unchained(_trustedForwarders);
}
Airdrop logic
| 4,757,588 |
./full_match/1/0x032Ba44EB2DB607d2F9424b90e191BbFb51152A1/sources/contracts/TwabRewards.sol
|
_userClaimedEpochs Record of epochs already claimed by the user _epochId Epoch id to check return true if the rewards have already been claimed for the given epoch, false otherwise/
|
function _isClaimedEpoch(uint256 _userClaimedEpochs, uint8 _epochId)
internal
pure
returns (bool)
{
return (_userClaimedEpochs >> _epochId) & uint256(1) == 1;
}
| 16,513,578 |
//Address: 0x2a203d5ab550d1abf1d40a25883c0ce4170ab0f0
//Contract name: Crowdsale
//Balance: 0 Ether
//Verification Date: 12/10/2017
//Transacion Count: 4
// CODE STARTS HERE
pragma solidity ^0.4.11;
/**
* @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;
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 Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale.
* Crowdsales have a start and end timestamps, where investors can make
* token purchases and the crowdsale will assign them tokens based
* on a token per ETH rate. Funds collected are forwarded to a wallet
* as they arrive.
*/
contract token { function transfer(address receiver, uint amount){ } }
contract Crowdsale {
using SafeMath for uint256;
// uint256 durationInMinutes;
// address where funds are collected
address public wallet;
// token address
address public addressOfTokenUsedAsReward;
uint256 public price = 200;//initial price
token tokenReward;
mapping (address => uint) public contributions;
// start and end timestamps where investments are allowed (both inclusive)
// uint256 public startTime;
// uint256 public endTime;
// amount of raised money in wei
uint256 public weiRaised;
uint256 public tokensSold;
/**
* 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);
function Crowdsale() {
//DO NOT FORGET TO CHANGE THIS
//This is the wallet where all the ETH will go!
wallet = 0x8c7E29FE448ea7E09584A652210fE520f992cE64;//this should be Filips wallet!
// durationInMinutes = _durationInMinutes;
//Here will come the checksum address we got
addressOfTokenUsedAsReward = 0xA7352F9d1872D931b3F9ff3058025c4aE07EF888; //address of the token contract
//web3.toChecksumAddress is needed here in most cases.
tokenReward = token(addressOfTokenUsedAsReward);
}
bool public started = false;
function startSale(){
if (msg.sender != wallet) throw;
started = true;
}
function stopSale(){
if(msg.sender != wallet) throw;
started = false;
}
function setPrice(uint256 _price){
if(msg.sender != wallet) throw;
price = _price;
}
// fallback function can be used to buy tokens
function () payable {
buyTokens(msg.sender);
}
// low level token purchase function
function buyTokens(address beneficiary) payable {
require(beneficiary != 0x0);
require(validPurchase());
uint256 weiAmount = msg.value;
if(tokensSold < 10000*10**6){
price = 300;
}else if(tokensSold < 20000*10**6){
price = 284;
}else if(tokensSold < 30000*10**6){
price = 269;
}else if(tokensSold < 40000*10**6){
price = 256;
}else if(tokensSold < 50000*10**6){
price = 244;
}else if(tokensSold < 60000*10**6){
price = 233;
}else if(tokensSold < 70000*10**6){
price = 223;
}else if(tokensSold < 80000*10**6){
price = 214;
}else if(tokensSold < 90000*10**6){
price = 205;
}else if(tokensSold < 100000*10**6){
price = 197;
}else if(tokensSold < 110000*10**6){
price = 189;
}else if(tokensSold < 120000*10**6){
price = 182;
}else if(tokensSold < 130000*10**6){
price = 175;
}else if(tokensSold < 140000*10**6){
price = 168;
}else if(tokensSold < 150000*10**6){
price = 162;
}else if(tokensSold < 160000*10**6){
price = 156;
}else if(tokensSold < 170000*10**6){
price = 150;
}else if(tokensSold < 180000*10**6){
price = 145;
}else if(tokensSold < 190000*10**6){
price = 140;
}else if(tokensSold < 200000*10**6){
price = 135;
}else if(tokensSold < 210000*10**6){
price = 131;
}else if(tokensSold < 220000*10**6){
price = 127;
}else if(tokensSold < 230000*10**6){
price = 123;
}else if(tokensSold < 240000*10**6){
price = 120;
}else if(tokensSold < 250000*10**6){
price = 117;
}else if(tokensSold < 260000*10**6){
price = 114;
}else if(tokensSold < 270000*10**6){
price = 111;
}else if(tokensSold < 280000*10**6){
price = 108;
}else if(tokensSold < 290000*10**6){
price = 105;
}else if(tokensSold < 300000*10**6){
price = 102;
}else if(tokensSold < 310000*10**6){
price = 100;
}else if(tokensSold < 320000*10**6){
price = 98;
}else if(tokensSold < 330000*10**6){
price = 96;
}else if(tokensSold < 340000*10**6){
price = 94;
}else if(tokensSold < 350000*10**6){
price = 92;
}else if(tokensSold < 360000*10**6){
price = 90;
}else if(tokensSold < 370000*10**6){
price = 88;
}else if(tokensSold < 380000*10**6){
price = 86;
}else if(tokensSold < 390000*10**6){
price = 84;
}else if(tokensSold < 400000*10**6){
price = 82;
}else if(tokensSold < 410000*10**6){
price = 80;
}else if(tokensSold < 420000*10**6){
price = 78;
}else if(tokensSold < 430000*10**6){
price = 76;
}else if(tokensSold < 440000*10**6){
price = 74;
}else if(tokensSold < 450000*10**6){
price = 72;
}else if(tokensSold < 460000*10**6){
price = 70;
}else if(tokensSold < 470000*10**6){
price = 68;
}else if(tokensSold < 480000*10**6){
price = 66;
}else if(tokensSold < 490000*10**6){
price = 64;
}else if(tokensSold < 500000*10**6){
price = 62;
}else if(tokensSold < 510000*10**6){
price = 60;
}else if(tokensSold < 520000*10**6){
price = 58;
}else if(tokensSold < 530000*10**6){
price = 57;
}else if(tokensSold < 540000*10**6){
price = 56;
}else if(tokensSold < 550000*10**6){
price = 55;
}else if(tokensSold < 560000*10**6){
price = 54;
}else if(tokensSold < 570000*10**6){
price = 53;
}else if(tokensSold < 580000*10**6){
price = 52;
}else if(tokensSold < 590000*10**6){
price = 51;
}else if(tokensSold < 600000*10**6){
price = 50;
}else if(tokensSold < 610000*10**6){
price = 49;
}else if(tokensSold < 620000*10**6){
price = 48;
}else if(tokensSold < 630000*10**6){
price = 47;
}else if(tokensSold < 640000*10**6){
price = 46;
}else if(tokensSold < 650000*10**6){
price = 45;
}else if(tokensSold < 660000*10**6){
price = 44;
}else if(tokensSold < 670000*10**6){
price = 43;
}else if(tokensSold < 680000*10**6){
price = 42;
}else if(tokensSold < 690000*10**6){
price = 41;
}else if(tokensSold < 700000*10**6){
price = 40;
}
//the price above is Token per ETH
// calculate token amount to be sent
uint256 tokens = (weiAmount/10**12) * price;//weiamount * price
require(tokens >= 1 * 10 ** 6); //1 token minimum
// update state
weiRaised = weiRaised.add(weiAmount);
tokenReward.transfer(beneficiary, tokens);
tokensSold = tokensSold.add(tokens);//now we can track the number of tokens sold.
TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);
forwardFunds();
}
// send ether to the fund collection wallet
// override to create custom fund forwarding mechanisms
function forwardFunds() internal {
// wallet.transfer(msg.value);
if (!wallet.send(msg.value)) {
throw;
}
}
// @return true if the transaction can buy tokens
function validPurchase() internal constant returns (bool) {
bool withinPeriod = started;
bool nonZeroPurchase = msg.value != 0;
return withinPeriod && nonZeroPurchase;
}
function withdrawTokens(uint256 _amount) {
if(msg.sender!=wallet) throw;
tokenReward.transfer(wallet,_amount);
}
}
|
event for token purchase logging purchaser who paid for the tokens beneficiary who got the tokens value weis paid for purchase amount amount of tokens purchased/DO NOT FORGET TO CHANGE THISThis is the wallet where all the ETH will go! durationInMinutes = _durationInMinutes;Here will come the checksum address we gotweb3.toChecksumAddress is needed here in most cases.
|
function Crowdsale() {
tokenReward = token(addressOfTokenUsedAsReward);
}
bool public started = false;
| 12,967,355 |
/**
* @authors: [@unknownunknown1]
* @reviewers: [@ferittuncer, @clesaege, @satello*, @mtsalenc*, @remedcu]
* @auditors: []
* @bounties: [{ link: https://github.com/kleros/kleros/issues/155, maxPayout: 100 ETH }]
* @deployments: []
* @tools: [MythX]
*/
/* solium-disable security/no-block-members */
/* solium-disable max-len */
/* solium-disable security/no-send */
pragma solidity ^0.4.26;
import "@kleros/kleros-interaction/contracts/standard/arbitration/Arbitrable.sol";
import "@kleros/kleros-interaction/contracts/libraries/CappedMath.sol";
/** @title KlerosGovernor
* Note that this contract trusts that the Arbitrator is honest and will not re-enter or modify its costs during a call.
* Also note that tx.origin should not matter in contracts called by the governor.
*/
contract KlerosGovernor is Arbitrable {
using CappedMath for uint;
/* *** Contract variables *** */
enum Status {NoDispute, DisputeCreated, Resolved}
struct Session {
Round[] rounds; // Tracks each appeal round of the dispute in the session in the form rounds[appeal].
uint ruling; // The ruling that was given in this session, if any.
uint disputeID; // ID given to the dispute of the session, if any.
uint[] submittedLists; // Tracks all lists that were submitted in a session in the form submittedLists[submissionID].
uint sumDeposit; // Sum of all submission deposits in a session (minus arbitration fees). This is used to calculate the reward.
Status status; // Status of a session.
mapping(bytes32 => bool) alreadySubmitted; // Indicates whether or not the transaction list was already submitted in order to catch duplicates in the form alreadySubmitted[listHash].
uint durationOffset; // Time in seconds that prolongs the submission period after the first submission, to give other submitters time to react.
}
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 Submission {
address submitter; // The one who submits the list.
uint deposit; // Value of the deposit paid upon submission of the list.
Transaction[] txs; // Transactions stored in the list in the form txs[_transactionIndex].
bytes32 listHash; // A hash chain of all transactions stored in the list. This is used as a unique identifier.
uint submissionTime; // The time when the list was submitted.
bool approved; // Whether the list was approved for execution or not.
uint approvalTime; // The time when the list was approved.
}
struct Round {
mapping (uint => uint) paidFees; // Tracks the fees paid by each side in this round in the form paidFees[submissionID].
mapping (uint => bool) hasPaid; // True when the side has fully paid its fees, false otherwise in the form hasPaid[submissionID].
uint feeRewards; // Sum of reimbursable fees and stake rewards available to the parties that made contributions to the side that ultimately wins a dispute.
mapping(address => mapping (uint => uint)) contributions; // Maps contributors to their contributions for each side in the form contributions[address][submissionID].
uint successfullyPaid; // Sum of all successfully paid fees paid by all sides.
}
uint constant NO_SHADOW_WINNER = uint(-1); // The value that indicates that no one has successfully paid appeal fees in a current round. It's the largest integer and not 0, because 0 can be a valid submission index.
address public deployer; // The address of the deployer of the contract.
uint public reservedETH; // Sum of contract's submission deposits and appeal fees. These funds are not to be used in the execution of transactions.
uint public submissionBaseDeposit; // The base deposit 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 executionTimeout; // Time in seconds allowed for the execution of approved lists.
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 each side 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 lastApprovalTime; // The time of the last approval of a transaction list.
uint public shadowWinner; // 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.
Submission[] public submissions; // Stores all created transaction lists. submissions[_listID].
Session[] public sessions; // Stores all submitting sessions. sessions[_session].
/* *** Modifiers *** */
modifier duringSubmissionPeriod() {
uint offset = sessions[sessions.length - 1].durationOffset;
require(now - lastApprovalTime <= submissionTimeout.addCap(offset), "Submission time has ended.");
_;
}
modifier duringApprovalPeriod() {
uint offset = sessions[sessions.length - 1].durationOffset;
require(now - lastApprovalTime > submissionTimeout.addCap(offset), "Approval time has not started yet.");
_;
}
modifier onlyByGovernor() {require(address(this) == msg.sender, "Only the governor can execute this."); _;}
/* *** Events *** */
/** @dev Emitted when a new list is submitted.
* @param _listID The index of the transaction list in the array of lists.
* @param _submitter The address that submitted the list.
* @param _session The number of the current session.
* @param _description The string in CSV format that contains labels of list's transactions.
* Note that the submitter may give bad descriptions of correct actions, but this is to be seen as UI enhancement, not a critical feature and that would play against him in case of dispute.
*/
event ListSubmitted(uint indexed _listID, address indexed _submitter, uint _session, string _description);
/** @dev Constructor.
* @param _arbitrator The arbitrator of the contract. It should support appealPeriod.
* @param _extraData Extra data for the arbitrator.
* @param _submissionBaseDeposit The base deposit required for submission.
* @param _submissionTimeout Time in seconds allocated for submitting transaction list.
* @param _executionTimeout Time in seconds after approval that allows to execute transactions of the approved list.
* @param _withdrawTimeout Time in seconds after submission that allows to withdraw submitted list.
* @param _sharedMultiplier Multiplier of the appeal cost that submitters 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 _submissionBaseDeposit,
uint _submissionTimeout,
uint _executionTimeout,
uint _withdrawTimeout,
uint _sharedMultiplier,
uint _winnerMultiplier,
uint _loserMultiplier
) public Arbitrable(_arbitrator, _extraData) {
lastApprovalTime = now;
submissionBaseDeposit = _submissionBaseDeposit;
submissionTimeout = _submissionTimeout;
executionTimeout = _executionTimeout;
withdrawTimeout = _withdrawTimeout;
sharedMultiplier = _sharedMultiplier;
winnerMultiplier = _winnerMultiplier;
loserMultiplier = _loserMultiplier;
shadowWinner = NO_SHADOW_WINNER;
sessions.length++;
deployer = msg.sender;
}
/** @dev Sets the meta evidence. Can only be called once.
* @param _metaEvidence The URI of the meta evidence file.
*/
function setMetaEvidence(string _metaEvidence) external {
require(msg.sender == deployer, "Can only be called once by the deployer of the contract.");
deployer = address(0);
emit MetaEvidence(0, _metaEvidence);
}
/** @dev Changes the value of the base deposit required for submitting a list.
* @param _submissionBaseDeposit The new value of the base deposit, in wei.
*/
function changeSubmissionDeposit(uint _submissionBaseDeposit) public onlyByGovernor {
submissionBaseDeposit = _submissionBaseDeposit;
}
/** @dev Changes the time allocated for submission.
* @param _submissionTimeout The new duration of the submission period, in seconds.
*/
function changeSubmissionTimeout(uint _submissionTimeout) public onlyByGovernor duringSubmissionPeriod {
submissionTimeout = _submissionTimeout;
}
/** @dev Changes the time allocated for list's execution.
* @param _executionTimeout The new duration of the execution timeout, in seconds.
*/
function changeExecutionTimeout(uint _executionTimeout) public onlyByGovernor {
executionTimeout = _executionTimeout;
}
/** @dev Changes the time allowed for list withdrawal.
* @param _withdrawTimeout The new duration of withdraw period, in seconds.
*/
function changeWithdrawTimeout(uint _withdrawTimeout) public onlyByGovernor {
withdrawTimeout = _withdrawTimeout;
}
/** @dev Changes the proportion of appeal fees that must be added to appeal cost when there is no winner or loser.
* @param _sharedMultiplier The new shared multiplier value in basis points.
*/
function changeSharedMultiplier(uint _sharedMultiplier) public onlyByGovernor {
sharedMultiplier = _sharedMultiplier;
}
/** @dev Changes the proportion of appeal fees that must be added to appeal cost for the winning party.
* @param _winnerMultiplier The new winner multiplier value in basis points.
*/
function changeWinnerMultiplier(uint _winnerMultiplier) public onlyByGovernor {
winnerMultiplier = _winnerMultiplier;
}
/** @dev Changes the proportion of appeal fees that must be added to appeal cost for the losing party.
* @param _loserMultiplier The new loser multiplier value in basis points.
*/
function changeLoserMultiplier(uint _loserMultiplier) public onlyByGovernor {
loserMultiplier = _loserMultiplier;
}
/** @dev Changes the arbitrator of the contract.
* @param _arbitrator The new trusted arbitrator.
* @param _arbitratorExtraData The extra data used by the new arbitrator.
*/
function changeArbitrator(Arbitrator _arbitrator, bytes _arbitratorExtraData) public onlyByGovernor duringSubmissionPeriod {
arbitrator = _arbitrator;
arbitratorExtraData = _arbitratorExtraData;
}
/** @dev Creates transaction list based on input parameters and submits it for potential approval and execution.
* Transactions must be ordered by their hash.
* @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.
* @param _description String in CSV format that describes list's transactions.
*/
function submitList (address[] _target, uint[] _value, bytes _data, uint[] _dataSize, string _description) public payable duringSubmissionPeriod {
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.");
Session storage session = sessions[sessions.length - 1];
Submission storage submission = submissions[submissions.length++];
submission.submitter = msg.sender;
// Do the assignment first to avoid creating a new variable and bypass a 'stack too deep' error.
submission.deposit = submissionBaseDeposit + arbitrator.arbitrationCost(arbitratorExtraData);
require(msg.value >= submission.deposit, "Submission deposit must be paid in full.");
// Using an array to get around the stack limit.
// 0 - List hash.
// 1 - Previous transaction hash.
// 2 - Current transaction hash.
bytes32[3] memory hashes;
uint readingPosition;
for (uint i = 0; i < _target.length; i++) {
bytes memory readData = new bytes(_dataSize[i]);
Transaction storage transaction = submission.txs[submission.txs.length++];
transaction.target = _target[i];
transaction.value = _value[i];
for (uint j = 0; j < _dataSize[i]; j++) {
readData[j] = _data[readingPosition + j];
}
transaction.data = readData;
readingPosition += _dataSize[i];
hashes[2] = keccak256(abi.encodePacked(transaction.target, transaction.value, transaction.data));
require(uint(hashes[2]) >= uint(hashes[1]), "The transactions are in incorrect order.");
hashes[0] = keccak256(abi.encodePacked(hashes[2], hashes[0]));
hashes[1] = hashes[2];
}
require(!session.alreadySubmitted[hashes[0]], "The same list was already submitted earlier.");
session.alreadySubmitted[hashes[0]] = true;
submission.listHash = hashes[0];
submission.submissionTime = now;
session.sumDeposit += submission.deposit;
session.submittedLists.push(submissions.length - 1);
if (session.submittedLists.length == 1)
session.durationOffset = now.subCap(lastApprovalTime);
emit ListSubmitted(submissions.length - 1, msg.sender, sessions.length - 1, _description);
uint remainder = msg.value - submission.deposit;
if (remainder > 0)
msg.sender.send(remainder);
reservedETH += submission.deposit;
}
/** @dev Withdraws submitted transaction list. Reimburses submission deposit.
* Withdrawal is only possible during the first half of the submission period and during withdrawPeriod seconds after the submission is made.
* @param _submissionID Submission's index in the array of submitted lists of the current sesssion.
* @param _listHash Hash of a withdrawing list.
*/
function withdrawTransactionList(uint _submissionID, bytes32 _listHash) public {
Session storage session = sessions[sessions.length - 1];
Submission storage submission = submissions[session.submittedLists[_submissionID]];
require(now - lastApprovalTime <= submissionTimeout / 2, "Lists can be withdrawn only in the first half of the initial submission period.");
// This require statement is an extra check to prevent _submissionID linking to the wrong list because of index swap during withdrawal.
require(submission.listHash == _listHash, "Provided hash doesn't correspond with submission ID.");
require(submission.submitter == msg.sender, "Can't withdraw the list created by someone else.");
require(now - submission.submissionTime <= withdrawTimeout, "Withdrawing time has passed.");
session.submittedLists[_submissionID] = session.submittedLists[session.submittedLists.length - 1];
session.alreadySubmitted[_listHash] = false;
session.submittedLists.length--;
session.sumDeposit = session.sumDeposit.subCap(submission.deposit);
msg.sender.transfer(submission.deposit);
reservedETH = reservedETH.subCap(submission.deposit);
}
/** @dev Approves a transaction list or creates a dispute if more than one list was submitted. TRUSTED.
* If nothing was submitted changes session.
*/
function executeSubmissions() public duringApprovalPeriod {
Session storage session = sessions[sessions.length - 1];
require(session.status == Status.NoDispute, "Can't approve transaction list while dispute is active.");
if (session.submittedLists.length == 0) {
lastApprovalTime = now;
session.status = Status.Resolved;
sessions.length++;
} else if (session.submittedLists.length == 1) {
Submission storage submission = submissions[session.submittedLists[0]];
submission.approved = true;
submission.approvalTime = now;
uint sumDeposit = session.sumDeposit;
session.sumDeposit = 0;
submission.submitter.send(sumDeposit);
lastApprovalTime = now;
session.status = Status.Resolved;
sessions.length++;
reservedETH = reservedETH.subCap(sumDeposit);
} else {
session.status = Status.DisputeCreated;
uint arbitrationCost = arbitrator.arbitrationCost(arbitratorExtraData);
session.disputeID = arbitrator.createDispute.value(arbitrationCost)(session.submittedLists.length, arbitratorExtraData);
session.rounds.length++;
session.sumDeposit = session.sumDeposit.subCap(arbitrationCost);
reservedETH = reservedETH.subCap(arbitrationCost);
emit Dispute(arbitrator, session.disputeID, 0, sessions.length - 1);
}
}
/** @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. TRUSTED.
* @param _submissionID Submission's index in the array of submitted lists of the current sesssion. Note that submissionID can be swapped with an ID of a withdrawn list in submission period.
*/
function fundAppeal(uint _submissionID) public payable {
Session storage session = sessions[sessions.length - 1];
require(_submissionID <= session.submittedLists.length - 1, "SubmissionID is out of bounds.");
require(session.status == Status.DisputeCreated, "No dispute to appeal.");
require(arbitrator.disputeStatus(session.disputeID) == Arbitrator.DisputeStatus.Appealable, "Dispute is not appealable.");
(uint appealPeriodStart, uint appealPeriodEnd) = arbitrator.appealPeriod(session.disputeID);
require(
now >= appealPeriodStart && now < appealPeriodEnd,
"Appeal fees must be paid within the appeal period."
);
uint winner = arbitrator.currentRuling(session.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;
}
Round storage round = session.rounds[session.rounds.length - 1];
require(!round.hasPaid[_submissionID], "Appeal fee has already been paid.");
uint appealCost = arbitrator.appealCost(session.disputeID, arbitratorExtraData);
uint totalCost = appealCost.addCap((appealCost.mulCap(multiplier)) / MULTIPLIER_DIVISOR);
// Take up to the amount necessary to fund the current round at the current costs.
uint contribution; // Amount contributed.
uint remainingETH; // Remaining ETH to send back.
(contribution, remainingETH) = calculateContribution(msg.value, totalCost.subCap(round.paidFees[_submissionID]));
round.contributions[msg.sender][_submissionID] += contribution;
round.paidFees[_submissionID] += contribution;
// Add contribution to reward when the fee funding is successful, otherwise it can be withdrawn later.
if (round.paidFees[_submissionID] >= totalCost) {
round.hasPaid[_submissionID] = true;
if (shadowWinner == NO_SHADOW_WINNER)
shadowWinner = _submissionID;
round.feeRewards += round.paidFees[_submissionID];
round.successfullyPaid += round.paidFees[_submissionID];
}
// Reimburse leftover ETH.
msg.sender.send(remainingETH);
reservedETH += contribution;
if (shadowWinner != NO_SHADOW_WINNER && shadowWinner != _submissionID && round.hasPaid[_submissionID]) {
// Two sides are fully funded.
shadowWinner = NO_SHADOW_WINNER;
arbitrator.appeal.value(appealCost)(session.disputeID, arbitratorExtraData);
session.rounds.length++;
round.feeRewards = round.feeRewards.subCap(appealCost);
reservedETH = reservedETH.subCap(appealCost);
}
}
/** @dev Returns the contribution value and remainder from available ETH and required amount.
* @param _available The amount of ETH available for the contribution.
* @param _requiredAmount The amount of ETH required for the contribution.
* @return taken The amount of ETH taken.
* @return remainder The amount of ETH left from the contribution.
*/
function calculateContribution(uint _available, uint _requiredAmount)
internal
pure
returns(uint taken, uint remainder)
{
if (_requiredAmount > _available)
taken = _available;
else {
taken = _requiredAmount;
remainder = _available - _requiredAmount;
}
}
/** @dev Sends the fee stake rewards and reimbursements proportional to the contributions made to the winner of a dispute. Reimburses contributions if there is no winner.
* @param _beneficiary The address that made contributions to a request.
* @param _session The session from which to withdraw.
* @param _round The round from which to withdraw.
* @param _submissionID Submission's index in the array of submitted lists of the session which the beneficiary contributed to.
*/
function withdrawFeesAndRewards(address _beneficiary, uint _session, uint _round, uint _submissionID) public {
Session storage session = sessions[_session];
Round storage round = session.rounds[_round];
require(session.status == Status.Resolved, "Session has an ongoing dispute.");
uint reward;
// Allow to reimburse if funding of the round was unsuccessful.
if (!round.hasPaid[_submissionID]) {
reward = round.contributions[_beneficiary][_submissionID];
} else if (session.ruling == 0 || !round.hasPaid[session.ruling - 1]) {
// Reimburse unspent fees proportionally if there is no winner and loser. Also applies to the situation where the ultimate winner didn't pay appeal fees fully.
reward = round.successfullyPaid > 0
? (round.contributions[_beneficiary][_submissionID] * round.feeRewards) / round.successfullyPaid
: 0;
} else if (session.ruling - 1 == _submissionID) {
// Reward the winner. Subtract 1 from ruling to sync submissionID with arbitrator's choice.
reward = round.paidFees[_submissionID] > 0
? (round.contributions[_beneficiary][_submissionID] * round.feeRewards) / round.paidFees[_submissionID]
: 0;
}
round.contributions[_beneficiary][_submissionID] = 0;
_beneficiary.send(reward); // It is the user responsibility to accept ETH.
reservedETH = reservedETH.subCap(reward);
}
/** @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 {
Session storage session = sessions[sessions.length - 1];
require(msg.sender == address(arbitrator), "Must be called by the arbitrator.");
require(session.status == Status.DisputeCreated, "The dispute has already been resolved.");
require(_ruling <= session.submittedLists.length, "Ruling is out of bounds.");
if (shadowWinner != NO_SHADOW_WINNER)
executeRuling(_disputeID, shadowWinner + 1);
else
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 {
Session storage session = sessions[sessions.length - 1];
if (_ruling != 0) {
Submission storage submission = submissions[session.submittedLists[_ruling - 1]];
submission.approved = true;
submission.approvalTime = now;
submission.submitter.send(session.sumDeposit);
}
// If the ruiling is "0" the reserved funds of this session become expendable.
reservedETH = reservedETH.subCap(session.sumDeposit);
session.sumDeposit = 0;
shadowWinner = NO_SHADOW_WINNER;
lastApprovalTime = now;
session.status = Status.Resolved;
session.ruling = _ruling;
sessions.length++;
}
/** @dev Executes selected transactions of the list. UNTRUSTED.
* @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 {
Submission storage submission = submissions[_listID];
require(submission.approved, "Can't execute list that wasn't approved.");
require(now - submission.approvalTime <= executionTimeout, "Time to execute the transaction list has passed.");
for (uint i = _cursor; i < submission.txs.length && (_count == 0 || i < _cursor + _count); i++) {
Transaction storage transaction = submission.txs[i];
uint expendableFunds = getExpendableFunds();
if (!transaction.executed && transaction.value <= expendableFunds) {
bool callResult = transaction.target.call.value(transaction.value)(transaction.data); // solium-disable-line security/no-call-value
// An extra check to prevent re-entrancy through target call.
if (callResult == true) {
require(!transaction.executed, "This transaction has already been executed.");
transaction.executed = true;
}
}
}
}
/** @dev Fallback function to receive funds for the execution of transactions.
*/
function () public payable {}
/** @dev Gets the sum of contract funds that are used for the execution of transactions.
* @return Contract balance without reserved ETH.
*/
function getExpendableFunds() public view returns (uint) {
return address(this).balance.subCap(reservedETH);
}
/** @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
)
{
Submission storage submission = submissions[_listID];
Transaction storage transaction = submission.txs[_transactionIndex];
return (
transaction.target,
transaction.value,
transaction.data,
transaction.executed
);
}
/** @dev Gets the contributions made by a party for a given round of a session.
* Note that this function is O(n), where n is the number of submissions in the session. This could exceed the gas limit, therefore this function should only be used for interface display and not by other contracts.
* @param _session The ID of the session.
* @param _round The position of the round.
* @param _contributor The address of the contributor.
* @return The contributions.
*/
function getContributions(
uint _session,
uint _round,
address _contributor
) public view returns(uint[] contributions) {
Session storage session = sessions[_session];
Round storage round = session.rounds[_round];
contributions = new uint[](session.submittedLists.length);
for (uint i = 0; i < contributions.length; i++) {
contributions[i] = round.contributions[_contributor][i];
}
}
/** @dev Gets the information on a round of a session.
* Note that this function is O(n), where n is the number of submissions in the session. This could exceed the gas limit, therefore this function should only be used for interface display and not by other contracts.
* @param _session The ID of the session.
* @param _round The round to be queried.
* @return The round information.
*/
function getRoundInfo(uint _session, uint _round)
public
view
returns (
uint[] paidFees,
bool[] hasPaid,
uint feeRewards,
uint successfullyPaid
)
{
Session storage session = sessions[_session];
Round storage round = session.rounds[_round];
paidFees = new uint[](session.submittedLists.length);
hasPaid = new bool[](session.submittedLists.length);
for (uint i = 0; i < session.submittedLists.length; i++) {
paidFees[i] = round.paidFees[i];
hasPaid[i] = round.hasPaid[i];
}
feeRewards = round.feeRewards;
successfullyPaid = round.successfullyPaid;
}
/** @dev Gets the array of submitted lists in the session.
* Note that this function is O(n), where n is the number of submissions in the session. This could exceed the gas limit, therefore this function should only be used for interface display and not by other contracts.
* @param _session The ID of the session.
* @return submittedLists Indexes of lists that were submitted during the session.
*/
function getSubmittedLists(uint _session) public view returns (uint[] submittedLists) {
Session storage session = sessions[_session];
submittedLists = session.submittedLists;
}
/** @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) {
Submission storage submission = submissions[_listID];
return submission.txs.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 submissions.length;
}
/** @dev Gets the number of the ongoing session.
* @return The number of the ongoing session.
*/
function getCurrentSessionNumber() public view returns (uint) {
return sessions.length - 1;
}
/** @dev Gets the number rounds in ongoing session.
* @return The number of rounds in session.
*/
function getSessionRoundsNumber(uint _session) public view returns (uint) {
Session storage session = sessions[_session];
return session.rounds.length;
}
}
|
Withdraws submitted transaction list. Reimburses submission deposit. Withdrawal is only possible during the first half of the submission period and during withdrawPeriod seconds after the submission is made. _submissionID Submission's index in the array of submitted lists of the current sesssion. _listHash Hash of a withdrawing list./ This require statement is an extra check to prevent _submissionID linking to the wrong list because of index swap during withdrawal.
|
function withdrawTransactionList(uint _submissionID, bytes32 _listHash) public {
Session storage session = sessions[sessions.length - 1];
Submission storage submission = submissions[session.submittedLists[_submissionID]];
require(now - lastApprovalTime <= submissionTimeout / 2, "Lists can be withdrawn only in the first half of the initial submission period.");
require(submission.listHash == _listHash, "Provided hash doesn't correspond with submission ID.");
require(submission.submitter == msg.sender, "Can't withdraw the list created by someone else.");
require(now - submission.submissionTime <= withdrawTimeout, "Withdrawing time has passed.");
session.submittedLists[_submissionID] = session.submittedLists[session.submittedLists.length - 1];
session.alreadySubmitted[_listHash] = false;
session.submittedLists.length--;
session.sumDeposit = session.sumDeposit.subCap(submission.deposit);
msg.sender.transfer(submission.deposit);
reservedETH = reservedETH.subCap(submission.deposit);
}
| 12,753,164 |
./partial_match/1/0xBba1Acf75e69898Deb876e193A8069F8795a977C/sources/RonaldoInu.sol
|
approve token transfer to cover all possible scenarios add the liquidity
|
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
_approve(address(this), address(uniswapV2Router), tokenAmount);
address(this),
tokenAmount,
marketingWallet1,
block.timestamp
);
}
| 4,416,288 |
/**
*Submitted for verification at Etherscan.io on 2021-05-01
*/
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
// Part: IFund
interface IFund {
function underlying() external view returns (address);
function deposit(uint256 amountWei) external;
function depositFor(uint256 amountWei, address holder) external;
function withdraw(uint256 numberOfShares) external;
function getPricePerShare() external view returns (uint256);
function totalValueLocked() external view returns (uint256);
function underlyingBalanceWithInvestmentForHolder(address holder)
external
view
returns (uint256);
}
// Part: IGovernable
interface IGovernable {
function governance() external view returns (address);
}
// Part: IStrategy
interface IStrategy {
function name() external pure returns (string memory);
function version() external pure returns (string memory);
function underlying() external view returns (address);
function fund() external view returns (address);
function creator() external view returns (address);
function withdrawAllToFund() external;
function withdrawToFund(uint256 amount) external;
function investedUnderlyingBalance() external view returns (uint256);
function doHardWork() external;
function depositArbCheck() external view returns (bool);
}
// Part: IYVaultV2
interface IYVaultV2 {
// ERC20 part
function balanceOf(address) external view returns (uint256);
function decimals() external view returns (uint256);
// VaultV2 view interface
function token() external view returns (address);
function emergencyShutdown() external view returns (bool);
function pricePerShare() external view returns (uint256);
// VaultV2 user interface
function deposit(uint256 amount) external;
function withdraw(uint256 amount) external;
}
// Part: OpenZeppelin/[emailΒ protected]/Address
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// 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);
}
}
}
}
// Part: OpenZeppelin/[emailΒ protected]/IERC20
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// Part: OpenZeppelin/[emailΒ protected]/Math
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// Part: OpenZeppelin/[emailΒ protected]/SafeMath
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, 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;
}
}
// Part: OpenZeppelin/[emailΒ protected]/SafeERC20
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// Part: YearnV2StrategyBase
/**
* This strategy takes an asset (DAI, USDC), deposits into yv2 vault. Currently building only for DAI.
*/
abstract contract YearnV2StrategyBase is IStrategy {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
address public immutable override underlying;
address public immutable override fund;
address public immutable override creator;
// the y-vault corresponding to the underlying asset
address public immutable yVault;
// these tokens cannot be claimed by the governance
mapping(address => bool) public canNotSweep;
bool public investActivated;
constructor(address _fund, address _yVault) public {
require(_fund != address(0), "Fund cannot be empty");
require(_yVault != address(0), "Yearn Vault cannot be empty");
fund = _fund;
address _underlying = IFund(_fund).underlying();
require(
_underlying == IYVaultV2(_yVault).token(),
"Underlying do not match"
);
underlying = _underlying;
yVault = _yVault;
creator = msg.sender;
// approve max amount to save on gas costs later
IERC20(_underlying).safeApprove(_yVault, type(uint256).max);
// restricted tokens, can not be swept
canNotSweep[_underlying] = true;
canNotSweep[_yVault] = true;
investActivated = true;
}
function _governance() internal view returns (address) {
return IGovernable(fund).governance();
}
modifier onlyFundOrGovernance() {
require(
msg.sender == fund || msg.sender == _governance(),
"The sender has to be the governance or fund"
);
_;
}
/**
* TODO
*/
function depositArbCheck() public view override returns (bool) {
return true;
}
/**
* Allows Governance to withdraw partial shares to reduce slippage incurred
* and facilitate migration / withdrawal / strategy switch
*/
function withdrawPartialShares(uint256 shares)
external
onlyFundOrGovernance
{
IYVaultV2(yVault).withdraw(shares);
}
function setInvestActivated(bool _investActivated)
external
onlyFundOrGovernance
{
investActivated = _investActivated;
}
/**
* Withdraws an underlying asset from the strategy to the fund in the specified amount.
* It tries to withdraw from the strategy contract if this has enough balance.
* Otherwise, we withdraw shares from the yv2 vault. Transfer the required underlying amount to fund,
* and reinvest the rest. We can make it better by calculating the correct amount and withdrawing only that much.
*/
function withdrawToFund(uint256 underlyingAmount)
external
override
onlyFundOrGovernance
{
uint256 underlyingBalanceBefore =
IERC20(underlying).balanceOf(address(this));
if (underlyingBalanceBefore >= underlyingAmount) {
IERC20(underlying).safeTransfer(fund, underlyingAmount);
return;
}
uint256 shares =
_shareValueFromUnderlying(
underlyingAmount.sub(underlyingBalanceBefore)
);
uint256 totalShares = IYVaultV2(yVault).balanceOf(address(this));
if (shares > totalShares) {
//can't withdraw more than we have
shares = totalShares;
}
IYVaultV2(yVault).withdraw(shares);
// we can transfer the asset to the fund
uint256 underlyingBalance = IERC20(underlying).balanceOf(address(this));
if (underlyingBalance > 0) {
IERC20(underlying).safeTransfer(
fund,
Math.min(underlyingAmount, underlyingBalance)
);
}
}
/**
* Withdraws all assets from the yv2 vault and transfer to fund.
*/
function withdrawAllToFund() external override onlyFundOrGovernance {
uint256 shares = IYVaultV2(yVault).balanceOf(address(this));
IYVaultV2(yVault).withdraw(shares);
uint256 underlyingBalance = IERC20(underlying).balanceOf(address(this));
if (underlyingBalance > 0) {
IERC20(underlying).safeTransfer(fund, underlyingBalance);
}
}
/**
* Invests all underlying assets into our yv2 vault.
*/
function _investAllUnderlying() internal {
if (!investActivated) {
return;
}
require(
!IYVaultV2(yVault).emergencyShutdown(),
"Vault is emergency shutdown"
);
uint256 underlyingBalance = IERC20(underlying).balanceOf(address(this));
if (underlyingBalance > 0) {
// deposits the entire balance to yv2 vault
IYVaultV2(yVault).deposit(underlyingBalance);
}
}
/**
* The hard work only invests all underlying assets
*/
function doHardWork() external override onlyFundOrGovernance {
_investAllUnderlying();
}
// no tokens apart from underlying should be sent to this contract. Any tokens that are sent here by mistake are recoverable by governance
function sweep(address _token, address _sweepTo) external {
require(_governance() == msg.sender, "Not governance");
require(!canNotSweep[_token], "Token is restricted");
IERC20(_token).safeTransfer(
_sweepTo,
IERC20(_token).balanceOf(address(this))
);
}
/**
* Returns the underlying invested balance. This is the underlying amount based on shares in the yv2 vault,
* plus the current balance of the underlying asset.
*/
function investedUnderlyingBalance()
external
view
override
returns (uint256)
{
uint256 shares = IERC20(yVault).balanceOf(address(this));
uint256 price = IYVaultV2(yVault).pricePerShare();
uint256 precision = 10**(IYVaultV2(yVault).decimals());
uint256 underlyingBalanceinYVault = shares.mul(price).div(precision);
return
underlyingBalanceinYVault.add(
IERC20(underlying).balanceOf(address(this))
);
}
/**
* Returns the value of the underlying token in yToken
*/
function _shareValueFromUnderlying(uint256 underlyingAmount)
internal
view
returns (uint256)
{
uint256 precision = 10**(IYVaultV2(yVault).decimals());
return
underlyingAmount.mul(precision).div(
IYVaultV2(yVault).pricePerShare()
);
}
}
// File: YearnV2StrategyUSDC.sol
/**
* Adds the mainnet vault addresses to the YearnV2StrategyBase
*/
contract YearnV2StrategyUSDC is YearnV2StrategyBase {
string public constant override name = "YearnV2StrategyUSDC";
string public constant override version = "V1";
address internal constant _yvusdc =
address(0x5f18C75AbDAe578b483E5F43f12a39cF75b973a9);
constructor(address _fund) public YearnV2StrategyBase(_fund, _yvusdc) {}
}
|
Invests all underlying assets into our yv2 vault./ deposits the entire balance to yv2 vault
|
function _investAllUnderlying() internal {
if (!investActivated) {
return;
}
require(
!IYVaultV2(yVault).emergencyShutdown(),
"Vault is emergency shutdown"
);
uint256 underlyingBalance = IERC20(underlying).balanceOf(address(this));
if (underlyingBalance > 0) {
IYVaultV2(yVault).deposit(underlyingBalance);
}
}
| 10,680,340 |
./full_match/77/0xB083410baBCF71f10a8958DF948bFE1eFC32987e/sources/contracts/official/CUSIT001/CUSIT001Token.sol
|
Owner function to pay dividends to all token holders/ increase the total amount paid snapshot the tokens at the moment the payment is done check if we have paid everything
|
function setPaidDividends() public onlyOwner {
require(!bCompletedPayment, "Dividends payment is already completed");
nTotalDividendsPaid = nTotalDividendsPaid.add(nPaymentValue);
nCurrentSnapshotId = _snapshot();
if (nCurrentSnapshotId == TOTAL_PERIODS) {
bCompletedPayment = true;
}
}
| 5,047,368 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/Math.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "./libraries/DecimalsConverter.sol";
import "./tokens/erc20permit-upgradeable/ERC20PermitUpgradeable.sol";
import "./interfaces/IPolicyBook.sol";
import "./interfaces/IBMICoverStaking.sol";
import "./interfaces/ICapitalPool.sol";
import "./interfaces/IBMICoverStakingView.sol";
import "./interfaces/IContractsRegistry.sol";
import "./interfaces/IPolicyRegistry.sol";
import "./interfaces/IClaimVoting.sol";
import "./interfaces/IClaimingRegistry.sol";
import "./interfaces/ILiquidityMining.sol";
import "./interfaces/IPolicyQuote.sol";
import "./interfaces/IRewardsGenerator.sol";
import "./interfaces/ILiquidityRegistry.sol";
import "./interfaces/INFTStaking.sol";
import "./abstract/AbstractDependant.sol";
import "./Globals.sol";
contract PolicyBook is IPolicyBook, ERC20PermitUpgradeable, AbstractDependant {
using SafeERC20 for ERC20;
using SafeMath for uint256;
using Math for uint256;
uint256 public constant MINUMUM_COVERAGE = 100 * DECIMALS18; // 100 STBL
uint256 public constant ANNUAL_COVERAGE_TOKENS = MINUMUM_COVERAGE * 10; // 1000 STBL
uint256 public constant RISKY_UTILIZATION_RATIO = 80 * PRECISION;
uint256 public constant MODERATE_UTILIZATION_RATIO = 50 * PRECISION;
uint256 public constant PREMIUM_DISTRIBUTION_EPOCH = 1 days;
uint256 public constant MAX_PREMIUM_DISTRIBUTION_EPOCHS = 90;
uint256 public constant MINIMUM_REWARD = 15 * PRECISION; // 0.15
uint256 public constant MAXIMUM_REWARD = 2 * PERCENTAGE_100; // 2.0
uint256 public constant BASE_REWARD = PERCENTAGE_100; // 1.0
uint256 public constant override EPOCH_DURATION = 1 weeks;
uint256 public constant MAXIMUM_EPOCHS = SECONDS_IN_THE_YEAR / EPOCH_DURATION;
uint256 public constant VIRTUAL_EPOCHS = 2;
uint256 public constant WITHDRAWAL_PERIOD = 8 days;
uint256 public constant override READY_TO_WITHDRAW_PERIOD = 2 days;
bool public override whitelisted;
uint256 public override epochStartTime;
uint256 public lastDistributionEpoch;
uint256 public lastPremiumDistributionEpoch;
int256 public lastPremiumDistributionAmount;
address public override insuranceContractAddress;
IPolicyBookFabric.ContractType public override contractType;
ERC20 public stblToken;
IPolicyRegistry public policyRegistry;
IBMICoverStaking public bmiCoverStaking;
IRewardsGenerator public rewardsGenerator;
ILiquidityMining public liquidityMining;
IClaimVoting public claimVoting;
IClaimingRegistry public claimingRegistry;
ILiquidityRegistry public liquidityRegistry;
address public reinsurancePoolAddress;
IPolicyQuote public policyQuote;
address public policyBookAdmin;
address public policyBookRegistry;
address public policyBookFabricAddress;
uint256 public override totalLiquidity;
uint256 public override totalCoverTokens;
mapping(address => WithdrawalInfo) public override withdrawalsInfo;
mapping(address => PolicyHolder) public override policyHolders;
mapping(address => uint256) public liquidityFromLM;
mapping(uint256 => uint256) public epochAmounts;
mapping(uint256 => int256) public premiumDistributionDeltas;
uint256 public override stblDecimals;
// new state variables here , avoid break the storage when upgrade
INFTStaking public nftStaking;
IBMICoverStakingView public bmiCoverStakingView;
ICapitalPool public capitalPool;
IPolicyBookFacade public override policyBookFacade;
event LiquidityAdded(
address _liquidityHolder,
uint256 _liquidityAmount,
uint256 _newTotalLiquidity
);
event WithdrawalRequested(
address _liquidityHolder,
uint256 _tokensToWithdraw,
uint256 _readyToWithdrawDate
);
event LiquidityWithdrawn(
address _liquidityHolder,
uint256 _tokensToWithdraw,
uint256 _newTotalLiquidity
);
event PolicyBought(
address _policyHolder,
uint256 _coverTokens,
uint256 _price,
uint256 _newTotalCoverTokens,
address _distributor
);
event CoverageChanged(uint256 _newTotalCoverTokens);
modifier onlyClaimVoting() {
require(_msgSender() == address(claimVoting), "PB: Not a CV");
_;
}
modifier onlyPolicyBookFacade() {
require(_msgSender() == address(policyBookFacade), "PB: Not a PBFc");
_;
}
modifier onlyPolicyBookFabric() {
require(_msgSender() == policyBookFabricAddress, "PB: Not PBF");
_;
}
modifier onlyPolicyBookAdmin() {
require(_msgSender() == policyBookAdmin, "PB: Not a PBA");
_;
}
modifier onlyLiquidityAdders() {
require(
_msgSender() == policyBookFabricAddress || _msgSender() == address(policyBookFacade),
"PB: Not allowed"
);
_;
}
modifier onlyCapitalPool() {
require(_msgSender() == address(capitalPool), "PB: Not a CP");
_;
}
modifier updateBMICoverStakingReward() {
_;
forceUpdateBMICoverStakingRewardMultiplier();
}
modifier withPremiumsDistribution() {
_distributePremiums();
_;
}
function _distributePremiums() internal {
uint256 lastEpoch = lastPremiumDistributionEpoch;
uint256 currentEpoch = _getPremiumDistributionEpoch();
if (currentEpoch > lastEpoch) {
(
lastPremiumDistributionAmount,
lastPremiumDistributionEpoch,
totalLiquidity
) = _getPremiumsDistribution(lastEpoch, currentEpoch);
}
}
function __PolicyBook_init(
address _insuranceContract,
IPolicyBookFabric.ContractType _contractType,
string calldata _description,
string calldata _projectSymbol
) external override initializer {
string memory fullSymbol = string(abi.encodePacked("bmiV2", _projectSymbol, "Cover"));
__ERC20Permit_init(fullSymbol);
__ERC20_init(_description, fullSymbol);
insuranceContractAddress = _insuranceContract;
contractType = _contractType;
epochStartTime = block.timestamp;
lastDistributionEpoch = 1;
lastPremiumDistributionEpoch = _getPremiumDistributionEpoch();
}
function setPolicyBookFacade(address _policyBookFacade)
external
override
onlyPolicyBookFabric
{
policyBookFacade = IPolicyBookFacade(_policyBookFacade);
}
function setDependencies(IContractsRegistry _contractsRegistry)
external
override
onlyInjectorOrZero
{
stblToken = ERC20(_contractsRegistry.getUSDTContract());
bmiCoverStaking = IBMICoverStaking(_contractsRegistry.getBMICoverStakingContract());
bmiCoverStakingView = IBMICoverStakingView(
_contractsRegistry.getBMICoverStakingViewContract()
);
rewardsGenerator = IRewardsGenerator(_contractsRegistry.getRewardsGeneratorContract());
claimVoting = IClaimVoting(_contractsRegistry.getClaimVotingContract());
policyRegistry = IPolicyRegistry(_contractsRegistry.getPolicyRegistryContract());
reinsurancePoolAddress = _contractsRegistry.getReinsurancePoolContract();
capitalPool = ICapitalPool(_contractsRegistry.getCapitalPoolContract());
policyQuote = IPolicyQuote(_contractsRegistry.getPolicyQuoteContract());
claimingRegistry = IClaimingRegistry(_contractsRegistry.getClaimingRegistryContract());
liquidityRegistry = ILiquidityRegistry(_contractsRegistry.getLiquidityRegistryContract());
policyBookAdmin = _contractsRegistry.getPolicyBookAdminContract();
policyBookRegistry = _contractsRegistry.getPolicyBookRegistryContract();
policyBookFabricAddress = _contractsRegistry.getPolicyBookFabricContract();
nftStaking = INFTStaking(_contractsRegistry.getNFTStakingContract());
stblDecimals = stblToken.decimals();
}
function whitelist(bool _whitelisted)
external
override
onlyPolicyBookAdmin
updateBMICoverStakingReward
{
whitelisted = _whitelisted;
}
function getEpoch(uint256 time) public view override returns (uint256) {
return time.sub(epochStartTime).div(EPOCH_DURATION) + 1;
}
function _getPremiumDistributionEpoch() internal view returns (uint256) {
return block.timestamp / PREMIUM_DISTRIBUTION_EPOCH;
}
function _getSTBLToBMIXRatio(uint256 currentLiquidity) internal view returns (uint256) {
uint256 _currentTotalSupply = totalSupply();
if (_currentTotalSupply == 0) {
return PERCENTAGE_100;
}
return currentLiquidity.mul(PERCENTAGE_100).div(_currentTotalSupply);
}
function convertBMIXToSTBL(uint256 _amount) public view override returns (uint256) {
(, uint256 currentLiquidity) = getNewCoverAndLiquidity();
return _amount.mul(_getSTBLToBMIXRatio(currentLiquidity)).div(PERCENTAGE_100);
}
function convertSTBLToBMIX(uint256 _amount) public view override returns (uint256) {
(, uint256 currentLiquidity) = getNewCoverAndLiquidity();
return _amount.mul(PERCENTAGE_100).div(_getSTBLToBMIXRatio(currentLiquidity));
}
function _submitClaimAndInitializeVoting(string memory evidenceURI, bool appeal) internal {
uint256 cover = policyHolders[_msgSender()].coverTokens;
uint256 virtualEndEpochNumber =
policyHolders[_msgSender()].endEpochNumber + VIRTUAL_EPOCHS;
/// @dev "lock" claim and appeal tokens
if (!appeal) {
epochAmounts[virtualEndEpochNumber] = epochAmounts[virtualEndEpochNumber].sub(cover);
} else {
uint256 claimIndex = claimingRegistry.claimIndex(_msgSender(), address(this));
uint256 endLockEpoch =
Math.max(
getEpoch(claimingRegistry.claimEndTime(claimIndex)) + 1,
virtualEndEpochNumber
);
epochAmounts[endLockEpoch] = epochAmounts[endLockEpoch].sub(cover);
}
/// @dev if appeal period expired, this would fail in case of appeal (no button is displayed on FE)
claimVoting.initializeVoting(_msgSender(), evidenceURI, cover, appeal);
}
function submitClaimAndInitializeVoting(string calldata evidenceURI) external override {
_submitClaimAndInitializeVoting(evidenceURI, false);
}
function submitAppealAndInitializeVoting(string calldata evidenceURI) external override {
_submitClaimAndInitializeVoting(evidenceURI, true);
}
function commitClaim(
address claimer,
uint256 claimAmount,
uint256 claimEndTime,
IClaimingRegistry.ClaimStatus status
) external override onlyClaimVoting withPremiumsDistribution updateBMICoverStakingReward {
updateEpochsInfo();
uint256 cover = policyHolders[claimer].coverTokens;
if (status == IClaimingRegistry.ClaimStatus.ACCEPTED) {
uint256 newTotalCover = totalCoverTokens.sub(cover);
totalCoverTokens = newTotalCover;
capitalPool.fundClaim(claimer, claimAmount);
// TODO: verify
// check additional state changes other than transfer
delete policyHolders[claimer];
policyRegistry.removePolicy(claimer);
} else if (status == IClaimingRegistry.ClaimStatus.REJECTED_CAN_APPEAL) {
uint256 endUnlockEpoch =
Math.max(
getEpoch(claimEndTime) + 1,
policyHolders[claimer].endEpochNumber + VIRTUAL_EPOCHS
);
epochAmounts[endUnlockEpoch] = epochAmounts[endUnlockEpoch].add(cover);
} else {
uint256 virtualEndEpochNumber =
policyHolders[claimer].endEpochNumber.add(VIRTUAL_EPOCHS);
if (lastDistributionEpoch <= virtualEndEpochNumber) {
epochAmounts[virtualEndEpochNumber] = epochAmounts[virtualEndEpochNumber].add(
cover
);
} else {
uint256 newTotalCover = totalCoverTokens.sub(cover);
totalCoverTokens = newTotalCover;
policyBookFacade.reevaluateProvidedLeverageStable();
emit CoverageChanged(newTotalCover);
}
}
}
function _getPremiumsDistribution(uint256 lastEpoch, uint256 currentEpoch)
internal
view
returns (
int256 currentDistribution,
uint256 distributionEpoch,
uint256 newTotalLiquidity
)
{
currentDistribution = lastPremiumDistributionAmount;
newTotalLiquidity = totalLiquidity;
distributionEpoch = Math.min(
currentEpoch,
lastEpoch + MAX_PREMIUM_DISTRIBUTION_EPOCHS + 1
);
for (uint256 i = lastEpoch + 1; i <= distributionEpoch; i++) {
currentDistribution += premiumDistributionDeltas[i];
newTotalLiquidity = newTotalLiquidity.add(uint256(currentDistribution));
}
}
function forceUpdateBMICoverStakingRewardMultiplier() public override {
uint256 rewardMultiplier;
if (whitelisted) {
rewardMultiplier = MINIMUM_REWARD;
uint256 liquidity = totalLiquidity;
uint256 coverTokens = totalCoverTokens;
if (coverTokens > 0 && liquidity > 0) {
rewardMultiplier = BASE_REWARD;
uint256 utilizationRatio = coverTokens.mul(PERCENTAGE_100).div(liquidity);
if (utilizationRatio < MODERATE_UTILIZATION_RATIO) {
rewardMultiplier = Math
.max(utilizationRatio, PRECISION)
.sub(PRECISION)
.mul(BASE_REWARD.sub(MINIMUM_REWARD))
.div(MODERATE_UTILIZATION_RATIO)
.add(MINIMUM_REWARD);
} else if (utilizationRatio > RISKY_UTILIZATION_RATIO) {
rewardMultiplier = MAXIMUM_REWARD
.sub(BASE_REWARD)
.mul(utilizationRatio.sub(RISKY_UTILIZATION_RATIO))
.div(PERCENTAGE_100.sub(RISKY_UTILIZATION_RATIO))
.add(BASE_REWARD);
}
}
}
rewardsGenerator.updatePolicyBookShare(rewardMultiplier.div(10**22)); // 5 decimal places or zero
}
function getNewCoverAndLiquidity()
public
view
override
returns (uint256 newTotalCoverTokens, uint256 newTotalLiquidity)
{
newTotalLiquidity = totalLiquidity;
newTotalCoverTokens = totalCoverTokens;
uint256 lastEpoch = lastPremiumDistributionEpoch;
uint256 currentEpoch = _getPremiumDistributionEpoch();
if (currentEpoch > lastEpoch) {
(, , newTotalLiquidity) = _getPremiumsDistribution(lastEpoch, currentEpoch);
}
uint256 newDistributionEpoch = Math.min(getEpoch(block.timestamp), MAXIMUM_EPOCHS);
for (uint256 i = lastDistributionEpoch; i < newDistributionEpoch; i++) {
newTotalCoverTokens = newTotalCoverTokens.sub(epochAmounts[i]);
}
}
function getPolicyPrice(
uint256 _epochsNumber,
uint256 _coverTokens,
address _holder
)
public
view
override
returns (
uint256 totalSeconds,
uint256 totalPrice,
uint256 pricePercentage
)
{
require(_coverTokens >= MINUMUM_COVERAGE, "PB: Wrong cover");
require(_epochsNumber > 0 && _epochsNumber <= MAXIMUM_EPOCHS, "PB: Wrong epoch duration");
(uint256 newTotalCoverTokens, uint256 newTotalLiquidity) = getNewCoverAndLiquidity();
totalSeconds = secondsToEndCurrentEpoch().add(_epochsNumber.sub(1).mul(EPOCH_DURATION));
(totalPrice, pricePercentage) = policyQuote.getQuotePredefined(
totalSeconds,
_coverTokens,
newTotalCoverTokens,
newTotalLiquidity,
policyBookFacade.totalLeveragedLiquidity(),
policyBookFacade.safePricingModel()
);
///@notice commented this because of PB size when adding a new feature
/// and it is not used anymore ATM
// reduce premium by reward NFT locked by user
// uint256 _reductionMultiplier = nftStaking.getUserReductionMultiplier(_holder);
// if (_reductionMultiplier > 0) {
// totalPrice = totalPrice.sub(totalPrice.mul(_reductionMultiplier).div(PERCENTAGE_100));
// }
}
function buyPolicy(
address _buyer,
address _holder,
uint256 _epochsNumber,
uint256 _coverTokens,
uint256 _distributorFee,
address _distributor
) external override returns (uint256, uint256) {
return
_buyPolicy(
BuyPolicyParameters(
_buyer,
_holder,
_epochsNumber,
_coverTokens,
_distributorFee,
_distributor
)
);
}
function _buyPolicy(BuyPolicyParameters memory parameters)
internal
onlyPolicyBookFacade
withPremiumsDistribution
updateBMICoverStakingReward
returns (uint256, uint256)
{
require(
!policyRegistry.isPolicyActive(parameters.holder, address(this)),
"PB: The holder already exists"
);
require(
claimingRegistry.canBuyNewPolicy(parameters.holder, address(this)),
"PB: Claim is pending"
);
updateEpochsInfo();
uint256 _totalCoverTokens = totalCoverTokens.add(parameters.coverTokens);
require(totalLiquidity >= _totalCoverTokens, "PB: Not enough liquidity");
(uint256 _totalSeconds, uint256 _totalPrice, uint256 pricePercentage) =
getPolicyPrice(parameters.epochsNumber, parameters.coverTokens, parameters.holder);
// Partners are rewarded with X% of the Premium, coming from the Protocolβs fee part.
// It's a part of 20% initially send to the Reinsurance pool
// (the other 80% of the Premium is a yield for coverage providers).
uint256 _distributorFeeAmount;
if (parameters.distributorFee > 0) {
_distributorFeeAmount = _totalPrice.mul(parameters.distributorFee).div(PERCENTAGE_100);
}
uint256 _reinsurancePrice =
_totalPrice.mul(PROTOCOL_PERCENTAGE).div(PERCENTAGE_100).sub(_distributorFeeAmount);
uint256 _price = _totalPrice.sub(_distributorFeeAmount);
_addPolicyHolder(parameters, _totalPrice, _reinsurancePrice);
totalCoverTokens = _totalCoverTokens;
if (_distributorFeeAmount > 0) {
stblToken.safeTransferFrom(
parameters.buyer,
parameters.distributor,
DecimalsConverter.convertFrom18(_distributorFeeAmount, stblDecimals)
);
}
stblToken.safeTransferFrom(
parameters.buyer,
address(capitalPool),
DecimalsConverter.convertFrom18(_price, stblDecimals)
);
_price = capitalPool.addPolicyHoldersHardSTBL(
DecimalsConverter.convertFrom18(_price, stblDecimals),
parameters.epochsNumber,
DecimalsConverter.convertFrom18(_reinsurancePrice, stblDecimals)
);
_addPolicyPremiumToDistributions(
_totalSeconds.add(VIRTUAL_EPOCHS * EPOCH_DURATION),
_price
);
policyRegistry.addPolicy(parameters.holder, parameters.coverTokens, _price, _totalSeconds);
emit PolicyBought(
parameters.holder,
parameters.coverTokens,
_totalPrice,
_totalCoverTokens,
parameters.distributor
);
return (_price, pricePercentage);
}
function _addPolicyHolder(
BuyPolicyParameters memory parameters,
uint256 _totalPrice,
uint256 _reinsurancePrice
) internal {
uint256 _currentEpochNumber = getEpoch(block.timestamp);
uint256 _endEpochNumber = _currentEpochNumber.add(parameters.epochsNumber.sub(1));
uint256 _virtualEndEpochNumber = _endEpochNumber + VIRTUAL_EPOCHS;
policyHolders[parameters.holder] = PolicyHolder(
parameters.coverTokens,
_currentEpochNumber,
_endEpochNumber,
_totalPrice,
_reinsurancePrice
);
epochAmounts[_virtualEndEpochNumber] = epochAmounts[_virtualEndEpochNumber].add(
parameters.coverTokens
);
}
/// @dev no need to cap epochs because the maximum policy duration is 1 year
function _addPolicyPremiumToDistributions(uint256 _totalSeconds, uint256 _distributedAmount)
internal
{
uint256 distributionEpochs = _totalSeconds.add(1).div(PREMIUM_DISTRIBUTION_EPOCH).max(1);
int256 distributedPerEpoch = int256(_distributedAmount.div(distributionEpochs));
uint256 nextEpoch = _getPremiumDistributionEpoch() + 1;
premiumDistributionDeltas[nextEpoch] += distributedPerEpoch;
premiumDistributionDeltas[nextEpoch + distributionEpochs] -= distributedPerEpoch;
}
function updateEpochsInfo() public override {
uint256 _lastDistributionEpoch = lastDistributionEpoch;
uint256 _newDistributionEpoch =
Math.min(getEpoch(block.timestamp), _lastDistributionEpoch + MAXIMUM_EPOCHS);
if (_lastDistributionEpoch < _newDistributionEpoch) {
uint256 _newTotalCoverTokens = totalCoverTokens;
for (uint256 i = _lastDistributionEpoch; i < _newDistributionEpoch; i++) {
_newTotalCoverTokens = _newTotalCoverTokens.sub(epochAmounts[i]);
delete epochAmounts[i];
}
lastDistributionEpoch = _newDistributionEpoch;
totalCoverTokens = _newTotalCoverTokens;
policyBookFacade.reevaluateProvidedLeverageStable();
emit CoverageChanged(_newTotalCoverTokens);
}
}
function secondsToEndCurrentEpoch() public view override returns (uint256) {
uint256 epochNumber = block.timestamp.sub(epochStartTime).div(EPOCH_DURATION) + 1;
return epochNumber.mul(EPOCH_DURATION).sub(block.timestamp.sub(epochStartTime));
}
function addLiquidityFor(address _liquidityHolderAddr, uint256 _liquidityAmount)
external
override
{
addLiquidity(_liquidityHolderAddr, _liquidityHolderAddr, _liquidityAmount, 0);
}
/// @notice adds liquidity on behalf of a sender
/// @dev only allowed to be called from its facade
/// @param _liquidityBuyerAddr, address of the one who pays
/// @param _liquidityHolderAddr, address of the one who hold
/// @param _liquidityAmount, uint256 amount to be added on behalf the sender
/// @param _stakeSTBLAmount uint256 the staked amount if add liq and stake
function addLiquidity(
address _liquidityBuyerAddr,
address _liquidityHolderAddr,
uint256 _liquidityAmount,
uint256 _stakeSTBLAmount
)
public
override
onlyLiquidityAdders
withPremiumsDistribution
updateBMICoverStakingReward
returns (uint256)
{
if (_stakeSTBLAmount > 0) {
require(_stakeSTBLAmount <= _liquidityAmount, "PB: Wrong staking amount");
}
uint256 stblLiquidity = DecimalsConverter.convertFrom18(_liquidityAmount, stblDecimals);
require(stblLiquidity > 0, "PB: Liquidity amount is zero");
updateEpochsInfo();
/// @dev PBF already sent stable tokens
/// TODO: track PB sblIngress individually ? or only the _mint
if (_msgSender() != policyBookFabricAddress) {
stblToken.safeTransferFrom(_liquidityBuyerAddr, address(capitalPool), stblLiquidity);
}
capitalPool.addCoverageProvidersHardSTBL(stblLiquidity);
uint256 _liquidityAmountBMIX = convertSTBLToBMIX(_liquidityAmount);
_mint(_liquidityHolderAddr, _liquidityAmountBMIX);
uint256 liquidity = totalLiquidity.add(_liquidityAmount);
totalLiquidity = liquidity;
liquidityRegistry.tryToAddPolicyBook(_liquidityHolderAddr, address(this));
if (_stakeSTBLAmount > 0) {
bmiCoverStaking.stakeBMIXFrom(
_liquidityHolderAddr,
convertSTBLToBMIX(_stakeSTBLAmount)
);
}
emit LiquidityAdded(_liquidityHolderAddr, _liquidityAmount, liquidity);
return _liquidityAmountBMIX;
}
function getAvailableBMIXWithdrawableAmount(address _userAddr)
external
view
override
returns (uint256)
{
(uint256 newTotalCoverTokens, uint256 newTotalLiquidity) = getNewCoverAndLiquidity();
return
convertSTBLToBMIX(
Math.min(
newTotalLiquidity.sub(newTotalCoverTokens),
_getUserAvailableSTBL(_userAddr)
)
);
}
function _getUserAvailableSTBL(address _userAddr) internal view returns (uint256) {
uint256 availableSTBL =
convertBMIXToSTBL(
balanceOf(_userAddr).add(withdrawalsInfo[_userAddr].withdrawalAmount)
);
return availableSTBL;
}
function getWithdrawalStatus(address _userAddr)
public
view
override
returns (WithdrawalStatus)
{
uint256 readyToWithdrawDate = withdrawalsInfo[_userAddr].readyToWithdrawDate;
if (readyToWithdrawDate == 0) {
return WithdrawalStatus.NONE;
}
if (block.timestamp < readyToWithdrawDate) {
return WithdrawalStatus.PENDING;
}
if (
block.timestamp >= readyToWithdrawDate.add(READY_TO_WITHDRAW_PERIOD) &&
!withdrawalsInfo[_userAddr].withdrawalAllowed
) {
return WithdrawalStatus.EXPIRED;
}
return WithdrawalStatus.READY;
}
function requestWithdrawal(uint256 _tokensToWithdraw, address _user)
external
override
onlyPolicyBookFacade
withPremiumsDistribution
{
require(_tokensToWithdraw > 0, "PB: Amount is zero");
uint256 _stblTokensToWithdraw = convertBMIXToSTBL(_tokensToWithdraw);
uint256 _availableSTBLBalance = _getUserAvailableSTBL(_user);
require(_availableSTBLBalance >= _stblTokensToWithdraw, "PB: Wrong announced amount");
updateEpochsInfo();
require(
totalLiquidity >= totalCoverTokens.add(_stblTokensToWithdraw),
"PB: Not enough free liquidity"
);
_lockTokens(_user, _tokensToWithdraw);
uint256 _readyToWithdrawDate = block.timestamp.add(WITHDRAWAL_PERIOD);
withdrawalsInfo[_user] = WithdrawalInfo(_tokensToWithdraw, _readyToWithdrawDate, false);
emit WithdrawalRequested(_user, _tokensToWithdraw, _readyToWithdrawDate);
}
function _lockTokens(address _userAddr, uint256 _neededTokensToLock) internal {
uint256 _currentLockedTokens = withdrawalsInfo[_userAddr].withdrawalAmount;
if (_currentLockedTokens > _neededTokensToLock) {
this.transfer(_userAddr, _currentLockedTokens - _neededTokensToLock);
} else if (_currentLockedTokens < _neededTokensToLock) {
this.transferFrom(
_userAddr,
address(this),
_neededTokensToLock - _currentLockedTokens
);
}
}
function unlockTokens() external override {
uint256 _lockedAmount = withdrawalsInfo[_msgSender()].withdrawalAmount;
require(_lockedAmount > 0, "PB: Amount is zero");
this.transfer(_msgSender(), _lockedAmount);
delete withdrawalsInfo[_msgSender()];
liquidityRegistry.removeExpiredWithdrawalRequest(_msgSender(), address(this));
}
function withdrawLiquidity(address sender)
external
override
onlyPolicyBookFacade
withPremiumsDistribution
updateBMICoverStakingReward
returns (uint256)
{
require(
getWithdrawalStatus(sender) == WithdrawalStatus.READY,
"PB: Withdrawal is not ready"
);
updateEpochsInfo();
uint256 liquidity = totalLiquidity;
uint256 _currentWithdrawalAmount = withdrawalsInfo[sender].withdrawalAmount;
uint256 _tokensToWithdraw =
Math.min(_currentWithdrawalAmount, convertSTBLToBMIX(liquidity.sub(totalCoverTokens)));
uint256 _stblTokensToWithdraw = convertBMIXToSTBL(_tokensToWithdraw);
capitalPool.withdrawLiquidity(
sender,
DecimalsConverter.convertFrom18(_stblTokensToWithdraw, stblDecimals),
false
);
_burn(address(this), _tokensToWithdraw);
liquidity = liquidity.sub(_stblTokensToWithdraw);
_currentWithdrawalAmount = _currentWithdrawalAmount.sub(_tokensToWithdraw);
if (_currentWithdrawalAmount == 0) {
delete withdrawalsInfo[sender];
liquidityRegistry.tryToRemovePolicyBook(sender, address(this));
} else {
withdrawalsInfo[sender].withdrawalAllowed = true;
withdrawalsInfo[sender].withdrawalAmount = _currentWithdrawalAmount;
}
totalLiquidity = liquidity;
emit LiquidityWithdrawn(sender, _stblTokensToWithdraw, liquidity);
return _tokensToWithdraw;
}
function updateLiquidity(uint256 _lostLiquidity) external override onlyCapitalPool {
updateEpochsInfo();
uint256 _newLiquidity = totalLiquidity.sub(_lostLiquidity);
totalLiquidity = _newLiquidity;
emit LiquidityWithdrawn(_msgSender(), _lostLiquidity, _newLiquidity);
}
/// @notice returns APY% with 10**5 precision
function getAPY() public view override returns (uint256) {
uint256 lastEpoch = lastPremiumDistributionEpoch;
uint256 currentEpoch = _getPremiumDistributionEpoch();
int256 premiumDistributionAmount = lastPremiumDistributionAmount;
// simulates addLiquidity()
if (currentEpoch > lastEpoch) {
(premiumDistributionAmount, currentEpoch, ) = _getPremiumsDistribution(
lastEpoch,
currentEpoch
);
}
premiumDistributionAmount += premiumDistributionDeltas[currentEpoch + 1];
return
uint256(premiumDistributionAmount).mul(365).mul(10**7).div(
convertBMIXToSTBL(totalSupply()).add(APY_TOKENS)
);
}
function userStats(address _user) external view override returns (PolicyHolder memory) {
return policyHolders[_user];
}
/// @notice _annualProfitYields is multiplied by 10**5
/// @notice _annualInsuranceCost is calculated for 1000 STBL cover (or _maxCapacities if it is less)
/// @notice _bmiXRatio is multiplied by 10**18. To get STBL representation,
/// multiply BMIX tokens by this value and then divide by 10**18
function numberStats()
external
view
override
returns (
uint256 _maxCapacities,
uint256 _totalSTBLLiquidity,
uint256 _totalLeveragedLiquidity,
uint256 _stakedSTBL,
uint256 _annualProfitYields,
uint256 _annualInsuranceCost,
uint256 _bmiXRatio
)
{
uint256 newTotalCoverTokens;
(newTotalCoverTokens, _totalSTBLLiquidity) = getNewCoverAndLiquidity();
_maxCapacities = _totalSTBLLiquidity - newTotalCoverTokens;
_stakedSTBL = rewardsGenerator.getStakedPolicyBookSTBL(address(this));
_annualProfitYields = getAPY().add(bmiCoverStakingView.getPolicyBookAPY(address(this)));
uint256 possibleCoverage = Math.min(ANNUAL_COVERAGE_TOKENS, _maxCapacities);
_totalLeveragedLiquidity = policyBookFacade.totalLeveragedLiquidity();
if (possibleCoverage >= MINUMUM_COVERAGE) {
(_annualInsuranceCost, ) = policyQuote.getQuotePredefined(
SECONDS_IN_THE_YEAR,
possibleCoverage,
newTotalCoverTokens,
_totalSTBLLiquidity,
_totalLeveragedLiquidity,
policyBookFacade.safePricingModel()
);
_annualInsuranceCost = _annualInsuranceCost
.mul(ANNUAL_COVERAGE_TOKENS.mul(PRECISION).div(possibleCoverage))
.div(PRECISION)
.div(10);
}
_bmiXRatio = convertBMIXToSTBL(10**18);
}
function info()
external
view
override
returns (
string memory _symbol,
address _insuredContract,
IPolicyBookFabric.ContractType _contractType,
bool _whitelisted
)
{
return (symbol(), insuranceContractAddress, contractType, whitelisted);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.5 <0.8.0;
import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import "../../interfaces/tokens/erc20permit-upgradeable/IERC20PermitUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.sol";
import "./EIP712Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
/**
* COPIED FROM https://github.com/OpenZeppelin/openzeppelin-contracts-upgradeable/tree/release-v3.4/contracts/drafts
* @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.
*/
abstract contract ERC20PermitUpgradeable is
Initializable,
ERC20Upgradeable,
IERC20PermitUpgradeable,
EIP712Upgradeable
{
using CountersUpgradeable for CountersUpgradeable.Counter;
mapping(address => CountersUpgradeable.Counter) private _nonces;
// solhint-disable-next-line var-name-mixedcase
bytes32 private _PERMIT_TYPEHASH;
/**
* @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`.
*
* It's a good idea to use the same `name` that is defined as the ERC20 token name.
*/
function __ERC20Permit_init(string memory name) internal initializer {
__Context_init_unchained();
__EIP712_init_unchained(name, "1");
__ERC20Permit_init_unchained(name);
}
function __ERC20Permit_init_unchained(string memory name) internal initializer {
_PERMIT_TYPEHASH = keccak256(
"Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"
);
}
/**
* @dev See {IERC20Permit-permit}.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public virtual override {
// solhint-disable-next-line not-rely-on-time
require(block.timestamp <= deadline, "ERC20Permit: expired deadline");
bytes32 structHash =
keccak256(
abi.encode(
_PERMIT_TYPEHASH,
owner,
spender,
value,
_nonces[owner].current(),
deadline
)
);
bytes32 hash = _hashTypedDataV4(structHash);
address signer = recover(hash, v, r, s);
require(signer == owner, "ERC20Permit: invalid signature");
_nonces[owner].increment();
_approve(owner, spender, value);
}
/**
* @dev Overload of {ECDSA-recover-bytes32-bytes-} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) 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.
require(
uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0,
"ECDSA: invalid signature 's' value"
);
require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value");
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
require(signer != address(0), "ECDSA: invalid signature");
return signer;
}
/**
* @dev See {IERC20Permit-nonces}.
*/
function nonces(address owner) public view 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();
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
/**
* COPIED FROM https://github.com/OpenZeppelin/openzeppelin-contracts-upgradeable/tree/release-v3.4/contracts/drafts
* @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].
*/
abstract contract EIP712Upgradeable is Initializable {
/* solhint-disable var-name-mixedcase */
bytes32 private _HASHED_NAME;
bytes32 private _HASHED_VERSION;
bytes32 private constant _TYPE_HASH =
keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
);
/* solhint-enable var-name-mixedcase */
/**
* @dev Initializes the domain separator and parameter caches.
*
* The meaning of `name` and `version` is specified in
* https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
*
* - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
* - `version`: the current major version of the signing domain.
*
* NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
* contract upgrade].
*/
function __EIP712_init(string memory name, string memory version) internal initializer {
__EIP712_init_unchained(name, version);
}
function __EIP712_init_unchained(string memory name, string memory version)
internal
initializer
{
bytes32 hashedName = keccak256(bytes(name));
bytes32 hashedVersion = keccak256(bytes(version));
_HASHED_NAME = hashedName;
_HASHED_VERSION = hashedVersion;
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view returns (bytes32) {
return _buildDomainSeparator(_TYPE_HASH, _EIP712NameHash(), _EIP712VersionHash());
}
function _buildDomainSeparator(
bytes32 typeHash,
bytes32 name,
bytes32 version
) private view returns (bytes32) {
return keccak256(abi.encode(typeHash, name, version, _getChainId(), 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 returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", _domainSeparatorV4(), structHash));
}
function _getChainId() private view returns (uint256 chainId) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
// solhint-disable-next-line no-inline-assembly
assembly {
chainId := chainid()
}
}
/**
* @dev The hash of the name parameter for the EIP712 domain.
*
* NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs
* are a concern.
*/
function _EIP712NameHash() internal view virtual returns (bytes32) {
return _HASHED_NAME;
}
/**
* @dev The hash of the version parameter for the EIP712 domain.
*
* NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs
* are a concern.
*/
function _EIP712VersionHash() internal view virtual returns (bytes32) {
return _HASHED_VERSION;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
/// @notice the intention of this library is to be able to easily convert
/// one amount of tokens with N decimal places
/// to another amount with M decimal places
library DecimalsConverter {
using SafeMath for uint256;
function convert(
uint256 amount,
uint256 baseDecimals,
uint256 destinationDecimals
) internal pure returns (uint256) {
if (baseDecimals > destinationDecimals) {
amount = amount.div(10**(baseDecimals - destinationDecimals));
} else if (baseDecimals < destinationDecimals) {
amount = amount.mul(10**(destinationDecimals - baseDecimals));
}
return amount;
}
function convertTo18(uint256 amount, uint256 baseDecimals) internal pure returns (uint256) {
return convert(amount, baseDecimals, 18);
}
function convertFrom18(uint256 amount, uint256 destinationDecimals)
internal
pure
returns (uint256)
{
return convert(amount, 18, destinationDecimals);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* COPIED FROM https://github.com/OpenZeppelin/openzeppelin-contracts-upgradeable/tree/release-v3.4/contracts/drafts
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/
interface IERC20PermitUpgradeable {
/**
* @dev Sets `value` as the allowance of `spender` over `owner`'s tokens,
* given `owner`'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for `permit`, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
interface IRewardsGenerator {
struct PolicyBookRewardInfo {
uint256 rewardMultiplier; // includes 5 decimal places
uint256 totalStaked;
uint256 lastUpdateBlock;
uint256 lastCumulativeSum; // includes 100 percentage
uint256 cumulativeReward; // includes 100 percentage
}
struct StakeRewardInfo {
uint256 lastCumulativeSum; // includes 100 percentage
uint256 cumulativeReward;
uint256 stakeAmount;
}
/// @notice this function is called every time policybook's STBL to bmiX rate changes
function updatePolicyBookShare(uint256 newRewardMultiplier) external;
/// @notice aggregates specified nfts into a single one
function aggregate(
address policyBookAddress,
uint256[] calldata nftIndexes,
uint256 nftIndexTo
) external;
/// @notice migrates stake from the LegacyRewardsGenerator (will be called once for each user)
/// the rewards multipliers must be set in advance
function migrationStake(
address policyBookAddress,
uint256 nftIndex,
uint256 amount,
uint256 currentReward
) external;
/// @notice informs generator of stake (rewards)
function stake(
address policyBookAddress,
uint256 nftIndex,
uint256 amount
) external;
/// @notice returns policybook's APY multiplied by 10**5
function getPolicyBookAPY(address policyBookAddress) external view returns (uint256);
/// @notice returns policybook's RewardMultiplier multiplied by 10**5
function getPolicyBookRewardMultiplier(address policyBookAddress)
external
view
returns (uint256);
/// @dev returns PolicyBook reward per block multiplied by 10**25
function getPolicyBookRewardPerBlock(address policyBookAddress)
external
view
returns (uint256);
/// @notice returns PolicyBook's staked STBL
function getStakedPolicyBookSTBL(address policyBookAddress) external view returns (uint256);
/// @notice returns NFT's staked STBL
function getStakedNFTSTBL(uint256 nftIndex) external view returns (uint256);
/// @notice returns a reward of NFT
function getReward(address policyBookAddress, uint256 nftIndex)
external
view
returns (uint256);
/// @notice informs generator of withdrawal (all funds)
function withdrawFunds(address policyBookAddress, uint256 nftIndex) external returns (uint256);
/// @notice informs generator of withdrawal (rewards)
function withdrawReward(address policyBookAddress, uint256 nftIndex)
external
returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
import "./IPolicyBookFabric.sol";
import "./IClaimingRegistry.sol";
interface IPolicyRegistry {
struct PolicyInfo {
uint256 coverAmount;
uint256 premium;
uint256 startTime;
uint256 endTime;
}
struct PolicyUserInfo {
string symbol;
address insuredContract;
IPolicyBookFabric.ContractType contractType;
uint256 coverTokens;
uint256 startTime;
uint256 endTime;
uint256 paid;
}
function STILL_CLAIMABLE_FOR() external view returns (uint256);
/// @notice Returns the number of the policy for the user, access: ANY
/// @param _userAddr Policy holder address
/// @return the number of police in the array
function getPoliciesLength(address _userAddr) external view returns (uint256);
/// @notice Shows whether the user has a policy, access: ANY
/// @param _userAddr Policy holder address
/// @param _policyBookAddr Address of policy book
/// @return true if user has policy in specific policy book
function policyExists(address _userAddr, address _policyBookAddr) external view returns (bool);
/// @notice Returns information about current policy, access: ANY
/// @param _userAddr Policy holder address
/// @param _policyBookAddr Address of policy book
/// @return true if user has active policy in specific policy book
function isPolicyActive(address _userAddr, address _policyBookAddr)
external
view
returns (bool);
/// @notice returns current policy start time or zero
function policyStartTime(address _userAddr, address _policyBookAddr)
external
view
returns (uint256);
/// @notice returns current policy end time or zero
function policyEndTime(address _userAddr, address _policyBookAddr)
external
view
returns (uint256);
/// @notice Returns the array of the policy itself , access: ANY
/// @param _userAddr Policy holder address
/// @param _isActive If true, then returns an array with information about active policies, if false, about inactive
/// @return _policiesCount is the number of police in the array
/// @return _policyBooksArr is the array of policy books addresses
/// @return _policies is the array of policies
/// @return _policyStatuses parameter will show which button to display on the dashboard
function getPoliciesInfo(
address _userAddr,
bool _isActive,
uint256 _offset,
uint256 _limit
)
external
view
returns (
uint256 _policiesCount,
address[] memory _policyBooksArr,
PolicyInfo[] memory _policies,
IClaimingRegistry.ClaimStatus[] memory _policyStatuses
);
/// @notice Getting stats from users of policy books, access: ANY
function getUsersInfo(address[] calldata _users, address[] calldata _policyBooks)
external
view
returns (PolicyUserInfo[] memory _stats);
function getPoliciesArr(address _userAddr) external view returns (address[] memory _arr);
/// @notice Adds a new policy to the list , access: ONLY POLICY BOOKS
/// @param _userAddr is the user's address
/// @param _coverAmount is the number of insured tokens
/// @param _premium is the name of PolicyBook
/// @param _durationDays is the number of days for which the insured
function addPolicy(
address _userAddr,
uint256 _coverAmount,
uint256 _premium,
uint256 _durationDays
) external;
/// @notice Removes the policy book from the list, access: ONLY POLICY BOOKS
/// @param _userAddr is the user's address
function removePolicy(address _userAddr) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
interface IPolicyQuote {
/// @notice Let user to calculate policy cost in stable coin, access: ANY
/// @param _durationSeconds is number of seconds to cover
/// @param _tokens is a number of tokens to cover
/// @param _totalCoverTokens is a number of covered tokens
/// @param _totalLiquidity is a liquidity amount
/// @param _totalLeveragedLiquidity is a totale deployed leverage to the pool
/// @param _safePricingModel the pricing model configured for this bool safe or risk
/// @return amount of stable coin policy costs
function getQuotePredefined(
uint256 _durationSeconds,
uint256 _tokens,
uint256 _totalCoverTokens,
uint256 _totalLiquidity,
uint256 _totalLeveragedLiquidity,
bool _safePricingModel
) external view returns (uint256, uint256);
/// @notice Let user to calculate policy cost in stable coin, access: ANY
/// @param _durationSeconds is number of seconds to cover
/// @param _tokens is number of tokens to cover
/// @param _policyBookAddr is address of policy book
/// @return amount of stable coin policy costs
function getQuote(
uint256 _durationSeconds,
uint256 _tokens,
address _policyBookAddr
) external view returns (uint256);
/// @notice setup all pricing model varlues
///@param _highRiskRiskyAssetThresholdPercentage URRp Utilization ration for pricing model when the assets is considered risky, %
///@param _lowRiskRiskyAssetThresholdPercentage URRp Utilization ration for pricing model when the assets is not considered risky, %
///@param _highRiskMinimumCostPercentage MC minimum cost of cover (Premium) when the assets is considered risky, %;
///@param _lowRiskMinimumCostPercentage MC minimum cost of cover (Premium), when the assets is not considered risky, %
///@param _minimumInsuranceCost minimum cost of insurance (Premium) , (10**18)
///@param _lowRiskMaxPercentPremiumCost TMCI target maximum cost of cover when the asset is not considered risky (Premium)
///@param _lowRiskMaxPercentPremiumCost100Utilization MCI not risky
///@param _highRiskMaxPercentPremiumCost TMCI target maximum cost of cover when the asset is considered risky (Premium)
///@param _highRiskMaxPercentPremiumCost100Utilization MCI risky
function setupPricingModel(
uint256 _highRiskRiskyAssetThresholdPercentage,
uint256 _lowRiskRiskyAssetThresholdPercentage,
uint256 _highRiskMinimumCostPercentage,
uint256 _lowRiskMinimumCostPercentage,
uint256 _minimumInsuranceCost,
uint256 _lowRiskMaxPercentPremiumCost,
uint256 _lowRiskMaxPercentPremiumCost100Utilization,
uint256 _highRiskMaxPercentPremiumCost,
uint256 _highRiskMaxPercentPremiumCost100Utilization
) external;
///@notice return min ur under the current pricing model
///@param _safePricingModel pricing model of the pool wethere it is safe or risky model
function getMINUR(bool _safePricingModel) external view returns (uint256 _minUR);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
import "./IPolicyBook.sol";
import "./ILeveragePortfolio.sol";
interface IPolicyBookFacade {
/// @notice Let user to buy policy by supplying stable coin, access: ANY
/// @param _epochsNumber period policy will cover
/// @param _coverTokens amount paid for the coverage
function buyPolicy(uint256 _epochsNumber, uint256 _coverTokens) external;
/// @param _holder who owns coverage
/// @param _epochsNumber period policy will cover
/// @param _coverTokens amount paid for the coverage
function buyPolicyFor(
address _holder,
uint256 _epochsNumber,
uint256 _coverTokens
) external;
function policyBook() external view returns (IPolicyBook);
function userLiquidity(address account) external view returns (uint256);
/// @notice virtual funds deployed by reinsurance pool
function VUreinsurnacePool() external view returns (uint256);
/// @notice leverage funds deployed by reinsurance pool
function LUreinsurnacePool() external view returns (uint256);
/// @notice leverage funds deployed by user leverage pool
function LUuserLeveragePool(address userLeveragePool) external view returns (uint256);
/// @notice total leverage funds deployed to the pool sum of (VUreinsurnacePool,LUreinsurnacePool,LUuserLeveragePool)
function totalLeveragedLiquidity() external view returns (uint256);
function userleveragedMPL() external view returns (uint256);
function reinsurancePoolMPL() external view returns (uint256);
function rebalancingThreshold() external view returns (uint256);
function safePricingModel() external view returns (bool);
/// @notice policyBookFacade initializer
/// @param pbProxy polciybook address upgreadable cotnract.
function __PolicyBookFacade_init(
address pbProxy,
address liquidityProvider,
uint256 initialDeposit
) external;
/// @param _epochsNumber period policy will cover
/// @param _coverTokens amount paid for the coverage
/// @param _distributor if it was sold buy a whitelisted distributor, it is distributor address to receive fee (commission)
function buyPolicyFromDistributor(
uint256 _epochsNumber,
uint256 _coverTokens,
address _distributor
) external;
/// @param _buyer who is buying the coverage
/// @param _epochsNumber period policy will cover
/// @param _coverTokens amount paid for the coverage
/// @param _distributor if it was sold buy a whitelisted distributor, it is distributor address to receive fee (commission)
function buyPolicyFromDistributorFor(
address _buyer,
uint256 _epochsNumber,
uint256 _coverTokens,
address _distributor
) external;
/// @notice Let user to add liquidity by supplying stable coin, access: ANY
/// @param _liquidityAmount is amount of stable coin tokens to secure
function addLiquidity(uint256 _liquidityAmount) external;
/// @notice Let user to add liquidity by supplying stable coin, access: ANY
/// @param _user the one taht add liquidity
/// @param _liquidityAmount is amount of stable coin tokens to secure
function addLiquidityFromDistributorFor(address _user, uint256 _liquidityAmount) external;
function addLiquidityAndStakeFor(
address _liquidityHolderAddr,
uint256 _liquidityAmount,
uint256 _stakeSTBLAmount
) external;
/// @notice Let user to add liquidity by supplying stable coin and stake it,
/// @dev access: ANY
function addLiquidityAndStake(uint256 _liquidityAmount, uint256 _stakeSTBLAmount) external;
/// @notice Let user to withdraw deposited liqiudity, access: ANY
function withdrawLiquidity() external;
/// @notice deploy leverage funds (RP lStable, ULP lStable)
/// @param deployedAmount uint256 the deployed amount to be added or substracted from the total liquidity
/// @param leveragePool whether user leverage or reinsurance leverage
function deployLeverageFundsAfterRebalance(
uint256 deployedAmount,
ILeveragePortfolio.LeveragePortfolio leveragePool
) external;
/// @notice deploy virtual funds (RP vStable)
/// @param deployedAmount uint256 the deployed amount to be added to the liquidity
function deployVirtualFundsAfterRebalance(uint256 deployedAmount) external;
///@dev in case ur changed of the pools by commit a claim or policy expired
function reevaluateProvidedLeverageStable() external;
/// @notice set the MPL for the user leverage and the reinsurance leverage
/// @param _userLeverageMPL uint256 value of the user leverage MPL
/// @param _reinsuranceLeverageMPL uint256 value of the reinsurance leverage MPL
function setMPLs(uint256 _userLeverageMPL, uint256 _reinsuranceLeverageMPL) external;
/// @notice sets the rebalancing threshold value
/// @param _newRebalancingThreshold uint256 rebalancing threshhold value
function setRebalancingThreshold(uint256 _newRebalancingThreshold) external;
/// @notice sets the rebalancing threshold value
/// @param _safePricingModel bool is pricing model safe (true) or not (false)
function setSafePricingModel(bool _safePricingModel) external;
/// @notice returns how many BMI tokens needs to approve in order to submit a claim
function getClaimApprovalAmount(address user) external view returns (uint256);
/// @notice upserts a withdraw request
/// @dev prevents adding a request if an already pending or ready request is open.
/// @param _tokensToWithdraw uint256 amount of tokens to withdraw
function requestWithdrawal(uint256 _tokensToWithdraw) external;
function listUserLeveragePools(uint256 offset, uint256 limit)
external
view
returns (address[] memory _userLeveragePools);
function countUserLeveragePools() external view returns (uint256);
/// @notice get utilization rate of the pool on chain
function getUtilizationRatioPercentage(bool withLeverage) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
interface IPolicyBookFabric {
enum ContractType {CONTRACT, STABLECOIN, SERVICE, EXCHANGE, VARIOUS}
/// @notice Create new Policy Book contract, access: ANY
/// @param _contract is Contract to create policy book for
/// @param _contractType is Contract to create policy book for
/// @param _description is bmiXCover token desription for this policy book
/// @param _projectSymbol replaces x in bmiXCover token symbol
/// @param _initialDeposit is an amount user deposits on creation (addLiquidity())
/// @return _policyBook is address of created contract
function create(
address _contract,
ContractType _contractType,
string calldata _description,
string calldata _projectSymbol,
uint256 _initialDeposit,
address _shieldMiningToken
) external returns (address);
function createLeveragePools(
address _insuranceContract,
ContractType _contractType,
string calldata _description,
string calldata _projectSymbol
) external returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
import "./IPolicyBookFabric.sol";
import "./IClaimingRegistry.sol";
import "./IPolicyBookFacade.sol";
interface IPolicyBook {
enum WithdrawalStatus {NONE, PENDING, READY, EXPIRED}
struct PolicyHolder {
uint256 coverTokens;
uint256 startEpochNumber;
uint256 endEpochNumber;
uint256 paid;
uint256 reinsurancePrice;
}
struct WithdrawalInfo {
uint256 withdrawalAmount;
uint256 readyToWithdrawDate;
bool withdrawalAllowed;
}
struct BuyPolicyParameters {
address buyer;
address holder;
uint256 epochsNumber;
uint256 coverTokens;
uint256 distributorFee;
address distributor;
}
function policyHolders(address _holder)
external
view
returns (
uint256,
uint256,
uint256,
uint256,
uint256
);
function policyBookFacade() external view returns (IPolicyBookFacade);
function setPolicyBookFacade(address _policyBookFacade) external;
function EPOCH_DURATION() external view returns (uint256);
function stblDecimals() external view returns (uint256);
function READY_TO_WITHDRAW_PERIOD() external view returns (uint256);
function whitelisted() external view returns (bool);
function epochStartTime() external view returns (uint256);
// @TODO: should we let DAO to change contract address?
/// @notice Returns address of contract this PolicyBook covers, access: ANY
/// @return _contract is address of covered contract
function insuranceContractAddress() external view returns (address _contract);
/// @notice Returns type of contract this PolicyBook covers, access: ANY
/// @return _type is type of contract
function contractType() external view returns (IPolicyBookFabric.ContractType _type);
function totalLiquidity() external view returns (uint256);
function totalCoverTokens() external view returns (uint256);
// /// @notice return MPL for user leverage pool
// function userleveragedMPL() external view returns (uint256);
// /// @notice return MPL for reinsurance pool
// function reinsurancePoolMPL() external view returns (uint256);
// function bmiRewardMultiplier() external view returns (uint256);
function withdrawalsInfo(address _userAddr)
external
view
returns (
uint256 _withdrawalAmount,
uint256 _readyToWithdrawDate,
bool _withdrawalAllowed
);
function __PolicyBook_init(
address _insuranceContract,
IPolicyBookFabric.ContractType _contractType,
string calldata _description,
string calldata _projectSymbol
) external;
function whitelist(bool _whitelisted) external;
function getEpoch(uint256 time) external view returns (uint256);
/// @notice get STBL equivalent
function convertBMIXToSTBL(uint256 _amount) external view returns (uint256);
/// @notice get BMIX equivalent
function convertSTBLToBMIX(uint256 _amount) external view returns (uint256);
/// @notice submits new claim of the policy book
function submitClaimAndInitializeVoting(string calldata evidenceURI) external;
/// @notice submits new appeal claim of the policy book
function submitAppealAndInitializeVoting(string calldata evidenceURI) external;
/// @notice updates info on claim acceptance
function commitClaim(
address claimer,
uint256 claimAmount,
uint256 claimEndTime,
IClaimingRegistry.ClaimStatus status
) external;
/// @notice forces an update of RewardsGenerator multiplier
function forceUpdateBMICoverStakingRewardMultiplier() external;
/// @notice function to get precise current cover and liquidity
function getNewCoverAndLiquidity()
external
view
returns (uint256 newTotalCoverTokens, uint256 newTotalLiquidity);
/// @notice view function to get precise policy price
/// @param _epochsNumber is number of epochs to cover
/// @param _coverTokens is number of tokens to cover
/// @param _buyer address of the user who buy the policy
/// @return totalSeconds is number of seconds to cover
/// @return totalPrice is the policy price which will pay by the buyer
function getPolicyPrice(
uint256 _epochsNumber,
uint256 _coverTokens,
address _buyer
)
external
view
returns (
uint256 totalSeconds,
uint256 totalPrice,
uint256 pricePercentage
);
/// @notice Let user to buy policy by supplying stable coin, access: ANY
/// @param _buyer who is transferring funds
/// @param _holder who owns coverage
/// @param _epochsNumber period policy will cover
/// @param _coverTokens amount paid for the coverage
/// @param _distributorFee distributor fee (commission). It can't be greater than PROTOCOL_PERCENTAGE
/// @param _distributor if it was sold buy a whitelisted distributor, it is distributor address to receive fee (commission)
function buyPolicy(
address _buyer,
address _holder,
uint256 _epochsNumber,
uint256 _coverTokens,
uint256 _distributorFee,
address _distributor
) external returns (uint256, uint256);
function updateEpochsInfo() external;
function secondsToEndCurrentEpoch() external view returns (uint256);
/// @notice Let eligible contracts add liqiudity for another user by supplying stable coin
/// @param _liquidityHolderAddr is address of address to assign cover
/// @param _liqudityAmount is amount of stable coin tokens to secure
function addLiquidityFor(address _liquidityHolderAddr, uint256 _liqudityAmount) external;
/// @notice Let user to add liquidity by supplying stable coin, access: ANY
/// @param _liquidityBuyerAddr address the one that transfer funds
/// @param _liquidityHolderAddr address the one that owns liquidity
/// @param _liquidityAmount uint256 amount to be added on behalf the sender
/// @param _stakeSTBLAmount uint256 the staked amount if add liq and stake
function addLiquidity(
address _liquidityBuyerAddr,
address _liquidityHolderAddr,
uint256 _liquidityAmount,
uint256 _stakeSTBLAmount
) external returns (uint256);
function getAvailableBMIXWithdrawableAmount(address _userAddr) external view returns (uint256);
function getWithdrawalStatus(address _userAddr) external view returns (WithdrawalStatus);
function requestWithdrawal(uint256 _tokensToWithdraw, address _user) external;
// function requestWithdrawalWithPermit(
// uint256 _tokensToWithdraw,
// uint8 _v,
// bytes32 _r,
// bytes32 _s
// ) external;
function unlockTokens() external;
/// @notice Let user to withdraw deposited liqiudity, access: ANY
function withdrawLiquidity(address sender) external returns (uint256);
///@notice for doing defi hard rebalancing, access: policyBookFacade
function updateLiquidity(uint256 _newLiquidity) external;
function getAPY() external view returns (uint256);
/// @notice Getting user stats, access: ANY
function userStats(address _user) external view returns (PolicyHolder memory);
/// @notice Getting number stats, access: ANY
/// @return _maxCapacities is a max token amount that a user can buy
/// @return _totalSTBLLiquidity is PolicyBook's liquidity
/// @return _totalLeveragedLiquidity is PolicyBook's leveraged liquidity
/// @return _stakedSTBL is how much stable coin are staked on this PolicyBook
/// @return _annualProfitYields is its APY
/// @return _annualInsuranceCost is percentage of cover tokens that is required to be paid for 1 year of insurance
function numberStats()
external
view
returns (
uint256 _maxCapacities,
uint256 _totalSTBLLiquidity,
uint256 _totalLeveragedLiquidity,
uint256 _stakedSTBL,
uint256 _annualProfitYields,
uint256 _annualInsuranceCost,
uint256 _bmiXRatio
);
/// @notice Getting info, access: ANY
/// @return _symbol is the symbol of PolicyBook (bmiXCover)
/// @return _insuredContract is an addres of insured contract
/// @return _contractType is a type of insured contract
/// @return _whitelisted is a state of whitelisting
function info()
external
view
returns (
string memory _symbol,
address _insuredContract,
IPolicyBookFabric.ContractType _contractType,
bool _whitelisted
);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
interface INFTStaking {
/// @notice let user lock NFT, access: ANY
/// @param _nftId is the NFT id which locked
function lockNFT(uint256 _nftId) external;
/// @notice let user unlcok NFT if enabled, access: ANY
/// @param _nftId is the NFT id which unlocked
function unlockNFT(uint256 _nftId) external;
/// @notice get user reduction multiplier for policy premium, access: PolicyBook
/// @param _user is the user who locked NFT
/// @return reduction multiplier of locked NFT by user
function getUserReductionMultiplier(address _user) external view returns (uint256);
/// @notice return enabledlockingNFTs state, access: ANY
/// if true user can't unlock NFT and vice versa
function enabledlockingNFTs() external view returns (bool);
/// @notice To enable/disable locking of the NFTs
/// @param _enabledlockingNFTs is a state for enable/disbale locking of the NFT
function enableLockingNFTs(bool _enabledlockingNFTs) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
interface ILiquidityRegistry {
struct LiquidityInfo {
address policyBookAddr;
uint256 lockedAmount;
uint256 availableAmount;
uint256 bmiXRatio; // multiply availableAmount by this num to get stable coin
}
struct WithdrawalRequestInfo {
address policyBookAddr;
uint256 requestAmount;
uint256 requestSTBLAmount;
uint256 availableLiquidity;
uint256 readyToWithdrawDate;
uint256 endWithdrawDate;
}
struct WithdrawalSetInfo {
address policyBookAddr;
uint256 requestAmount;
uint256 requestSTBLAmount;
uint256 availableSTBLAmount;
}
function tryToAddPolicyBook(address _userAddr, address _policyBookAddr) external;
function tryToRemovePolicyBook(address _userAddr, address _policyBookAddr) external;
function removeExpiredWithdrawalRequest(address _userAddr, address _policyBookAddr) external;
function getPolicyBooksArrLength(address _userAddr) external view returns (uint256);
function getPolicyBooksArr(address _userAddr)
external
view
returns (address[] memory _resultArr);
function getLiquidityInfos(
address _userAddr,
uint256 _offset,
uint256 _limit
) external view returns (LiquidityInfo[] memory _resultArr);
function getWithdrawalRequests(
address _userAddr,
uint256 _offset,
uint256 _limit
) external view returns (uint256 _arrLength, WithdrawalRequestInfo[] memory _resultArr);
function getWithdrawalSet(
address _userAddr,
uint256 _offset,
uint256 _limit
) external view returns (uint256 _arrLength, WithdrawalSetInfo[] memory _resultArr);
function registerWithdrawl(address _policyBook, address _users) external;
function getAllPendingWithdrawalRequestsAmount()
external
returns (uint256 _totalWithdrawlAmount);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
interface ILiquidityMining {
struct TeamDetails {
string teamName;
address referralLink;
uint256 membersNumber;
uint256 totalStakedAmount;
uint256 totalReward;
}
struct UserInfo {
address userAddr;
string teamName;
uint256 stakedAmount;
uint256 mainNFT; // 0 or NFT index if available
uint256 platinumNFT; // 0 or NFT index if available
}
struct UserRewardsInfo {
string teamName;
uint256 totalBMIReward; // total BMI reward
uint256 availableBMIReward; // current claimable BMI reward
uint256 incomingPeriods; // how many month are incoming
uint256 timeToNextDistribution; // exact time left to next distribution
uint256 claimedBMI; // actual number of claimed BMI
uint256 mainNFTAvailability; // 0 or NFT index if available
uint256 platinumNFTAvailability; // 0 or NFT index if available
bool claimedNFTs; // true if user claimed NFTs
}
struct MyTeamInfo {
TeamDetails teamDetails;
uint256 myStakedAmount;
uint256 teamPlace;
}
struct UserTeamInfo {
address teamAddr;
uint256 stakedAmount;
uint256 countOfRewardedMonth;
bool isNFTDistributed;
}
struct TeamInfo {
string name;
uint256 totalAmount;
address[] teamLeaders;
}
function startLiquidityMiningTime() external view returns (uint256);
function getTopTeams() external view returns (TeamDetails[] memory teams);
function getTopUsers() external view returns (UserInfo[] memory users);
function getAllTeamsLength() external view returns (uint256);
function getAllTeamsDetails(uint256 _offset, uint256 _limit)
external
view
returns (TeamDetails[] memory _teamDetailsArr);
function getMyTeamsLength() external view returns (uint256);
function getMyTeamMembers(uint256 _offset, uint256 _limit)
external
view
returns (address[] memory _teamMembers, uint256[] memory _memberStakedAmount);
function getAllUsersLength() external view returns (uint256);
function getAllUsersInfo(uint256 _offset, uint256 _limit)
external
view
returns (UserInfo[] memory _userInfos);
function getMyTeamInfo() external view returns (MyTeamInfo memory _myTeamInfo);
function getRewardsInfo(address user)
external
view
returns (UserRewardsInfo memory userRewardInfo);
function createTeam(string calldata _teamName) external;
function deleteTeam() external;
function joinTheTeam(address _referralLink) external;
function getSlashingPercentage() external view returns (uint256);
function investSTBL(uint256 _tokensAmount, address _policyBookAddr) external;
function distributeNFT() external;
function checkPlatinumNFTReward(address _userAddr) external view returns (uint256);
function checkMainNFTReward(address _userAddr) external view returns (uint256);
function distributeBMIReward() external;
function getTotalUserBMIReward(address _userAddr) external view returns (uint256);
function checkAvailableBMIReward(address _userAddr) external view returns (uint256);
/// @notice checks if liquidity mining event is lasting (startLiquidityMining() has been called)
/// @return true if LM is started and not ended, false otherwise
function isLMLasting() external view returns (bool);
/// @notice checks if liquidity mining event is finished. In order to be finished, it has to be started
/// @return true if LM is finished, false if event is still going or not started
function isLMEnded() external view returns (bool);
function getEndLMTime() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
interface ILeveragePortfolio {
enum LeveragePortfolio {USERLEVERAGEPOOL, REINSURANCEPOOL}
struct LevFundsFactors {
uint256 netMPL;
uint256 netMPLn;
address policyBookAddr;
}
function targetUR() external view returns (uint256);
function d_ProtocolConstant() external view returns (uint256);
function a_ProtocolConstant() external view returns (uint256);
function max_ProtocolConstant() external view returns (uint256);
/// @notice deploy lStable from user leverage pool or reinsurance pool using 2 formulas: access by policybook.
/// @param leveragePoolType LeveragePortfolio is determine the pool which call the function
function deployLeverageStableToCoveragePools(LeveragePortfolio leveragePoolType)
external
returns (uint256);
/// @notice deploy the vStable from RP in v2 and for next versions it will be from RP and LP : access by policybook.
function deployVirtualStableToCoveragePools() external returns (uint256);
/// @notice set the threshold % for re-evaluation of the lStable provided across all Coverage pools : access by owner
/// @param threshold uint256 is the reevaluatation threshold
function setRebalancingThreshold(uint256 threshold) external;
/// @notice set the protocol constant : access by owner
/// @param _targetUR uint256 target utitlization ration
/// @param _d_ProtocolConstant uint256 D protocol constant
/// @param _a1_ProtocolConstant uint256 A1 protocol constant
/// @param _max_ProtocolConstant uint256 the max % included
function setProtocolConstant(
uint256 _targetUR,
uint256 _d_ProtocolConstant,
uint256 _a1_ProtocolConstant,
uint256 _max_ProtocolConstant
) external;
/// @notice calc M factor by formual M = min( abs((1/ (Tur-UR))*d) /a, max)
/// @param poolUR uint256 utitilization ratio for a coverage pool
/// @return uint256 M facotr
//function calcM(uint256 poolUR) external returns (uint256);
/// @return uint256 the amount of vStable stored in the pool
function totalLiquidity() external view returns (uint256);
/// @notice add the portion of 80% of premium to user leverage pool where the leverage provide lstable : access policybook
/// add the 20% of premium + portion of 80% of premium where reisnurance pool participate in coverage pools (vStable) : access policybook
/// @param epochsNumber uint256 the number of epochs which the policy holder will pay a premium for
/// @param premiumAmount uint256 the premium amount which is a portion of 80% of the premium
function addPolicyPremium(uint256 epochsNumber, uint256 premiumAmount) external;
/// @notice Used to get a list of coverage pools which get leveraged , use with count()
/// @return _coveragePools a list containing policybook addresses
function listleveragedCoveragePools(uint256 offset, uint256 limit)
external
view
returns (address[] memory _coveragePools);
/// @notice get count of coverage pools which get leveraged
function countleveragedCoveragePools() external view returns (uint256);
function updateLiquidity(uint256 _lostLiquidity) external;
function forceUpdateBMICoverStakingRewardMultiplier() external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
interface IContractsRegistry {
function getUniswapRouterContract() external view returns (address);
function getUniswapBMIToETHPairContract() external view returns (address);
function getUniswapBMIToUSDTPairContract() external view returns (address);
function getSushiswapRouterContract() external view returns (address);
function getSushiswapBMIToETHPairContract() external view returns (address);
function getSushiswapBMIToUSDTPairContract() external view returns (address);
function getSushiSwapMasterChefV2Contract() external view returns (address);
function getWETHContract() external view returns (address);
function getUSDTContract() external view returns (address);
function getBMIContract() external view returns (address);
function getPriceFeedContract() external view returns (address);
function getPolicyBookRegistryContract() external view returns (address);
function getPolicyBookFabricContract() external view returns (address);
function getBMICoverStakingContract() external view returns (address);
function getBMICoverStakingViewContract() external view returns (address);
function getLegacyRewardsGeneratorContract() external view returns (address);
function getRewardsGeneratorContract() external view returns (address);
function getBMIUtilityNFTContract() external view returns (address);
function getNFTStakingContract() external view returns (address);
function getLiquidityBridgeContract() external view returns (address);
function getClaimingRegistryContract() external view returns (address);
function getPolicyRegistryContract() external view returns (address);
function getLiquidityRegistryContract() external view returns (address);
function getClaimVotingContract() external view returns (address);
function getReinsurancePoolContract() external view returns (address);
function getLeveragePortfolioViewContract() external view returns (address);
function getCapitalPoolContract() external view returns (address);
function getPolicyBookAdminContract() external view returns (address);
function getPolicyQuoteContract() external view returns (address);
function getLegacyBMIStakingContract() external view returns (address);
function getBMIStakingContract() external view returns (address);
function getSTKBMIContract() external view returns (address);
function getVBMIContract() external view returns (address);
function getLegacyLiquidityMiningStakingContract() external view returns (address);
function getLiquidityMiningStakingETHContract() external view returns (address);
function getLiquidityMiningStakingUSDTContract() external view returns (address);
function getReputationSystemContract() external view returns (address);
function getAaveProtocolContract() external view returns (address);
function getAaveLendPoolAddressProvdierContract() external view returns (address);
function getAaveATokenContract() external view returns (address);
function getCompoundProtocolContract() external view returns (address);
function getCompoundCTokenContract() external view returns (address);
function getCompoundComptrollerContract() external view returns (address);
function getYearnProtocolContract() external view returns (address);
function getYearnVaultContract() external view returns (address);
function getYieldGeneratorContract() external view returns (address);
function getShieldMiningContract() external view returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
import "./IPolicyBookFabric.sol";
interface IClaimingRegistry {
enum ClaimStatus {
CAN_CLAIM,
UNCLAIMABLE,
PENDING,
AWAITING_CALCULATION,
REJECTED_CAN_APPEAL,
REJECTED,
ACCEPTED
}
struct ClaimInfo {
address claimer;
address policyBookAddress;
string evidenceURI;
uint256 dateSubmitted;
uint256 dateEnded;
bool appeal;
ClaimStatus status;
uint256 claimAmount;
}
/// @notice returns anonymous voting duration
function anonymousVotingDuration(uint256 index) external view returns (uint256);
/// @notice returns the whole voting duration
function votingDuration(uint256 index) external view returns (uint256);
/// @notice returns how many time should pass before anyone could calculate a claim result
function anyoneCanCalculateClaimResultAfter(uint256 index) external view returns (uint256);
/// @notice returns true if a user can buy new policy of specified PolicyBook
function canBuyNewPolicy(address buyer, address policyBookAddress)
external
view
returns (bool);
/// @notice submits new PolicyBook claim for the user
function submitClaim(
address user,
address policyBookAddress,
string calldata evidenceURI,
uint256 cover,
bool appeal
) external returns (uint256);
/// @notice returns true if the claim with this index exists
function claimExists(uint256 index) external view returns (bool);
/// @notice returns claim submition time
function claimSubmittedTime(uint256 index) external view returns (uint256);
/// @notice returns claim end time or zero in case it is pending
function claimEndTime(uint256 index) external view returns (uint256);
/// @notice returns true if the claim is anonymously votable
function isClaimAnonymouslyVotable(uint256 index) external view returns (bool);
/// @notice returns true if the claim is exposably votable
function isClaimExposablyVotable(uint256 index) external view returns (bool);
/// @notice returns true if claim is anonymously votable or exposably votable
function isClaimVotable(uint256 index) external view returns (bool);
/// @notice returns true if a claim can be calculated by anyone
function canClaimBeCalculatedByAnyone(uint256 index) external view returns (bool);
/// @notice returns true if this claim is pending or awaiting
function isClaimPending(uint256 index) external view returns (bool);
/// @notice returns how many claims the holder has
function countPolicyClaimerClaims(address user) external view returns (uint256);
/// @notice returns how many pending claims are there
function countPendingClaims() external view returns (uint256);
/// @notice returns how many claims are there
function countClaims() external view returns (uint256);
/// @notice returns a claim index of it's claimer and an ordinal number
function claimOfOwnerIndexAt(address claimer, uint256 orderIndex)
external
view
returns (uint256);
/// @notice returns pending claim index by its ordinal index
function pendingClaimIndexAt(uint256 orderIndex) external view returns (uint256);
/// @notice returns claim index by its ordinal index
function claimIndexAt(uint256 orderIndex) external view returns (uint256);
/// @notice returns current active claim index by policybook and claimer
function claimIndex(address claimer, address policyBookAddress)
external
view
returns (uint256);
/// @notice returns true if the claim is appealed
function isClaimAppeal(uint256 index) external view returns (bool);
/// @notice returns current status of a claim
function policyStatus(address claimer, address policyBookAddress)
external
view
returns (ClaimStatus);
/// @notice returns current status of a claim
function claimStatus(uint256 index) external view returns (ClaimStatus);
/// @notice returns the claim owner (claimer)
function claimOwner(uint256 index) external view returns (address);
/// @notice returns the claim PolicyBook
function claimPolicyBook(uint256 index) external view returns (address);
/// @notice returns claim info by its index
function claimInfo(uint256 index) external view returns (ClaimInfo memory _claimInfo);
function getAllPendingClaimsAmount() external view returns (uint256 _totalClaimsAmount);
function getClaimableAmounts(uint256[] memory _claimIndexes) external view returns (uint256);
/// @notice marks the user's claim as Accepted
function acceptClaim(uint256 index) external;
/// @notice marks the user's claim as Rejected
function rejectClaim(uint256 index) external;
/// @notice Update Image Uri in case it contains material that is ilegal
/// or offensive.
/// @dev Only the owner of the PolicyBookAdmin can erase/update evidenceUri.
/// @param _claimIndex Claim Index that is going to be updated
/// @param _newEvidenceURI New evidence uri. It can be blank.
function updateImageUriOfClaim(uint256 _claimIndex, string calldata _newEvidenceURI) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
import "./IClaimingRegistry.sol";
interface IClaimVoting {
enum VoteStatus {
ANONYMOUS_PENDING,
AWAITING_EXPOSURE,
EXPIRED,
EXPOSED_PENDING,
AWAITING_CALCULATION,
MINORITY,
MAJORITY
}
struct VotingResult {
uint256 withdrawalAmount;
uint256 lockedBMIAmount;
uint256 reinsuranceTokensAmount;
uint256 votedAverageWithdrawalAmount;
uint256 votedYesStakedBMIAmountWithReputation;
uint256 votedNoStakedBMIAmountWithReputation;
uint256 allVotedStakedBMIAmount;
uint256 votedYesPercentage;
}
struct VotingInst {
uint256 claimIndex;
bytes32 finalHash;
string encryptedVote;
address voter;
uint256 voterReputation;
uint256 suggestedAmount;
uint256 stakedBMIAmount;
bool accept;
VoteStatus status;
}
struct MyClaimInfo {
uint256 index;
address policyBookAddress;
string evidenceURI;
bool appeal;
uint256 claimAmount;
IClaimingRegistry.ClaimStatus finalVerdict;
uint256 finalClaimAmount;
uint256 bmiCalculationReward;
}
struct PublicClaimInfo {
uint256 claimIndex;
address claimer;
address policyBookAddress;
string evidenceURI;
bool appeal;
uint256 claimAmount;
uint256 time;
}
struct AllClaimInfo {
PublicClaimInfo publicClaimInfo;
IClaimingRegistry.ClaimStatus finalVerdict;
uint256 finalClaimAmount;
uint256 bmiCalculationReward;
}
struct MyVoteInfo {
AllClaimInfo allClaimInfo;
string encryptedVote;
uint256 suggestedAmount;
VoteStatus status;
uint256 time;
}
struct VotesUpdatesInfo {
uint256 bmiReward;
uint256 stblReward;
int256 reputationChange;
int256 stakeChange;
}
/// @notice starts the voting process
function initializeVoting(
address claimer,
string calldata evidenceURI,
uint256 coverTokens,
bool appeal
) external;
/// @notice returns true if the user has no PENDING votes
function canWithdraw(address user) external view returns (bool);
/// @notice returns true if the user has no AWAITING_CALCULATION votes
function canVote(address user) external view returns (bool);
/// @notice returns how many votes the user has
function countVotes(address user) external view returns (uint256);
/// @notice returns status of the vote
function voteStatus(uint256 index) external view returns (VoteStatus);
/// @notice returns a list of claims that are votable for msg.sender
function whatCanIVoteFor(uint256 offset, uint256 limit)
external
returns (uint256 _claimsCount, PublicClaimInfo[] memory _votablesInfo);
/// @notice returns info list of ALL claims
function allClaims(uint256 offset, uint256 limit)
external
view
returns (AllClaimInfo[] memory _allClaimsInfo);
/// @notice returns info list of claims of msg.sender
function myClaims(uint256 offset, uint256 limit)
external
view
returns (MyClaimInfo[] memory _myClaimsInfo);
/// @notice returns info list of claims that are voted by msg.sender
function myVotes(uint256 offset, uint256 limit)
external
view
returns (MyVoteInfo[] memory _myVotesInfo);
/// @notice returns an array of votes that can be calculated + update information
function myVotesUpdates(uint256 offset, uint256 limit)
external
view
returns (
uint256 _votesUpdatesCount,
uint256[] memory _claimIndexes,
VotesUpdatesInfo memory _myVotesUpdatesInfo
);
/// @notice anonymously votes (result used later in exposeVote())
/// @notice the claims have to be PENDING, the voter can vote only once for a specific claim
/// @param claimIndexes are the indexes of the claims the voter is voting on
/// (each one is unique for each claim and appeal)
/// @param finalHashes are the hashes produced by the encryption algorithm.
/// They will be verified onchain in expose function
/// @param encryptedVotes are the AES encrypted values that represent the actual vote
function anonymouslyVoteBatch(
uint256[] calldata claimIndexes,
bytes32[] calldata finalHashes,
string[] calldata encryptedVotes
) external;
/// @notice exposes votes of anonymous votings
/// @notice the vote has to be voted anonymously prior
/// @param claimIndexes are the indexes of the claims to expose votes for
/// @param suggestedClaimAmounts are the actual vote values.
/// They must match the decrypted values in anonymouslyVoteBatch function
/// @param hashedSignaturesOfClaims are the validation data needed to construct proper finalHashes
function exposeVoteBatch(
uint256[] calldata claimIndexes,
uint256[] calldata suggestedClaimAmounts,
bytes32[] calldata hashedSignaturesOfClaims
) external;
/// @notice calculates results of votes
function calculateVoterResultBatch(uint256[] calldata claimIndexes) external;
/// @notice calculates results of claims
function calculateVotingResultBatch(uint256[] calldata claimIndexes) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
import "./IPolicyBookFacade.sol";
interface ICapitalPool {
struct PremiumFactors {
uint256 epochsNumber;
uint256 premiumPrice;
uint256 vStblDeployedByRP;
uint256 vStblOfCP;
uint256 poolUtilizationRation;
uint256 premiumPerDeployment;
uint256 userLeveragePoolsCount;
IPolicyBookFacade policyBookFacade;
}
enum PoolType {COVERAGE, LEVERAGE, REINSURANCE}
function virtualUsdtAccumulatedBalance() external view returns (uint256);
function liquidityCushionBalance() external view returns (uint256);
/// @notice distributes the policybook premiums into pools (CP, ULP , RP)
/// @dev distributes the balances acording to the established percentages
/// @param _stblAmount amount hardSTBL ingressed into the system
/// @param _epochsNumber uint256 the number of epochs which the policy holder will pay a premium for
/// @param _protocolFee uint256 the amount of protocol fee earned by premium
function addPolicyHoldersHardSTBL(
uint256 _stblAmount,
uint256 _epochsNumber,
uint256 _protocolFee
) external returns (uint256);
/// @notice distributes the hardSTBL from the coverage providers
/// @dev emits PoolBalancedUpdated event
/// @param _stblAmount amount hardSTBL ingressed into the system
function addCoverageProvidersHardSTBL(uint256 _stblAmount) external;
/// @notice distributes the hardSTBL from the leverage providers
/// @dev emits PoolBalancedUpdated event
/// @param _stblAmount amount hardSTBL ingressed into the system
function addLeverageProvidersHardSTBL(uint256 _stblAmount) external;
/// @notice distributes the hardSTBL from the reinsurance pool
/// @dev emits PoolBalancedUpdated event
/// @param _stblAmount amount hardSTBL ingressed into the system
function addReinsurancePoolHardSTBL(uint256 _stblAmount) external;
/// @notice rebalances pools acording to v2 specification and dao enforced policies
/// @dev emits PoolBalancesUpdated
function rebalanceLiquidityCushion() external;
/// @notice Fullfils policybook claims by transfering the balance to claimer
/// @param _claimer, address of the claimer recieving the withdraw
/// @param _stblAmount uint256 amount to be withdrawn
function fundClaim(address _claimer, uint256 _stblAmount) external;
/// @notice Withdraws liquidity from a specific policbybook to the user
/// @param _sender, address of the user beneficiary of the withdraw
/// @param _stblAmount uint256 amount to be withdrawn
/// @param _isLeveragePool bool wether the pool is ULP or CP(policybook)
function withdrawLiquidity(
address _sender,
uint256 _stblAmount,
bool _isLeveragePool
) external;
function rebalanceDuration() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
import "./IBMICoverStaking.sol";
interface IBMICoverStakingView {
function getPolicyBookAPY(address policyBookAddress) external view returns (uint256);
function policyBookByNFT(uint256 tokenId) external view returns (address);
function stakingInfoByStaker(
address staker,
address[] calldata policyBooksAddresses,
uint256 offset,
uint256 limit
)
external
view
returns (
IBMICoverStaking.PolicyBookInfo[] memory policyBooksInfo,
IBMICoverStaking.UserInfo[] memory usersInfo,
uint256[] memory nftsCount,
IBMICoverStaking.NFTsInfo[][] memory nftsInfo
);
function stakingInfoByToken(uint256 tokenId)
external
view
returns (IBMICoverStaking.StakingInfo memory);
// Not Migratable
// function totalStaked(address user) external view returns (uint256);
// function totalStakedSTBL(address user) external view returns (uint256);
// function getStakerBMIProfit(address staker, address policyBookAddress, uint256 offset, uint256 limit) external view returns (uint256) ;
// function getSlashedBMIProfit(uint256 tokenId) external view returns (uint256);
// function getBMIProfit(uint256 tokenId) external view returns (uint256);
// function uri(uint256 tokenId) external view returns (string memory);
// function tokenOfOwnerByIndex(address user, uint256 index) external view returns (uint256);
// function ownerOf(uint256 tokenId) external view returns (address);
// function getSlashingPercentage() external view returns (uint256);
// function getSlashedStakerBMIProfit( address staker, address policyBookAddress, uint256 offset, uint256 limit) external view returns (uint256 totalProfit) ;
// function balanceOf(address user) external view returns (uint256);
// function _aggregateForEach( address staker, address policyBookAddress, uint256 offset, uint256 limit, function(uint256) view returns (uint256) func) internal view returns (uint256 total);
// function stakedByNFT(uint256 tokenId) external view returns (uint256);
// function stakedSTBLByNFT(uint256 tokenId) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
interface IBMICoverStaking {
struct StakingInfo {
address policyBookAddress;
uint256 stakedBMIXAmount;
}
struct PolicyBookInfo {
uint256 totalStakedSTBL;
uint256 rewardPerBlock;
uint256 stakingAPY;
uint256 liquidityAPY;
}
struct UserInfo {
uint256 totalStakedBMIX;
uint256 totalStakedSTBL;
uint256 totalBmiReward;
}
struct NFTsInfo {
uint256 nftIndex;
string uri;
uint256 stakedBMIXAmount;
uint256 stakedSTBLAmount;
uint256 reward;
}
function aggregateNFTs(address policyBookAddress, uint256[] calldata tokenIds) external;
function stakeBMIX(uint256 amount, address policyBookAddress) external;
function stakeBMIXWithPermit(
uint256 bmiXAmount,
address policyBookAddress,
uint8 v,
bytes32 r,
bytes32 s
) external;
function stakeBMIXFrom(address user, uint256 amount) external;
function stakeBMIXFromWithPermit(
address user,
uint256 bmiXAmount,
uint8 v,
bytes32 r,
bytes32 s
) external;
// mappings
function _stakersPool(uint256 index)
external
view
returns (address policyBookAddress, uint256 stakedBMIXAmount);
// function getPolicyBookAPY(address policyBookAddress) external view returns (uint256);
function restakeBMIProfit(uint256 tokenId) external;
function restakeStakerBMIProfit(address policyBookAddress) external;
function withdrawBMIProfit(uint256 tokenID) external;
function withdrawStakerBMIProfit(address policyBookAddress) external;
function withdrawFundsWithProfit(uint256 tokenID) external;
function withdrawStakerFundsWithProfit(address policyBookAddress) external;
function getSlashedBMIProfit(uint256 tokenId) external view returns (uint256);
function getBMIProfit(uint256 tokenId) external view returns (uint256);
function getSlashedStakerBMIProfit(
address staker,
address policyBookAddress,
uint256 offset,
uint256 limit
) external view returns (uint256 totalProfit);
function getStakerBMIProfit(
address staker,
address policyBookAddress,
uint256 offset,
uint256 limit
) external view returns (uint256 totalProfit);
function totalStaked(address user) external view returns (uint256);
function totalStakedSTBL(address user) external view returns (uint256);
function stakedByNFT(uint256 tokenId) external view returns (uint256);
function stakedSTBLByNFT(uint256 tokenId) external view returns (uint256);
function balanceOf(address user) external view returns (uint256);
function ownerOf(uint256 tokenId) external view returns (address);
function uri(uint256 tokenId) external view returns (string memory);
function tokenOfOwnerByIndex(address user, uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
import "../interfaces/IContractsRegistry.sol";
abstract contract AbstractDependant {
/// @dev keccak256(AbstractDependant.setInjector(address)) - 1
bytes32 private constant _INJECTOR_SLOT =
0xd6b8f2e074594ceb05d47c27386969754b6ad0c15e5eb8f691399cd0be980e76;
modifier onlyInjectorOrZero() {
address _injector = injector();
require(_injector == address(0) || _injector == msg.sender, "Dependant: Not an injector");
_;
}
function setInjector(address _injector) external onlyInjectorOrZero {
bytes32 slot = _INJECTOR_SLOT;
assembly {
sstore(slot, _injector)
}
}
/// @dev has to apply onlyInjectorOrZero() modifier
function setDependencies(IContractsRegistry) external virtual;
function injector() public view returns (address _injector) {
bytes32 slot = _INJECTOR_SLOT;
assembly {
_injector := sload(slot)
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
uint256 constant SECONDS_IN_THE_YEAR = 365 * 24 * 60 * 60; // 365 days * 24 hours * 60 minutes * 60 seconds
uint256 constant DAYS_IN_THE_YEAR = 365;
uint256 constant MAX_INT = type(uint256).max;
uint256 constant DECIMALS18 = 10**18;
uint256 constant PRECISION = 10**25;
uint256 constant PERCENTAGE_100 = 100 * PRECISION;
uint256 constant BLOCKS_PER_DAY = 6450;
uint256 constant BLOCKS_PER_YEAR = BLOCKS_PER_DAY * 365;
uint256 constant APY_TOKENS = DECIMALS18;
uint256 constant PROTOCOL_PERCENTAGE = 20 * PRECISION;
uint256 constant DEFAULT_REBALANCING_THRESHOLD = 10**23;
uint256 constant EPOCH_DAYS_AMOUNT = 7;
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "../../GSN/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../math/SafeMathUpgradeable.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 CountersUpgradeable {
using SafeMathUpgradeable 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;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../GSN/ContextUpgradeable.sol";
import "./IERC20Upgradeable.sol";
import "../../math/SafeMathUpgradeable.sol";
import "../../proxy/Initializable.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin 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 ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable {
using SafeMathUpgradeable for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
function __ERC20_init(string memory name_, string memory symbol_) internal initializer {
__Context_init_unchained();
__ERC20_init_unchained(name_, symbol_);
}
function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
uint256[44] private __gap;
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity >=0.4.24 <0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function _isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
// solhint-disable-next-line no-inline-assembly
assembly { cs := extcodesize(self) }
return cs == 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMathUpgradeable {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.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;
}
|
TODO: verify check additional state changes other than transfer
|
function commitClaim(
address claimer,
uint256 claimAmount,
uint256 claimEndTime,
IClaimingRegistry.ClaimStatus status
) external override onlyClaimVoting withPremiumsDistribution updateBMICoverStakingReward {
updateEpochsInfo();
uint256 cover = policyHolders[claimer].coverTokens;
if (status == IClaimingRegistry.ClaimStatus.ACCEPTED) {
uint256 newTotalCover = totalCoverTokens.sub(cover);
totalCoverTokens = newTotalCover;
capitalPool.fundClaim(claimer, claimAmount);
delete policyHolders[claimer];
policyRegistry.removePolicy(claimer);
uint256 endUnlockEpoch =
Math.max(
getEpoch(claimEndTime) + 1,
policyHolders[claimer].endEpochNumber + VIRTUAL_EPOCHS
);
epochAmounts[endUnlockEpoch] = epochAmounts[endUnlockEpoch].add(cover);
uint256 virtualEndEpochNumber =
policyHolders[claimer].endEpochNumber.add(VIRTUAL_EPOCHS);
if (lastDistributionEpoch <= virtualEndEpochNumber) {
epochAmounts[virtualEndEpochNumber] = epochAmounts[virtualEndEpochNumber].add(
cover
);
uint256 newTotalCover = totalCoverTokens.sub(cover);
totalCoverTokens = newTotalCover;
policyBookFacade.reevaluateProvidedLeverageStable();
emit CoverageChanged(newTotalCover);
}
}
}
| 9,946,722 |
./full_match/40/0x4Cab8a61C939A95b49977605548B7910a34Ec2C0/sources/project_/contracts/CustomBill.sol
|
_value uint return _payout uint return _fee uint/
|
function payoutFor(uint256 _value ) public view returns (uint256 _payout, uint256 _fee) {
If fee is in payout then takes in the already calculated value. If fee is in principal token
if(feeInPayout) {
uint total = _value * 1e18 / billPrice();
_fee = total.mul(currentFee()).div(1e6);
_payout = total.sub(_fee);
_fee = _value.mul(currentFee()).div(1e6);
_payout = customTreasury.valueOfToken(address(principalToken), _value.sub(_fee)) * 1e18 / billPrice();
}
} else {
}
| 9,544,660 |
./full_match/80001/0xFb5b58c5D536F42f15484f7ecf5814C028b42A4a/sources/DigitalaxGarmentNFTv2.sol
|
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 = DigitalaxERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || DigitalaxERC721.isApprovedForAll(owner, spender));
}
| 5,688,407 |
./partial_match/3/0x12A740BA21FB3c5c20aA05fd96107845Dc128e59/sources/TLAMB.sol
|
lambmap[msg.sender] = _remarks;
|
function transferRemarks(address _to, uint256 _value,bytes32 _remarks) public whenNotPaused returns (bool) {
bool result = transfer(_to,_value);
emit TransferRemarks(msg.sender, _to, _value,_remarks);
return result;
}
| 5,196,757 |
./partial_match/1/0x45A353132143f475B355620aD9d7413D0222Ea04/sources/APP.sol
|
Create `mintedAmount` tokens and send it to `target` target Address to receive the tokens mintedAmount the amount of tokens it will receive
|
function mintToken(address target, uint256 mintedAmount) onlyOwner {
balanceOf[target] += mintedAmount;
totalSupply += mintedAmount;
Transfer(0, this, mintedAmount);
Transfer(this, target, mintedAmount);
}
| 4,335,953 |
pragma solidity 0.5.16;
pragma experimental ABIEncoderV2;
/**
* @title Method Params Tester
* @dev Main goal of this contract is to check that execContractMethod works well for different input params
*/
contract MethodParamsTester {
/**
* @dev Basic method execution test
* @return string with pre-defined value
*/
function greet() public pure returns (string memory) {
return "Hello Ethereum Blockchain!";
}
/**
* @dev Checking that uint8 input parameter works
* @param inputValue parameter
* @return same value as in input parameter
*/
function uint8Test(uint8 inputValue) public pure returns(uint8) {
return inputValue;
}
/**
* @dev Checking that int8 input parameter works
* @param inputValue parameter
* @return same value as in input parameter
*/
function int8Test(int8 inputValue) public pure returns(int8) {
return inputValue;
}
/**
* @dev Checking that uint input parameter works
* @param inputValue parameter
* @return same value as in input parameter
*/
function uintTest(uint inputValue) public pure returns(uint) {
return inputValue;
}
/**
* @dev Checking that int input parameter works
* @param inputValue parameter
* @return same value as in input parameter
*/
function intTest(int inputValue) public pure returns(int) {
return inputValue;
}
/**
* @dev Checking that int[] array input parameter works
* @param inputValue array parameter
* @return same value as in input parameter
*/
function intArrayTest(int[] memory inputValue) public pure returns(int[] memory) {
return inputValue;
}
/**
* @dev Checking that bool[] array input parameter works
* @param inputValue array parameter
* @return same value as in input parameter
*/
function boolArrayTest(bool[] memory inputValue) public pure returns(bool[] memory) {
return inputValue;
}
/**
* @dev Checking that string[] array input parameter works
* @param inputValue array parameter
* @return same value as in input parameter
*/
function stringArrayTest(string[] memory inputValue) public pure returns(string memory)
{
if(keccak256(abi.encode(inputValue[0])) == keccak256(abi.encode("A1"))) {
return string(abi.encodePacked("test1", "test2", "test3"));
} else {
return string(abi.encodePacked("Something", "Went", "Wrong"));
}
}
/**
* @dev Checking that bytes input parameter works
* @param inputValue parameter
* @return same value as in input parameter
*/
function bytesArrayTest(bytes memory inputValue) public pure returns(bytes memory) {
return inputValue;
}
/**
* @dev Checking that bool input parameter works
* @param inputValue parameter
* @return same value as in input parameter
*/
function boolTest(bool inputValue) public pure returns(bool) {
return inputValue;
}
/**
* @dev Checking that string input parameter works
* @param inputValue parameter
* @return same value as in input parameter
*/
function stringTest(string memory inputValue) public pure returns(string memory) {
return inputValue;
}
/**
* @dev Checking that address input parameter works
* @param inputValue parameter
* @return same value as in input parameter
*/
function addressTest(address inputValue) public pure returns(address) {
return inputValue;
}
/**
* @dev Checking that byte input parameter works
* @param inputValue parameter
* @return same value as in input parameter
*/
function byteTest(byte inputValue) public pure returns(byte) {
return inputValue;
}
/**
* @dev Checking that multiple input parameters works
* @param inputValue1 int parameter
* @param inputValue2 int parameter
* @param inputValue3 string parameter
* @return string, which depends on input parameter
*/
function multipleParamsTest(int inputValue1, int inputValue2, string memory inputValue3) public pure returns(string memory) {
if(inputValue1 > inputValue2) {
return inputValue3;
} else {
return "inputValue2 < inputValue1";
}
}
}
|
Checking that int8 input parameter works inputValue parameter return same value as in input parameter/
|
function int8Test(int8 inputValue) public pure returns(int8) {
return inputValue;
}
| 12,587,514 |
/**
*Submitted for verification at Etherscan.io on 2021-03-31
*/
/**
Copyright 2020 PoolTogether Inc.
This file is part of PoolTogether.
PoolTogether 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 under version 3 of the License.
PoolTogether 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 PoolTogether. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.5.12;
contract GemLike {
function allowance(address, address) public returns (uint);
function approve(address, uint) public;
function transfer(address, uint) public returns (bool);
function transferFrom(address, address, uint) public returns (bool);
}
contract ValueLike {
function peek() public returns (uint, bool);
}
contract SaiTubLike {
function skr() public view returns (GemLike);
function gem() public view returns (GemLike);
function gov() public view returns (GemLike);
function sai() public view returns (GemLike);
function pep() public view returns (ValueLike);
function vox() public view returns (VoxLike);
function bid(uint) public view returns (uint);
function ink(bytes32) public view returns (uint);
function tag() public view returns (uint);
function tab(bytes32) public returns (uint);
function rap(bytes32) public returns (uint);
function draw(bytes32, uint) public;
function shut(bytes32) public;
function exit(uint) public;
function give(bytes32, address) public;
}
contract VoxLike {
function par() public returns (uint);
}
contract JoinLike {
function ilk() public returns (bytes32);
function gem() public returns (GemLike);
function dai() public returns (GemLike);
function join(address, uint) public;
function exit(address, uint) public;
}
contract VatLike {
function ilks(bytes32) public view returns (uint, uint, uint, uint, uint);
function hope(address) public;
function frob(bytes32, address, address, address, int, int) public;
}
contract ManagerLike {
function vat() public view returns (address);
function urns(uint) public view returns (address);
function open(bytes32, address) public returns (uint);
function frob(uint, int, int) public;
function give(uint, address) public;
function move(uint, address, uint) public;
}
contract OtcLike {
function getPayAmount(address, address, uint) public view returns (uint);
function buyAllAmount(address, uint, address, uint) public;
}
/**
Copyright 2020 PoolTogether Inc.
This file is part of PoolTogether.
PoolTogether 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 under version 3 of the License.
PoolTogether 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 PoolTogether. If not, see <https://www.gnu.org/licenses/>.
*/
/**
Copyright 2020 PoolTogether Inc.
This file is part of PoolTogether.
PoolTogether 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 under version 3 of the License.
PoolTogether 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 PoolTogether. If not, see <https://www.gnu.org/licenses/>.
*/
/**
* @dev Interface of the global ERC1820 Registry, as defined in the
* https://eips.ethereum.org/EIPS/eip-1820[EIP]. Accounts may register
* implementers for interfaces in this registry, as well as query support.
*
* Implementers may be shared by multiple accounts, and can also implement more
* than a single interface for each account. Contracts can implement interfaces
* for themselves, but externally-owned accounts (EOA) must delegate this to a
* contract.
*
* {IERC165} interfaces can also be queried via the registry.
*
* For an in-depth explanation and source code analysis, see the EIP text.
*/
interface IERC1820Registry {
/**
* @dev Sets `newManager` as the manager for `account`. A manager of an
* account is able to set interface implementers for it.
*
* By default, each account is its own manager. Passing a value of `0x0` in
* `newManager` will reset the manager to this initial state.
*
* Emits a {ManagerChanged} event.
*
* Requirements:
*
* - the caller must be the current manager for `account`.
*/
function setManager(address account, address newManager) external;
/**
* @dev Returns the manager for `account`.
*
* See {setManager}.
*/
function getManager(address account) external view returns (address);
/**
* @dev Sets the `implementer` contract as `account`'s implementer for
* `interfaceHash`.
*
* `account` being the zero address is an alias for the caller's address.
* The zero address can also be used in `implementer` to remove an old one.
*
* See {interfaceHash} to learn how these are created.
*
* Emits an {InterfaceImplementerSet} event.
*
* Requirements:
*
* - the caller must be the current manager for `account`.
* - `interfaceHash` must not be an {IERC165} interface id (i.e. it must not
* end in 28 zeroes).
* - `implementer` must implement {IERC1820Implementer} and return true when
* queried for support, unless `implementer` is the caller. See
* {IERC1820Implementer-canImplementInterfaceForAddress}.
*/
function setInterfaceImplementer(address account, bytes32 interfaceHash, address implementer) external;
/**
* @dev Returns the implementer of `interfaceHash` for `account`. If no such
* implementer is registered, returns the zero address.
*
* If `interfaceHash` is an {IERC165} interface id (i.e. it ends with 28
* zeroes), `account` will be queried for support of it.
*
* `account` being the zero address is an alias for the caller's address.
*/
function getInterfaceImplementer(address account, bytes32 interfaceHash) external view returns (address);
/**
* @dev Returns the interface hash for an `interfaceName`, as defined in the
* corresponding
* https://eips.ethereum.org/EIPS/eip-1820#interface-name[section of the EIP].
*/
function interfaceHash(string calldata interfaceName) external pure returns (bytes32);
/**
* @notice Updates the cache with whether the contract implements an ERC165 interface or not.
* @param account Address of the contract for which to update the cache.
* @param interfaceId ERC165 interface for which to update the cache.
*/
function updateERC165Cache(address account, bytes4 interfaceId) external;
/**
* @notice Checks whether a contract implements an ERC165 interface or not.
* If the result is not cached a direct lookup on the contract address is performed.
* If the result is not cached or the cached value is out-of-date, the cache MUST be updated manually by calling
* {updateERC165Cache} with the contract address.
* @param account Address of the contract to check.
* @param interfaceId ERC165 interface to check.
* @return True if `account` implements `interfaceId`, false otherwise.
*/
function implementsERC165Interface(address account, bytes4 interfaceId) external view returns (bool);
/**
* @notice Checks whether a contract implements an ERC165 interface or not without using nor updating the cache.
* @param account Address of the contract to check.
* @param interfaceId ERC165 interface to check.
* @return True if `account` implements `interfaceId`, false otherwise.
*/
function implementsERC165InterfaceNoCache(address account, bytes4 interfaceId) external view returns (bool);
event InterfaceImplementerSet(address indexed account, bytes32 indexed interfaceHash, address indexed implementer);
event ManagerChanged(address indexed account, address indexed newManager);
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
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;
}
}
/**
* @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.
uint256 cs;
assembly { cs := extcodesize(address) }
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
/**
* @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.
*/
contract ReentrancyGuard is Initializable {
// counter to allow mutex lock with only one SSTORE operation
uint256 private _guardCounter;
function initialize() public initializer {
// The counter starts at one to prevent changing it from zero to a non-zero
// value, which is a more expensive operation.
_guardCounter = 1;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_guardCounter += 1;
uint256 localCounter = _guardCounter;
_;
require(localCounter == _guardCounter, "ReentrancyGuard: reentrant call");
}
uint256[50] private ______gap;
}
/**
* @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];
}
}
/**
Copyright 2020 PoolTogether Inc.
This file is part of PoolTogether.
PoolTogether 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 under version 3 of the License.
PoolTogether 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 PoolTogether. If not, see <https://www.gnu.org/licenses/>.
*/
contract ICErc20 {
address public underlying;
function mint(uint256 mintAmount) external returns (uint);
function redeemUnderlying(uint256 redeemAmount) external returns (uint);
function balanceOfUnderlying(address owner) external returns (uint);
function getCash() external view returns (uint);
function supplyRatePerBlock() external view returns (uint);
}
/**
Copyright 2020 PoolTogether Inc.
This file is part of PoolTogether.
PoolTogether 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 under version 3 of the License.
PoolTogether 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 PoolTogether. If not, see <https://www.gnu.org/licenses/>.
*/
/**
Copyright 2020 PoolTogether Inc.
This file is part of PoolTogether.
PoolTogether 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 under version 3 of the License.
PoolTogether 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 PoolTogether. If not, see <https://www.gnu.org/licenses/>.
*/
/**
* @author Brendan Asselstine
* @notice A library that uses entropy to select a random number within a bound. Compensates for modulo bias.
* @dev Thanks to https://medium.com/hownetworks/dont-waste-cycles-with-modulo-bias-35b6fdafcf94
*/
library UniformRandomNumber {
/// @notice Select a random number without modulo bias using a random seed and upper bound
/// @param _entropy The seed for randomness
/// @param _upperBound The upper bound of the desired number
/// @return A random number less than the _upperBound
function uniform(uint256 _entropy, uint256 _upperBound) internal pure returns (uint256) {
require(_upperBound > 0, "UniformRand/min-bound");
uint256 min = -_upperBound % _upperBound;
uint256 random = _entropy;
while (true) {
if (random >= min) {
break;
}
random = uint256(keccak256(abi.encodePacked(random)));
}
return random % _upperBound;
}
}
/**
* @reviewers: [@clesaege, @unknownunknown1, @ferittuncer]
* @auditors: []
* @bounties: [<14 days 10 ETH max payout>]
* @deployments: []
*/
/**
* @title SortitionSumTreeFactory
* @author Enrique Piqueras - <[emailΒ protected]>
* @dev A factory of trees that keep track of staked values for sortition.
*/
library SortitionSumTreeFactory {
/* Structs */
struct SortitionSumTree {
uint K; // The maximum number of childs per node.
// We use this to keep track of vacant positions in the tree after removing a leaf. This is for keeping the tree as balanced as possible without spending gas on moving nodes around.
uint[] stack;
uint[] nodes;
// Two-way mapping of IDs to node indexes. Note that node index 0 is reserved for the root node, and means the ID does not have a node.
mapping(bytes32 => uint) IDsToNodeIndexes;
mapping(uint => bytes32) nodeIndexesToIDs;
}
/* Storage */
struct SortitionSumTrees {
mapping(bytes32 => SortitionSumTree) sortitionSumTrees;
}
/* internal */
/**
* @dev Create a sortition sum tree at the specified key.
* @param _key The key of the new tree.
* @param _K The number of children each node in the tree should have.
*/
function createTree(SortitionSumTrees storage self, bytes32 _key, uint _K) internal {
SortitionSumTree storage tree = self.sortitionSumTrees[_key];
require(tree.K == 0, "Tree already exists.");
require(_K > 1, "K must be greater than one.");
tree.K = _K;
tree.stack.length = 0;
tree.nodes.length = 0;
tree.nodes.push(0);
}
/**
* @dev Set a value of a tree.
* @param _key The key of the tree.
* @param _value The new value.
* @param _ID The ID of the value.
* `O(log_k(n))` where
* `k` is the maximum number of childs per node in the tree,
* and `n` is the maximum number of nodes ever appended.
*/
function set(SortitionSumTrees storage self, bytes32 _key, uint _value, bytes32 _ID) internal {
SortitionSumTree storage tree = self.sortitionSumTrees[_key];
uint treeIndex = tree.IDsToNodeIndexes[_ID];
if (treeIndex == 0) { // No existing node.
if (_value != 0) { // Non zero value.
// Append.
// Add node.
if (tree.stack.length == 0) { // No vacant spots.
// Get the index and append the value.
treeIndex = tree.nodes.length;
tree.nodes.push(_value);
// Potentially append a new node and make the parent a sum node.
if (treeIndex != 1 && (treeIndex - 1) % tree.K == 0) { // Is first child.
uint parentIndex = treeIndex / tree.K;
bytes32 parentID = tree.nodeIndexesToIDs[parentIndex];
uint newIndex = treeIndex + 1;
tree.nodes.push(tree.nodes[parentIndex]);
delete tree.nodeIndexesToIDs[parentIndex];
tree.IDsToNodeIndexes[parentID] = newIndex;
tree.nodeIndexesToIDs[newIndex] = parentID;
}
} else { // Some vacant spot.
// Pop the stack and append the value.
treeIndex = tree.stack[tree.stack.length - 1];
tree.stack.length--;
tree.nodes[treeIndex] = _value;
}
// Add label.
tree.IDsToNodeIndexes[_ID] = treeIndex;
tree.nodeIndexesToIDs[treeIndex] = _ID;
updateParents(self, _key, treeIndex, true, _value);
}
} else { // Existing node.
if (_value == 0) { // Zero value.
// Remove.
// Remember value and set to 0.
uint value = tree.nodes[treeIndex];
tree.nodes[treeIndex] = 0;
// Push to stack.
tree.stack.push(treeIndex);
// Clear label.
delete tree.IDsToNodeIndexes[_ID];
delete tree.nodeIndexesToIDs[treeIndex];
updateParents(self, _key, treeIndex, false, value);
} else if (_value != tree.nodes[treeIndex]) { // New, non zero value.
// Set.
bool plusOrMinus = tree.nodes[treeIndex] <= _value;
uint plusOrMinusValue = plusOrMinus ? _value - tree.nodes[treeIndex] : tree.nodes[treeIndex] - _value;
tree.nodes[treeIndex] = _value;
updateParents(self, _key, treeIndex, plusOrMinus, plusOrMinusValue);
}
}
}
/* internal Views */
/**
* @dev Query the leaves of a tree. Note that if `startIndex == 0`, the tree is empty and the root node will be returned.
* @param _key The key of the tree to get the leaves from.
* @param _cursor The pagination cursor.
* @param _count The number of items to return.
* @return The index at which leaves start, the values of the returned leaves, and whether there are more for pagination.
* `O(n)` where
* `n` is the maximum number of nodes ever appended.
*/
function queryLeafs(
SortitionSumTrees storage self,
bytes32 _key,
uint _cursor,
uint _count
) internal view returns(uint startIndex, uint[] memory values, bool hasMore) {
SortitionSumTree storage tree = self.sortitionSumTrees[_key];
// Find the start index.
for (uint i = 0; i < tree.nodes.length; i++) {
if ((tree.K * i) + 1 >= tree.nodes.length) {
startIndex = i;
break;
}
}
// Get the values.
uint loopStartIndex = startIndex + _cursor;
values = new uint[](loopStartIndex + _count > tree.nodes.length ? tree.nodes.length - loopStartIndex : _count);
uint valuesIndex = 0;
for (uint j = loopStartIndex; j < tree.nodes.length; j++) {
if (valuesIndex < _count) {
values[valuesIndex] = tree.nodes[j];
valuesIndex++;
} else {
hasMore = true;
break;
}
}
}
/**
* @dev Draw an ID from a tree using a number. Note that this function reverts if the sum of all values in the tree is 0.
* @param _key The key of the tree.
* @param _drawnNumber The drawn number.
* @return The drawn ID.
* `O(k * log_k(n))` where
* `k` is the maximum number of childs per node in the tree,
* and `n` is the maximum number of nodes ever appended.
*/
function draw(SortitionSumTrees storage self, bytes32 _key, uint _drawnNumber) internal view returns(bytes32 ID) {
SortitionSumTree storage tree = self.sortitionSumTrees[_key];
uint treeIndex = 0;
uint currentDrawnNumber = _drawnNumber % tree.nodes[0];
while ((tree.K * treeIndex) + 1 < tree.nodes.length) // While it still has children.
for (uint i = 1; i <= tree.K; i++) { // Loop over children.
uint nodeIndex = (tree.K * treeIndex) + i;
uint nodeValue = tree.nodes[nodeIndex];
if (currentDrawnNumber >= nodeValue) currentDrawnNumber -= nodeValue; // Go to the next child.
else { // Pick this child.
treeIndex = nodeIndex;
break;
}
}
ID = tree.nodeIndexesToIDs[treeIndex];
}
/** @dev Gets a specified ID's associated value.
* @param _key The key of the tree.
* @param _ID The ID of the value.
* @return The associated value.
*/
function stakeOf(SortitionSumTrees storage self, bytes32 _key, bytes32 _ID) internal view returns(uint value) {
SortitionSumTree storage tree = self.sortitionSumTrees[_key];
uint treeIndex = tree.IDsToNodeIndexes[_ID];
if (treeIndex == 0) value = 0;
else value = tree.nodes[treeIndex];
}
function total(SortitionSumTrees storage self, bytes32 _key) internal view returns (uint) {
SortitionSumTree storage tree = self.sortitionSumTrees[_key];
if (tree.nodes.length == 0) {
return 0;
} else {
return tree.nodes[0];
}
}
/* Private */
/**
* @dev Update all the parents of a node.
* @param _key The key of the tree to update.
* @param _treeIndex The index of the node to start from.
* @param _plusOrMinus Wether to add (true) or substract (false).
* @param _value The value to add or substract.
* `O(log_k(n))` where
* `k` is the maximum number of childs per node in the tree,
* and `n` is the maximum number of nodes ever appended.
*/
function updateParents(SortitionSumTrees storage self, bytes32 _key, uint _treeIndex, bool _plusOrMinus, uint _value) private {
SortitionSumTree storage tree = self.sortitionSumTrees[_key];
uint parentIndex = _treeIndex;
while (parentIndex != 0) {
parentIndex = (parentIndex - 1) / tree.K;
tree.nodes[parentIndex] = _plusOrMinus ? tree.nodes[parentIndex] + _value : tree.nodes[parentIndex] - _value;
}
}
}
/**
* @author Brendan Asselstine
* @notice Tracks committed and open balances for addresses. Affords selection of an address by indexing all committed balances.
*
* Balances are tracked in Draws. There is always one open Draw. Deposits are always added to the open Draw.
* When a new draw is opened, the previous opened draw is committed.
*
* The committed balance for an address is the total of their balances for committed Draws.
* An address's open balance is their balance in the open Draw.
*/
library DrawManager {
using SortitionSumTreeFactory for SortitionSumTreeFactory.SortitionSumTrees;
using SafeMath for uint256;
/**
* The ID to use for the selection tree.
*/
bytes32 public constant TREE_OF_DRAWS = "TreeOfDraws";
uint8 public constant MAX_BRANCHES_PER_NODE = 10;
/**
* Stores information for all draws.
*/
struct State {
/**
* Each Draw stores it's address balances in a sortitionSumTree. Draw trees are indexed using the Draw index.
* There is one root sortitionSumTree that stores all of the draw totals. The root tree is indexed using the constant TREE_OF_DRAWS.
*/
SortitionSumTreeFactory.SortitionSumTrees sortitionSumTrees;
/**
* Stores the consolidated draw index that an address deposited to.
*/
mapping(address => uint256) consolidatedDrawIndices;
/**
* Stores the last Draw index that an address deposited to.
*/
mapping(address => uint256) latestDrawIndices;
/**
* Stores a mapping of Draw index => Draw total
*/
mapping(uint256 => uint256) __deprecated__drawTotals;
/**
* The current open Draw index
*/
uint256 openDrawIndex;
/**
* The total of committed balances
*/
uint256 __deprecated__committedSupply;
}
/**
* @notice Opens the next Draw and commits the previous open Draw (if any).
* @param self The drawState this library is attached to
* @return The index of the new open Draw
*/
function openNextDraw(State storage self) public returns (uint256) {
if (self.openDrawIndex == 0) {
// If there is no previous draw, we must initialize
self.sortitionSumTrees.createTree(TREE_OF_DRAWS, MAX_BRANCHES_PER_NODE);
} else {
// else add current draw to sortition sum trees
bytes32 drawId = bytes32(self.openDrawIndex);
uint256 drawTotal = openSupply(self);
self.sortitionSumTrees.set(TREE_OF_DRAWS, drawTotal, drawId);
}
// now create a new draw
uint256 drawIndex = self.openDrawIndex.add(1);
self.sortitionSumTrees.createTree(bytes32(drawIndex), MAX_BRANCHES_PER_NODE);
self.openDrawIndex = drawIndex;
return drawIndex;
}
/**
* @notice Deposits the given amount into the current open draw by the given user.
* @param self The DrawManager state
* @param _addr The address to deposit for
* @param _amount The amount to deposit
*/
function deposit(State storage self, address _addr, uint256 _amount) public requireOpenDraw(self) onlyNonZero(_addr) {
bytes32 userId = bytes32(uint256(_addr));
uint256 openDrawIndex = self.openDrawIndex;
// update the current draw
uint256 currentAmount = self.sortitionSumTrees.stakeOf(bytes32(openDrawIndex), userId);
currentAmount = currentAmount.add(_amount);
drawSet(self, openDrawIndex, currentAmount, _addr);
uint256 consolidatedDrawIndex = self.consolidatedDrawIndices[_addr];
uint256 latestDrawIndex = self.latestDrawIndices[_addr];
// if this is the user's first draw, set it
if (consolidatedDrawIndex == 0) {
self.consolidatedDrawIndices[_addr] = openDrawIndex;
// otherwise, if the consolidated draw is not this draw
} else if (consolidatedDrawIndex != openDrawIndex) {
// if a second draw does not exist
if (latestDrawIndex == 0) {
// set the second draw to the current draw
self.latestDrawIndices[_addr] = openDrawIndex;
// otherwise if a second draw exists but is not the current one
} else if (latestDrawIndex != openDrawIndex) {
// merge it into the first draw, and update the second draw index to this one
uint256 consolidatedAmount = self.sortitionSumTrees.stakeOf(bytes32(consolidatedDrawIndex), userId);
uint256 latestAmount = self.sortitionSumTrees.stakeOf(bytes32(latestDrawIndex), userId);
drawSet(self, consolidatedDrawIndex, consolidatedAmount.add(latestAmount), _addr);
drawSet(self, latestDrawIndex, 0, _addr);
self.latestDrawIndices[_addr] = openDrawIndex;
}
}
}
/**
* @notice Deposits into a user's committed balance, thereby bypassing the open draw.
* @param self The DrawManager state
* @param _addr The address of the user for whom to deposit
* @param _amount The amount to deposit
*/
function depositCommitted(State storage self, address _addr, uint256 _amount) public requireCommittedDraw(self) onlyNonZero(_addr) {
bytes32 userId = bytes32(uint256(_addr));
uint256 consolidatedDrawIndex = self.consolidatedDrawIndices[_addr];
// if they have a committed balance
if (consolidatedDrawIndex != 0 && consolidatedDrawIndex != self.openDrawIndex) {
uint256 consolidatedAmount = self.sortitionSumTrees.stakeOf(bytes32(consolidatedDrawIndex), userId);
drawSet(self, consolidatedDrawIndex, consolidatedAmount.add(_amount), _addr);
} else { // they must not have any committed balance
self.latestDrawIndices[_addr] = consolidatedDrawIndex;
self.consolidatedDrawIndices[_addr] = self.openDrawIndex.sub(1);
drawSet(self, self.consolidatedDrawIndices[_addr], _amount, _addr);
}
}
/**
* @notice Withdraws a user's committed and open draws.
* @param self The DrawManager state
* @param _addr The address whose balance to withdraw
*/
function withdraw(State storage self, address _addr) public requireOpenDraw(self) onlyNonZero(_addr) {
uint256 consolidatedDrawIndex = self.consolidatedDrawIndices[_addr];
uint256 latestDrawIndex = self.latestDrawIndices[_addr];
if (consolidatedDrawIndex != 0) {
drawSet(self, consolidatedDrawIndex, 0, _addr);
delete self.consolidatedDrawIndices[_addr];
}
if (latestDrawIndex != 0) {
drawSet(self, latestDrawIndex, 0, _addr);
delete self.latestDrawIndices[_addr];
}
}
/**
* @notice Withdraw's from a user's open balance
* @param self The DrawManager state
* @param _addr The user to withdrawn from
* @param _amount The amount to withdraw
*/
function withdrawOpen(State storage self, address _addr, uint256 _amount) public requireOpenDraw(self) onlyNonZero(_addr) {
bytes32 userId = bytes32(uint256(_addr));
uint256 openTotal = self.sortitionSumTrees.stakeOf(bytes32(self.openDrawIndex), userId);
require(_amount <= openTotal, "DrawMan/exceeds-open");
uint256 remaining = openTotal.sub(_amount);
drawSet(self, self.openDrawIndex, remaining, _addr);
}
/**
* @notice Withdraw's from a user's committed balance. Fails if the user attempts to take more than available.
* @param self The DrawManager state
* @param _addr The user to withdraw from
* @param _amount The amount to withdraw.
*/
function withdrawCommitted(State storage self, address _addr, uint256 _amount) public requireCommittedDraw(self) onlyNonZero(_addr) {
bytes32 userId = bytes32(uint256(_addr));
uint256 consolidatedDrawIndex = self.consolidatedDrawIndices[_addr];
uint256 latestDrawIndex = self.latestDrawIndices[_addr];
uint256 consolidatedAmount = 0;
uint256 latestAmount = 0;
uint256 total = 0;
if (latestDrawIndex != 0 && latestDrawIndex != self.openDrawIndex) {
latestAmount = self.sortitionSumTrees.stakeOf(bytes32(latestDrawIndex), userId);
total = total.add(latestAmount);
}
if (consolidatedDrawIndex != 0 && consolidatedDrawIndex != self.openDrawIndex) {
consolidatedAmount = self.sortitionSumTrees.stakeOf(bytes32(consolidatedDrawIndex), userId);
total = total.add(consolidatedAmount);
}
// If the total is greater than zero, then consolidated *must* have the committed balance
// However, if the total is zero then the consolidated balance may be the open balance
if (total == 0) {
return;
}
require(_amount <= total, "Pool/exceed");
uint256 remaining = total.sub(_amount);
// if there was a second amount that needs to be updated
if (remaining > consolidatedAmount) {
uint256 secondRemaining = remaining.sub(consolidatedAmount);
drawSet(self, latestDrawIndex, secondRemaining, _addr);
} else if (latestAmount > 0) { // else delete the second amount if it exists
delete self.latestDrawIndices[_addr];
drawSet(self, latestDrawIndex, 0, _addr);
}
// if the consolidated amount needs to be destroyed
if (remaining == 0) {
delete self.consolidatedDrawIndices[_addr];
drawSet(self, consolidatedDrawIndex, 0, _addr);
} else if (remaining < consolidatedAmount) {
drawSet(self, consolidatedDrawIndex, remaining, _addr);
}
}
/**
* @notice Returns the total balance for an address, including committed balances and the open balance.
*/
function balanceOf(State storage drawState, address _addr) public view returns (uint256) {
return committedBalanceOf(drawState, _addr).add(openBalanceOf(drawState, _addr));
}
/**
* @notice Returns the total committed balance for an address.
* @param self The DrawManager state
* @param _addr The address whose committed balance should be returned
* @return The total committed balance
*/
function committedBalanceOf(State storage self, address _addr) public view returns (uint256) {
uint256 balance = 0;
uint256 consolidatedDrawIndex = self.consolidatedDrawIndices[_addr];
uint256 latestDrawIndex = self.latestDrawIndices[_addr];
if (consolidatedDrawIndex != 0 && consolidatedDrawIndex != self.openDrawIndex) {
balance = self.sortitionSumTrees.stakeOf(bytes32(consolidatedDrawIndex), bytes32(uint256(_addr)));
}
if (latestDrawIndex != 0 && latestDrawIndex != self.openDrawIndex) {
balance = balance.add(self.sortitionSumTrees.stakeOf(bytes32(latestDrawIndex), bytes32(uint256(_addr))));
}
return balance;
}
/**
* @notice Returns the open balance for an address
* @param self The DrawManager state
* @param _addr The address whose open balance should be returned
* @return The open balance
*/
function openBalanceOf(State storage self, address _addr) public view returns (uint256) {
if (self.openDrawIndex == 0) {
return 0;
} else {
return self.sortitionSumTrees.stakeOf(bytes32(self.openDrawIndex), bytes32(uint256(_addr)));
}
}
/**
* @notice Returns the open Draw balance for the DrawManager
* @param self The DrawManager state
* @return The open draw total balance
*/
function openSupply(State storage self) public view returns (uint256) {
return self.sortitionSumTrees.total(bytes32(self.openDrawIndex));
}
/**
* @notice Returns the committed balance for the DrawManager
* @param self The DrawManager state
* @return The total committed balance
*/
function committedSupply(State storage self) public view returns (uint256) {
return self.sortitionSumTrees.total(TREE_OF_DRAWS);
}
/**
* @notice Updates the Draw balance for an address.
* @param self The DrawManager state
* @param _drawIndex The Draw index
* @param _amount The new balance
* @param _addr The address whose balance should be updated
*/
function drawSet(State storage self, uint256 _drawIndex, uint256 _amount, address _addr) internal {
bytes32 drawId = bytes32(_drawIndex);
bytes32 userId = bytes32(uint256(_addr));
uint256 oldAmount = self.sortitionSumTrees.stakeOf(drawId, userId);
if (oldAmount != _amount) {
// If the amount has changed
// Update the Draw's balance for that address
self.sortitionSumTrees.set(drawId, _amount, userId);
// if the draw is committed
if (_drawIndex != self.openDrawIndex) {
// Get the new draw total
uint256 newDrawTotal = self.sortitionSumTrees.total(drawId);
// update the draw in the committed tree
self.sortitionSumTrees.set(TREE_OF_DRAWS, newDrawTotal, drawId);
}
}
}
/**
* @notice Selects an address by indexing into the committed tokens using the passed token.
* If there is no committed supply, the zero address is returned.
* @param self The DrawManager state
* @param _token The token index to select
* @return The selected address
*/
function draw(State storage self, uint256 _token) public view returns (address) {
// If there is no one to select, just return the zero address
if (committedSupply(self) == 0) {
return address(0);
}
require(_token < committedSupply(self), "Pool/ineligible");
bytes32 drawIndex = self.sortitionSumTrees.draw(TREE_OF_DRAWS, _token);
uint256 drawSupply = self.sortitionSumTrees.total(drawIndex);
uint256 drawToken = _token % drawSupply;
return address(uint256(self.sortitionSumTrees.draw(drawIndex, drawToken)));
}
/**
* @notice Selects an address using the entropy as an index into the committed tokens
* The entropy is passed into the UniformRandomNumber library to remove modulo bias.
* @param self The DrawManager state
* @param _entropy The random entropy to use
* @return The selected address
*/
function drawWithEntropy(State storage self, bytes32 _entropy) public view returns (address) {
uint256 bound = committedSupply(self);
address selected;
if (bound == 0) {
selected = address(0);
} else {
selected = draw(self, UniformRandomNumber.uniform(uint256(_entropy), bound));
}
return selected;
}
modifier requireOpenDraw(State storage self) {
require(self.openDrawIndex > 0, "Pool/no-open");
_;
}
modifier requireCommittedDraw(State storage self) {
require(self.openDrawIndex > 1, "Pool/no-commit");
_;
}
modifier onlyNonZero(address _addr) {
require(_addr != address(0), "Pool/not-zero");
_;
}
}
/**
* @title FixidityLib
* @author Gadi Guy, Alberto Cuesta Canada
* @notice This library provides fixed point arithmetic with protection against
* overflow.
* All operations are done with int256 and the operands must have been created
* with any of the newFrom* functions, which shift the comma digits() to the
* right and check for limits.
* When using this library be sure of using maxNewFixed() as the upper limit for
* creation of fixed point numbers. Use maxFixedMul(), maxFixedDiv() and
* maxFixedAdd() if you want to be certain that those operations don't
* overflow.
*/
library FixidityLib {
/**
* @notice Number of positions that the comma is shifted to the right.
*/
function digits() public pure returns(uint8) {
return 24;
}
/**
* @notice This is 1 in the fixed point units used in this library.
* @dev Test fixed1() equals 10^digits()
* Hardcoded to 24 digits.
*/
function fixed1() public pure returns(int256) {
return 1000000000000000000000000;
}
/**
* @notice The amount of decimals lost on each multiplication operand.
* @dev Test mulPrecision() equals sqrt(fixed1)
* Hardcoded to 24 digits.
*/
function mulPrecision() public pure returns(int256) {
return 1000000000000;
}
/**
* @notice Maximum value that can be represented in an int256
* @dev Test maxInt256() equals 2^255 -1
*/
function maxInt256() public pure returns(int256) {
return 57896044618658097711785492504343953926634992332820282019728792003956564819967;
}
/**
* @notice Minimum value that can be represented in an int256
* @dev Test minInt256 equals (2^255) * (-1)
*/
function minInt256() public pure returns(int256) {
return -57896044618658097711785492504343953926634992332820282019728792003956564819968;
}
/**
* @notice Maximum value that can be converted to fixed point. Optimize for
* @dev deployment.
* Test maxNewFixed() equals maxInt256() / fixed1()
* Hardcoded to 24 digits.
*/
function maxNewFixed() public pure returns(int256) {
return 57896044618658097711785492504343953926634992332820282;
}
/**
* @notice Minimum value that can be converted to fixed point. Optimize for
* deployment.
* @dev Test minNewFixed() equals -(maxInt256()) / fixed1()
* Hardcoded to 24 digits.
*/
function minNewFixed() public pure returns(int256) {
return -57896044618658097711785492504343953926634992332820282;
}
/**
* @notice Maximum value that can be safely used as an addition operator.
* @dev Test maxFixedAdd() equals maxInt256()-1 / 2
* Test add(maxFixedAdd(),maxFixedAdd()) equals maxFixedAdd() + maxFixedAdd()
* Test add(maxFixedAdd()+1,maxFixedAdd()) throws
* Test add(-maxFixedAdd(),-maxFixedAdd()) equals -maxFixedAdd() - maxFixedAdd()
* Test add(-maxFixedAdd(),-maxFixedAdd()-1) throws
*/
function maxFixedAdd() public pure returns(int256) {
return 28948022309329048855892746252171976963317496166410141009864396001978282409983;
}
/**
* @notice Maximum negative value that can be safely in a subtraction.
* @dev Test maxFixedSub() equals minInt256() / 2
*/
function maxFixedSub() public pure returns(int256) {
return -28948022309329048855892746252171976963317496166410141009864396001978282409984;
}
/**
* @notice Maximum value that can be safely used as a multiplication operator.
* @dev Calculated as sqrt(maxInt256()*fixed1()).
* Be careful with your sqrt() implementation. I couldn't find a calculator
* that would give the exact square root of maxInt256*fixed1 so this number
* is below the real number by no more than 3*10**28. It is safe to use as
* a limit for your multiplications, although powers of two of numbers over
* this value might still work.
* Test multiply(maxFixedMul(),maxFixedMul()) equals maxFixedMul() * maxFixedMul()
* Test multiply(maxFixedMul(),maxFixedMul()+1) throws
* Test multiply(-maxFixedMul(),maxFixedMul()) equals -maxFixedMul() * maxFixedMul()
* Test multiply(-maxFixedMul(),maxFixedMul()+1) throws
* Hardcoded to 24 digits.
*/
function maxFixedMul() public pure returns(int256) {
return 240615969168004498257251713877715648331380787511296;
}
/**
* @notice Maximum value that can be safely used as a dividend.
* @dev divide(maxFixedDiv,newFixedFraction(1,fixed1())) = maxInt256().
* Test maxFixedDiv() equals maxInt256()/fixed1()
* Test divide(maxFixedDiv(),multiply(mulPrecision(),mulPrecision())) = maxFixedDiv()*(10^digits())
* Test divide(maxFixedDiv()+1,multiply(mulPrecision(),mulPrecision())) throws
* Hardcoded to 24 digits.
*/
function maxFixedDiv() public pure returns(int256) {
return 57896044618658097711785492504343953926634992332820282;
}
/**
* @notice Maximum value that can be safely used as a divisor.
* @dev Test maxFixedDivisor() equals fixed1()*fixed1() - Or 10**(digits()*2)
* Test divide(10**(digits()*2 + 1),10**(digits()*2)) = returns 10*fixed1()
* Test divide(10**(digits()*2 + 1),10**(digits()*2 + 1)) = throws
* Hardcoded to 24 digits.
*/
function maxFixedDivisor() public pure returns(int256) {
return 1000000000000000000000000000000000000000000000000;
}
/**
* @notice Converts an int256 to fixed point units, equivalent to multiplying
* by 10^digits().
* @dev Test newFixed(0) returns 0
* Test newFixed(1) returns fixed1()
* Test newFixed(maxNewFixed()) returns maxNewFixed() * fixed1()
* Test newFixed(maxNewFixed()+1) fails
*/
function newFixed(int256 x)
public
pure
returns (int256)
{
require(x <= maxNewFixed());
require(x >= minNewFixed());
return x * fixed1();
}
/**
* @notice Converts an int256 in the fixed point representation of this
* library to a non decimal. All decimal digits will be truncated.
*/
function fromFixed(int256 x)
public
pure
returns (int256)
{
return x / fixed1();
}
/**
* @notice Converts an int256 which is already in some fixed point
* representation to a different fixed precision representation.
* Both the origin and destination precisions must be 38 or less digits.
* Origin values with a precision higher than the destination precision
* will be truncated accordingly.
* @dev
* Test convertFixed(1,0,0) returns 1;
* Test convertFixed(1,1,1) returns 1;
* Test convertFixed(1,1,0) returns 0;
* Test convertFixed(1,0,1) returns 10;
* Test convertFixed(10,1,0) returns 1;
* Test convertFixed(10,0,1) returns 100;
* Test convertFixed(100,1,0) returns 10;
* Test convertFixed(100,0,1) returns 1000;
* Test convertFixed(1000,2,0) returns 10;
* Test convertFixed(1000,0,2) returns 100000;
* Test convertFixed(1000,2,1) returns 100;
* Test convertFixed(1000,1,2) returns 10000;
* Test convertFixed(maxInt256,1,0) returns maxInt256/10;
* Test convertFixed(maxInt256,0,1) throws
* Test convertFixed(maxInt256,38,0) returns maxInt256/(10**38);
* Test convertFixed(1,0,38) returns 10**38;
* Test convertFixed(maxInt256,39,0) throws
* Test convertFixed(1,0,39) throws
*/
function convertFixed(int256 x, uint8 _originDigits, uint8 _destinationDigits)
public
pure
returns (int256)
{
require(_originDigits <= 38 && _destinationDigits <= 38);
uint8 decimalDifference;
if ( _originDigits > _destinationDigits ){
decimalDifference = _originDigits - _destinationDigits;
return x/(uint128(10)**uint128(decimalDifference));
}
else if ( _originDigits < _destinationDigits ){
decimalDifference = _destinationDigits - _originDigits;
// Cast uint8 -> uint128 is safe
// Exponentiation is safe:
// _originDigits and _destinationDigits limited to 38 or less
// decimalDifference = abs(_destinationDigits - _originDigits)
// decimalDifference < 38
// 10**38 < 2**128-1
require(x <= maxInt256()/uint128(10)**uint128(decimalDifference));
require(x >= minInt256()/uint128(10)**uint128(decimalDifference));
return x*(uint128(10)**uint128(decimalDifference));
}
// _originDigits == digits())
return x;
}
/**
* @notice Converts an int256 which is already in some fixed point
* representation to that of this library. The _originDigits parameter is the
* precision of x. Values with a precision higher than FixidityLib.digits()
* will be truncated accordingly.
*/
function newFixed(int256 x, uint8 _originDigits)
public
pure
returns (int256)
{
return convertFixed(x, _originDigits, digits());
}
/**
* @notice Converts an int256 in the fixed point representation of this
* library to a different representation. The _destinationDigits parameter is the
* precision of the output x. Values with a precision below than
* FixidityLib.digits() will be truncated accordingly.
*/
function fromFixed(int256 x, uint8 _destinationDigits)
public
pure
returns (int256)
{
return convertFixed(x, digits(), _destinationDigits);
}
/**
* @notice Converts two int256 representing a fraction to fixed point units,
* equivalent to multiplying dividend and divisor by 10^digits().
* @dev
* Test newFixedFraction(maxFixedDiv()+1,1) fails
* Test newFixedFraction(1,maxFixedDiv()+1) fails
* Test newFixedFraction(1,0) fails
* Test newFixedFraction(0,1) returns 0
* Test newFixedFraction(1,1) returns fixed1()
* Test newFixedFraction(maxFixedDiv(),1) returns maxFixedDiv()*fixed1()
* Test newFixedFraction(1,fixed1()) returns 1
* Test newFixedFraction(1,fixed1()-1) returns 0
*/
function newFixedFraction(
int256 numerator,
int256 denominator
)
public
pure
returns (int256)
{
require(numerator <= maxNewFixed());
require(denominator <= maxNewFixed());
require(denominator != 0);
int256 convertedNumerator = newFixed(numerator);
int256 convertedDenominator = newFixed(denominator);
return divide(convertedNumerator, convertedDenominator);
}
/**
* @notice Returns the integer part of a fixed point number.
* @dev
* Test integer(0) returns 0
* Test integer(fixed1()) returns fixed1()
* Test integer(newFixed(maxNewFixed())) returns maxNewFixed()*fixed1()
* Test integer(-fixed1()) returns -fixed1()
* Test integer(newFixed(-maxNewFixed())) returns -maxNewFixed()*fixed1()
*/
function integer(int256 x) public pure returns (int256) {
return (x / fixed1()) * fixed1(); // Can't overflow
}
/**
* @notice Returns the fractional part of a fixed point number.
* In the case of a negative number the fractional is also negative.
* @dev
* Test fractional(0) returns 0
* Test fractional(fixed1()) returns 0
* Test fractional(fixed1()-1) returns 10^24-1
* Test fractional(-fixed1()) returns 0
* Test fractional(-fixed1()+1) returns -10^24-1
*/
function fractional(int256 x) public pure returns (int256) {
return x - (x / fixed1()) * fixed1(); // Can't overflow
}
/**
* @notice Converts to positive if negative.
* Due to int256 having one more negative number than positive numbers
* abs(minInt256) reverts.
* @dev
* Test abs(0) returns 0
* Test abs(fixed1()) returns -fixed1()
* Test abs(-fixed1()) returns fixed1()
* Test abs(newFixed(maxNewFixed())) returns maxNewFixed()*fixed1()
* Test abs(newFixed(minNewFixed())) returns -minNewFixed()*fixed1()
*/
function abs(int256 x) public pure returns (int256) {
if (x >= 0) {
return x;
} else {
int256 result = -x;
assert (result > 0);
return result;
}
}
/**
* @notice x+y. If any operator is higher than maxFixedAdd() it
* might overflow.
* In solidity maxInt256 + 1 = minInt256 and viceversa.
* @dev
* Test add(maxFixedAdd(),maxFixedAdd()) returns maxInt256()-1
* Test add(maxFixedAdd()+1,maxFixedAdd()+1) fails
* Test add(-maxFixedSub(),-maxFixedSub()) returns minInt256()
* Test add(-maxFixedSub()-1,-maxFixedSub()-1) fails
* Test add(maxInt256(),maxInt256()) fails
* Test add(minInt256(),minInt256()) fails
*/
function add(int256 x, int256 y) public pure returns (int256) {
int256 z = x + y;
if (x > 0 && y > 0) assert(z > x && z > y);
if (x < 0 && y < 0) assert(z < x && z < y);
return z;
}
/**
* @notice x-y. You can use add(x,-y) instead.
* @dev Tests covered by add(x,y)
*/
function subtract(int256 x, int256 y) public pure returns (int256) {
return add(x,-y);
}
/**
* @notice x*y. If any of the operators is higher than maxFixedMul() it
* might overflow.
* @dev
* Test multiply(0,0) returns 0
* Test multiply(maxFixedMul(),0) returns 0
* Test multiply(0,maxFixedMul()) returns 0
* Test multiply(maxFixedMul(),fixed1()) returns maxFixedMul()
* Test multiply(fixed1(),maxFixedMul()) returns maxFixedMul()
* Test all combinations of (2,-2), (2, 2.5), (2, -2.5) and (0.5, -0.5)
* Test multiply(fixed1()/mulPrecision(),fixed1()*mulPrecision())
* Test multiply(maxFixedMul()-1,maxFixedMul()) equals multiply(maxFixedMul(),maxFixedMul()-1)
* Test multiply(maxFixedMul(),maxFixedMul()) returns maxInt256() // Probably not to the last digits
* Test multiply(maxFixedMul()+1,maxFixedMul()) fails
* Test multiply(maxFixedMul(),maxFixedMul()+1) fails
*/
function multiply(int256 x, int256 y) public pure returns (int256) {
if (x == 0 || y == 0) return 0;
if (y == fixed1()) return x;
if (x == fixed1()) return y;
// Separate into integer and fractional parts
// x = x1 + x2, y = y1 + y2
int256 x1 = integer(x) / fixed1();
int256 x2 = fractional(x);
int256 y1 = integer(y) / fixed1();
int256 y2 = fractional(y);
// (x1 + x2) * (y1 + y2) = (x1 * y1) + (x1 * y2) + (x2 * y1) + (x2 * y2)
int256 x1y1 = x1 * y1;
if (x1 != 0) assert(x1y1 / x1 == y1); // Overflow x1y1
// x1y1 needs to be multiplied back by fixed1
// solium-disable-next-line mixedcase
int256 fixed_x1y1 = x1y1 * fixed1();
if (x1y1 != 0) assert(fixed_x1y1 / x1y1 == fixed1()); // Overflow x1y1 * fixed1
x1y1 = fixed_x1y1;
int256 x2y1 = x2 * y1;
if (x2 != 0) assert(x2y1 / x2 == y1); // Overflow x2y1
int256 x1y2 = x1 * y2;
if (x1 != 0) assert(x1y2 / x1 == y2); // Overflow x1y2
x2 = x2 / mulPrecision();
y2 = y2 / mulPrecision();
int256 x2y2 = x2 * y2;
if (x2 != 0) assert(x2y2 / x2 == y2); // Overflow x2y2
// result = fixed1() * x1 * y1 + x1 * y2 + x2 * y1 + x2 * y2 / fixed1();
int256 result = x1y1;
result = add(result, x2y1); // Add checks for overflow
result = add(result, x1y2); // Add checks for overflow
result = add(result, x2y2); // Add checks for overflow
return result;
}
/**
* @notice 1/x
* @dev
* Test reciprocal(0) fails
* Test reciprocal(fixed1()) returns fixed1()
* Test reciprocal(fixed1()*fixed1()) returns 1 // Testing how the fractional is truncated
* Test reciprocal(2*fixed1()*fixed1()) returns 0 // Testing how the fractional is truncated
*/
function reciprocal(int256 x) public pure returns (int256) {
require(x != 0);
return (fixed1()*fixed1()) / x; // Can't overflow
}
/**
* @notice x/y. If the dividend is higher than maxFixedDiv() it
* might overflow. You can use multiply(x,reciprocal(y)) instead.
* There is a loss of precision on division for the lower mulPrecision() decimals.
* @dev
* Test divide(fixed1(),0) fails
* Test divide(maxFixedDiv(),1) = maxFixedDiv()*(10^digits())
* Test divide(maxFixedDiv()+1,1) throws
* Test divide(maxFixedDiv(),maxFixedDiv()) returns fixed1()
*/
function divide(int256 x, int256 y) public pure returns (int256) {
if (y == fixed1()) return x;
require(y != 0);
require(y <= maxFixedDivisor());
return multiply(x, reciprocal(y));
}
}
/**
* @title Blocklock
* @author Brendan Asselstine
* @notice A time lock with a cooldown period. When locked, the contract will remain locked until it is unlocked manually
* or the lock duration expires. After the contract is unlocked, it cannot be locked until the cooldown duration expires.
*/
library Blocklock {
using SafeMath for uint256;
struct State {
uint256 lockedAt;
uint256 unlockedAt;
uint256 lockDuration;
uint256 cooldownDuration;
}
/**
* @notice Sets the duration of the lock. This how long the lock lasts before it expires and automatically unlocks.
* @param self The Blocklock state
* @param lockDuration The duration, in blocks, that the lock should last.
*/
function setLockDuration(State storage self, uint256 lockDuration) public {
require(lockDuration > 0, "Blocklock/lock-min");
self.lockDuration = lockDuration;
}
/**
* @notice Sets the cooldown duration in blocks. This is the number of blocks that must pass before being able to
* lock again. The cooldown duration begins when the lock duration expires, or when it is unlocked manually.
* @param self The Blocklock state
* @param cooldownDuration The duration of the cooldown, in blocks.
*/
function setCooldownDuration(State storage self, uint256 cooldownDuration) public {
require(cooldownDuration > 0, "Blocklock/cool-min");
self.cooldownDuration = cooldownDuration;
}
/**
* @notice Returns whether the state is locked at the given block number.
* @param self The Blocklock state
* @param blockNumber The current block number.
*/
function isLocked(State storage self, uint256 blockNumber) public view returns (bool) {
uint256 endAt = lockEndAt(self);
return (
self.lockedAt != 0 &&
blockNumber >= self.lockedAt &&
blockNumber < endAt
);
}
/**
* @notice Locks the state at the given block number.
* @param self The Blocklock state
* @param blockNumber The block number to use as the lock start time
*/
function lock(State storage self, uint256 blockNumber) public {
require(canLock(self, blockNumber), "Blocklock/no-lock");
self.lockedAt = blockNumber;
}
/**
* @notice Manually unlocks the lock.
* @param self The Blocklock state
* @param blockNumber The block number at which the lock is being unlocked.
*/
function unlock(State storage self, uint256 blockNumber) public {
self.unlockedAt = blockNumber;
}
/**
* @notice Returns whether the Blocklock can be locked at the given block number
* @param self The Blocklock state
* @param blockNumber The block number to check against
* @return True if we can lock at the given block number, false otherwise.
*/
function canLock(State storage self, uint256 blockNumber) public view returns (bool) {
uint256 endAt = lockEndAt(self);
return (
self.lockedAt == 0 ||
blockNumber >= endAt.add(self.cooldownDuration)
);
}
function cooldownEndAt(State storage self) internal view returns (uint256) {
return lockEndAt(self).add(self.cooldownDuration);
}
function lockEndAt(State storage self) internal view returns (uint256) {
uint256 endAt = self.lockedAt.add(self.lockDuration);
// if we unlocked early
if (self.unlockedAt >= self.lockedAt && self.unlockedAt < endAt) {
endAt = self.unlockedAt;
}
return endAt;
}
}
/**
Copyright 2020 PoolTogether Inc.
This file is part of PoolTogether.
PoolTogether 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 under version 3 of the License.
PoolTogether 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 PoolTogether. If not, see <https://www.gnu.org/licenses/>.
*/
/**
* @dev Interface of the ERC777Token standard as defined in the EIP.
*
* This contract uses the
* https://eips.ethereum.org/EIPS/eip-1820[ERC1820 registry standard] to let
* token holders and recipients react to token movements by using setting implementers
* for the associated interfaces in said registry. See {IERC1820Registry} and
* {ERC1820Implementer}.
*/
interface IERC777 {
/**
* @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 smallest part of the token that is not divisible. This
* means all token operations (creation, movement and destruction) must have
* amounts that are a multiple of this number.
*
* For most token contracts, this value will equal 1.
*/
function granularity() external view returns (uint256);
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by an account (`owner`).
*/
function balanceOf(address owner) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* If send or receive hooks are registered for the caller and `recipient`,
* the corresponding functions will be called with `data` and empty
* `operatorData`. See {IERC777Sender} and {IERC777Recipient}.
*
* Emits a {Sent} event.
*
* Requirements
*
* - the caller must have at least `amount` tokens.
* - `recipient` cannot be the zero address.
* - if `recipient` is a contract, it must implement the {IERC777Recipient}
* interface.
*/
function send(address recipient, uint256 amount, bytes calldata data) external;
/**
* @dev Destroys `amount` tokens from the caller's account, reducing the
* total supply.
*
* If a send hook is registered for the caller, the corresponding function
* will be called with `data` and empty `operatorData`. See {IERC777Sender}.
*
* Emits a {Burned} event.
*
* Requirements
*
* - the caller must have at least `amount` tokens.
*/
function burn(uint256 amount, bytes calldata data) external;
/**
* @dev Returns true if an account is an operator of `tokenHolder`.
* Operators can send and burn tokens on behalf of their owners. All
* accounts are their own operator.
*
* See {operatorSend} and {operatorBurn}.
*/
function isOperatorFor(address operator, address tokenHolder) external view returns (bool);
/**
* @dev Make an account an operator of the caller.
*
* See {isOperatorFor}.
*
* Emits an {AuthorizedOperator} event.
*
* Requirements
*
* - `operator` cannot be calling address.
*/
function authorizeOperator(address operator) external;
/**
* @dev Make an account an operator of the caller.
*
* See {isOperatorFor} and {defaultOperators}.
*
* Emits a {RevokedOperator} event.
*
* Requirements
*
* - `operator` cannot be calling address.
*/
function revokeOperator(address operator) external;
/**
* @dev Returns the list of default operators. These accounts are operators
* for all token holders, even if {authorizeOperator} was never called on
* them.
*
* This list is immutable, but individual holders may revoke these via
* {revokeOperator}, in which case {isOperatorFor} will return false.
*/
function defaultOperators() external view returns (address[] memory);
/**
* @dev Moves `amount` tokens from `sender` to `recipient`. The caller must
* be an operator of `sender`.
*
* If send or receive hooks are registered for `sender` and `recipient`,
* the corresponding functions will be called with `data` and
* `operatorData`. See {IERC777Sender} and {IERC777Recipient}.
*
* Emits a {Sent} event.
*
* Requirements
*
* - `sender` cannot be the zero address.
* - `sender` must have at least `amount` tokens.
* - the caller must be an operator for `sender`.
* - `recipient` cannot be the zero address.
* - if `recipient` is a contract, it must implement the {IERC777Recipient}
* interface.
*/
function operatorSend(
address sender,
address recipient,
uint256 amount,
bytes calldata data,
bytes calldata operatorData
) external;
/**
* @dev Destoys `amount` tokens from `account`, reducing the total supply.
* The caller must be an operator of `account`.
*
* If a send hook is registered for `account`, the corresponding function
* will be called with `data` and `operatorData`. See {IERC777Sender}.
*
* Emits a {Burned} event.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
* - the caller must be an operator for `account`.
*/
function operatorBurn(
address account,
uint256 amount,
bytes calldata data,
bytes calldata operatorData
) external;
event Sent(
address indexed operator,
address indexed from,
address indexed to,
uint256 amount,
bytes data,
bytes operatorData
);
event Minted(address indexed operator, address indexed to, uint256 amount, bytes data, bytes operatorData);
event Burned(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData);
event AuthorizedOperator(address indexed operator, address indexed tokenHolder);
event RevokedOperator(address indexed operator, address indexed tokenHolder);
}
/**
* @dev Interface of the ERC777TokensSender standard as defined in the EIP.
*
* {IERC777} Token holders can be notified of operations performed on their
* tokens by having a contract implement this interface (contract holders can be
* their own implementer) and registering it on the
* https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry].
*
* See {IERC1820Registry} and {ERC1820Implementer}.
*/
interface IERC777Sender {
/**
* @dev Called by an {IERC777} token contract whenever a registered holder's
* (`from`) tokens are about to be moved or destroyed. The type of operation
* is conveyed by `to` being the zero address or not.
*
* This call occurs _before_ the token contract's state is updated, so
* {IERC777-balanceOf}, etc., can be used to query the pre-operation state.
*
* This function may revert to prevent the operation from being executed.
*/
function tokensToSend(
address operator,
address from,
address to,
uint256 amount,
bytes calldata userData,
bytes calldata operatorData
) external;
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* This test is non-exhaustive, and there may be false-negatives: during the
* execution of a contract's constructor, its address will be reported as
* not containing a contract.
*
* IMPORTANT: It is unsafe to assume that an address for which this
* function returns false is an externally-owned account (EOA) and not a
* contract.
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
/**
* @dev Implementation of the {IERC777} interface.
*
* Largely taken from the OpenZeppelin ERC777 contract.
*
* Support for ERC20 is included in this contract, as specified by the EIP: both
* the ERC777 and ERC20 interfaces can be safely used when interacting with it.
* Both {IERC777-Sent} and {IERC20-Transfer} events are emitted on token
* movements.
*
* Additionally, the {IERC777-granularity} value is hard-coded to `1`, meaning that there
* are no special restrictions in the amount of tokens that created, moved, or
* destroyed. This makes integration with ERC20 applications seamless.
*
* It is important to note that no Mint events are emitted. Tokens are minted in batches
* by a state change in a tree data structure, so emitting a Mint event for each user
* is not possible.
*
*/
contract PoolToken is Initializable, IERC20, IERC777 {
using SafeMath for uint256;
using Address for address;
/**
* Event emitted when a user or operator redeems tokens
*/
event Redeemed(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData);
IERC1820Registry constant internal ERC1820_REGISTRY = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24);
// We inline the result of the following hashes because Solidity doesn't resolve them at compile time.
// See https://github.com/ethereum/solidity/issues/4024.
// keccak256("ERC777TokensSender")
bytes32 constant internal TOKENS_SENDER_INTERFACE_HASH =
0x29ddb589b1fb5fc7cf394961c1adf5f8c6454761adf795e67fe149f658abe895;
// keccak256("ERC777TokensRecipient")
bytes32 constant internal TOKENS_RECIPIENT_INTERFACE_HASH =
0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b;
// keccak256("ERC777Token")
bytes32 constant internal TOKENS_INTERFACE_HASH =
0xac7fbab5f54a3ca8194167523c6753bfeb96a445279294b6125b68cce2177054;
// keccak256("ERC20Token")
bytes32 constant internal ERC20_TOKENS_INTERFACE_HASH =
0xaea199e31a596269b42cdafd93407f14436db6e4cad65417994c2eb37381e05a;
string internal _name;
string internal _symbol;
// This isn't ever read from - it's only used to respond to the defaultOperators query.
address[] internal _defaultOperatorsArray;
// Immutable, but accounts may revoke them (tracked in __revokedDefaultOperators).
mapping(address => bool) internal _defaultOperators;
// For each account, a mapping of its operators and revoked default operators.
mapping(address => mapping(address => bool)) internal _operators;
mapping(address => mapping(address => bool)) internal _revokedDefaultOperators;
// ERC20-allowances
mapping (address => mapping (address => uint256)) internal _allowances;
// The Pool that is bound to this token
BasePool internal _pool;
/**
* @notice Initializes the PoolToken.
* @param name The name of the token
* @param symbol The token symbol
* @param defaultOperators The default operators who are allowed to move tokens
*/
function init (
string memory name,
string memory symbol,
address[] memory defaultOperators,
BasePool pool
) public initializer {
require(bytes(name).length != 0, "PoolToken/name");
require(bytes(symbol).length != 0, "PoolToken/symbol");
require(address(pool) != address(0), "PoolToken/pool-zero");
_name = name;
_symbol = symbol;
_pool = pool;
_defaultOperatorsArray = defaultOperators;
for (uint256 i = 0; i < _defaultOperatorsArray.length; i++) {
_defaultOperators[_defaultOperatorsArray[i]] = true;
}
// register interfaces
ERC1820_REGISTRY.setInterfaceImplementer(address(this), TOKENS_INTERFACE_HASH, address(this));
ERC1820_REGISTRY.setInterfaceImplementer(address(this), ERC20_TOKENS_INTERFACE_HASH, address(this));
}
/**
* @notice Returns the address of the Pool contract
* @return The address of the pool contract
*/
function pool() public view returns (BasePool) {
return _pool;
}
/**
* @notice Calls the ERC777 transfer hook, and emits Redeemed and Transfer. Can only be called by the Pool contract.
* @param from The address from which to redeem tokens
* @param amount The amount of tokens to redeem
*/
function poolRedeem(address from, uint256 amount) external onlyPool {
_callTokensToSend(from, from, address(0), amount, '', '');
emit Redeemed(from, from, amount, '', '');
emit Transfer(from, address(0), amount);
}
/**
* @dev See {IERC777-name}.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev See {IERC777-symbol}.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev See {ERC20Detailed-decimals}.
*
* Always returns 18, as per the
* [ERC777 EIP](https://eips.ethereum.org/EIPS/eip-777#backward-compatibility).
*/
function decimals() public view returns (uint8) {
return 18;
}
/**
* @dev See {IERC777-granularity}.
*
* This implementation always returns `1`.
*/
function granularity() public view returns (uint256) {
return 1;
}
/**
* @dev See {IERC777-totalSupply}.
*/
function totalSupply() public view returns (uint256) {
return _pool.committedSupply();
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address _addr) external view returns (uint256) {
return _pool.committedBalanceOf(_addr);
}
/**
* @dev See {IERC777-send}.
*
* Also emits a {Transfer} event for ERC20 compatibility.
*/
function send(address recipient, uint256 amount, bytes calldata data) external {
_send(msg.sender, msg.sender, recipient, amount, data, "");
}
/**
* @dev See {IERC20-transfer}.
*
* Unlike `send`, `recipient` is _not_ required to implement the {IERC777Recipient}
* interface if it is a contract.
*
* Also emits a {Sent} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool) {
require(recipient != address(0), "PoolToken/transfer-zero");
address from = msg.sender;
_callTokensToSend(from, from, recipient, amount, "", "");
_move(from, from, recipient, amount, "", "");
_callTokensReceived(from, from, recipient, amount, "", "", false);
return true;
}
/**
* @dev Allows a user to withdraw their tokens as the underlying asset.
*
* Also emits a {Transfer} event for ERC20 compatibility.
*/
function redeem(uint256 amount, bytes calldata data) external {
_redeem(msg.sender, msg.sender, amount, data, "");
}
/**
* @dev See {IERC777-burn}. Not currently implemented.
*
* Also emits a {Transfer} event for ERC20 compatibility.
*/
function burn(uint256, bytes calldata) external {
revert("PoolToken/no-support");
}
/**
* @dev See {IERC777-isOperatorFor}.
*/
function isOperatorFor(
address operator,
address tokenHolder
) public view returns (bool) {
return operator == tokenHolder ||
(_defaultOperators[operator] && !_revokedDefaultOperators[tokenHolder][operator]) ||
_operators[tokenHolder][operator];
}
/**
* @dev See {IERC777-authorizeOperator}.
*/
function authorizeOperator(address operator) external {
require(msg.sender != operator, "PoolToken/auth-self");
if (_defaultOperators[operator]) {
delete _revokedDefaultOperators[msg.sender][operator];
} else {
_operators[msg.sender][operator] = true;
}
emit AuthorizedOperator(operator, msg.sender);
}
/**
* @dev See {IERC777-revokeOperator}.
*/
function revokeOperator(address operator) external {
require(operator != msg.sender, "PoolToken/revoke-self");
if (_defaultOperators[operator]) {
_revokedDefaultOperators[msg.sender][operator] = true;
} else {
delete _operators[msg.sender][operator];
}
emit RevokedOperator(operator, msg.sender);
}
/**
* @dev See {IERC777-defaultOperators}.
*/
function defaultOperators() public view returns (address[] memory) {
return _defaultOperatorsArray;
}
/**
* @dev See {IERC777-operatorSend}.
*
* Emits {Sent} and {Transfer} events.
*/
function operatorSend(
address sender,
address recipient,
uint256 amount,
bytes calldata data,
bytes calldata operatorData
)
external
{
require(isOperatorFor(msg.sender, sender), "PoolToken/not-operator");
_send(msg.sender, sender, recipient, amount, data, operatorData);
}
/**
* @dev See {IERC777-operatorBurn}.
*
* Currently not supported
*/
function operatorBurn(address, uint256, bytes calldata, bytes calldata) external {
revert("PoolToken/no-support");
}
/**
* @dev Allows an operator to redeem tokens for the underlying asset on behalf of a user.
*
* Emits {Redeemed} and {Transfer} events.
*/
function operatorRedeem(address account, uint256 amount, bytes calldata data, bytes calldata operatorData) external {
require(isOperatorFor(msg.sender, account), "PoolToken/not-operator");
_redeem(msg.sender, account, amount, data, operatorData);
}
/**
* @dev See {IERC20-allowance}.
*
* Note that operator and allowance concepts are orthogonal: operators may
* not have allowance, and accounts with allowance may not be operators
* themselves.
*/
function allowance(address holder, address spender) public view returns (uint256) {
return _allowances[holder][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Note that accounts cannot have allowance issued by their operators.
*/
function approve(address spender, uint256 value) external returns (bool) {
address holder = msg.sender;
_approve(holder, spender, value);
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(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, "PoolToken/negative"));
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Note that operator and allowance concepts are orthogonal: operators cannot
* call `transferFrom` (unless they have allowance), and accounts with
* allowance cannot call `operatorSend` (unless they are operators).
*
* Emits {Sent}, {Transfer} and {Approval} events.
*/
function transferFrom(address holder, address recipient, uint256 amount) external returns (bool) {
require(recipient != address(0), "PoolToken/to-zero");
require(holder != address(0), "PoolToken/from-zero");
address spender = msg.sender;
_callTokensToSend(spender, holder, recipient, amount, "", "");
_move(spender, holder, recipient, amount, "", "");
_approve(holder, spender, _allowances[holder][spender].sub(amount, "PoolToken/exceed-allow"));
_callTokensReceived(spender, holder, recipient, amount, "", "", false);
return true;
}
/**
* Called by the associated Pool to emit `Mint` events.
* @param amount The amount that was minted
*/
function poolMint(uint256 amount) external onlyPool {
_mintEvents(address(_pool), address(_pool), amount, '', '');
}
/**
* Emits {Minted} and {IERC20-Transfer} events.
*/
function _mintEvents(
address operator,
address account,
uint256 amount,
bytes memory userData,
bytes memory operatorData
)
internal
{
emit Minted(operator, account, amount, userData, operatorData);
emit Transfer(address(0), account, amount);
}
/**
* @dev Send tokens
* @param operator address operator requesting the transfer
* @param from address token holder address
* @param to address recipient address
* @param amount uint256 amount of tokens to transfer
* @param userData bytes extra information provided by the token holder (if any)
* @param operatorData bytes extra information provided by the operator (if any)
*/
function _send(
address operator,
address from,
address to,
uint256 amount,
bytes memory userData,
bytes memory operatorData
)
private
{
require(from != address(0), "PoolToken/from-zero");
require(to != address(0), "PoolToken/to-zero");
_callTokensToSend(operator, from, to, amount, userData, operatorData);
_move(operator, from, to, amount, userData, operatorData);
_callTokensReceived(operator, from, to, amount, userData, operatorData, false);
}
/**
* @dev Redeems tokens for the underlying asset.
* @param operator address operator requesting the operation
* @param from address token holder address
* @param amount uint256 amount of tokens to redeem
* @param data bytes extra information provided by the token holder
* @param operatorData bytes extra information provided by the operator (if any)
*/
function _redeem(
address operator,
address from,
uint256 amount,
bytes memory data,
bytes memory operatorData
)
private
{
require(from != address(0), "PoolToken/from-zero");
_callTokensToSend(operator, from, address(0), amount, data, operatorData);
_pool.withdrawCommittedDepositFrom(from, amount);
emit Redeemed(operator, from, amount, data, operatorData);
emit Transfer(from, address(0), amount);
}
/**
* @notice Moves tokens from one user to another. Emits Sent and Transfer events.
*/
function _move(
address operator,
address from,
address to,
uint256 amount,
bytes memory userData,
bytes memory operatorData
)
private
{
_pool.moveCommitted(from, to, amount);
emit Sent(operator, from, to, amount, userData, operatorData);
emit Transfer(from, to, amount);
}
/**
* Approves of a token spend by a spender for a holder.
* @param holder The address from which the tokens are spent
* @param spender The address that is spending the tokens
* @param value The amount of tokens to spend
*/
function _approve(address holder, address spender, uint256 value) private {
require(spender != address(0), "PoolToken/from-zero");
_allowances[holder][spender] = value;
emit Approval(holder, spender, value);
}
/**
* @dev Call from.tokensToSend() if the interface is registered
* @param operator address operator requesting the transfer
* @param from address token holder address
* @param to address recipient address
* @param amount uint256 amount of tokens to transfer
* @param userData bytes extra information provided by the token holder (if any)
* @param operatorData bytes extra information provided by the operator (if any)
*/
function _callTokensToSend(
address operator,
address from,
address to,
uint256 amount,
bytes memory userData,
bytes memory operatorData
)
internal notLocked
{
address implementer = ERC1820_REGISTRY.getInterfaceImplementer(from, TOKENS_SENDER_INTERFACE_HASH);
if (implementer != address(0)) {
IERC777Sender(implementer).tokensToSend(operator, from, to, amount, userData, operatorData);
}
}
/**
* @dev Call to.tokensReceived() if the interface is registered. Reverts if the recipient is a contract but
* tokensReceived() was not registered for the recipient
* @param operator address operator requesting the transfer
* @param from address token holder address
* @param to address recipient address
* @param amount uint256 amount of tokens to transfer
* @param userData bytes extra information provided by the token holder (if any)
* @param operatorData bytes extra information provided by the operator (if any)
* @param requireReceptionAck whether to require that, if the recipient is a contract, it has registered a IERC777Recipient
*/
function _callTokensReceived(
address operator,
address from,
address to,
uint256 amount,
bytes memory userData,
bytes memory operatorData,
bool requireReceptionAck
)
private
{
address implementer = ERC1820_REGISTRY.getInterfaceImplementer(to, TOKENS_RECIPIENT_INTERFACE_HASH);
if (implementer != address(0)) {
IERC777Recipient(implementer).tokensReceived(operator, from, to, amount, userData, operatorData);
} else if (requireReceptionAck) {
require(!to.isContract(), "PoolToken/no-recip-inter");
}
}
/**
* @notice Requires the sender to be the pool contract
*/
modifier onlyPool() {
require(msg.sender == address(_pool), "PoolToken/only-pool");
_;
}
/**
* @notice Requires the contract to be unlocked
*/
modifier notLocked() {
require(!_pool.isLocked(), "PoolToken/is-locked");
_;
}
}
/**
* @title The Pool contract
* @author Brendan Asselstine
* @notice This contract allows users to pool deposits into Compound and win the accrued interest in periodic draws.
* Funds are immediately deposited and withdrawn from the Compound cToken contract.
* Draws go through three stages: open, committed and rewarded in that order.
* Only one draw is ever in the open stage. Users deposits are always added to the open draw. Funds in the open Draw are that user's open balance.
* When a Draw is committed, the funds in it are moved to a user's committed total and the total committed balance of all users is updated.
* When a Draw is rewarded, the gross winnings are the accrued interest since the last reward (if any). A winner is selected with their chances being
* proportional to their committed balance vs the total committed balance of all users.
*
*
* With the above in mind, there is always an open draw and possibly a committed draw. The progression is:
*
* Step 1: Draw 1 Open
* Step 2: Draw 2 Open | Draw 1 Committed
* Step 3: Draw 3 Open | Draw 2 Committed | Draw 1 Rewarded
* Step 4: Draw 4 Open | Draw 3 Committed | Draw 2 Rewarded
* Step 5: Draw 5 Open | Draw 4 Committed | Draw 3 Rewarded
* Step X: ...
*/
contract BasePool is Initializable, ReentrancyGuard {
using DrawManager for DrawManager.State;
using SafeMath for uint256;
using Roles for Roles.Role;
using Blocklock for Blocklock.State;
bytes32 internal constant ROLLED_OVER_ENTROPY_MAGIC_NUMBER = bytes32(uint256(1));
IERC1820Registry constant internal ERC1820_REGISTRY = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24);
// We inline the result of the following hashes because Solidity doesn't resolve them at compile time.
// See https://github.com/ethereum/solidity/issues/4024.
// keccak256("PoolTogetherRewardListener")
bytes32 constant internal REWARD_LISTENER_INTERFACE_HASH =
0x68f03b0b1a978ee238a70b362091d993343460bc1a2830ab3f708936d9f564a4;
/**
* Emitted when a user deposits into the Pool.
* @param sender The purchaser of the tickets
* @param amount The size of the deposit
*/
event Deposited(address indexed sender, uint256 amount);
/**
* Emitted when a user deposits into the Pool and the deposit is immediately committed
* @param sender The purchaser of the tickets
* @param amount The size of the deposit
*/
event DepositedAndCommitted(address indexed sender, uint256 amount);
/**
* Emitted when Sponsors have deposited into the Pool
* @param sender The purchaser of the tickets
* @param amount The size of the deposit
*/
event SponsorshipDeposited(address indexed sender, uint256 amount);
/**
* Emitted when an admin has been added to the Pool.
* @param admin The admin that was added
*/
event AdminAdded(address indexed admin);
/**
* Emitted when an admin has been removed from the Pool.
* @param admin The admin that was removed
*/
event AdminRemoved(address indexed admin);
/**
* Emitted when a user withdraws from the pool.
* @param sender The user that is withdrawing from the pool
* @param amount The amount that the user withdrew
*/
event Withdrawn(address indexed sender, uint256 amount);
/**
* Emitted when a user withdraws their sponsorship and fees from the pool.
* @param sender The user that is withdrawing
* @param amount The amount they are withdrawing
*/
event SponsorshipAndFeesWithdrawn(address indexed sender, uint256 amount);
/**
* Emitted when a user withdraws from their open deposit.
* @param sender The user that is withdrawing
* @param amount The amount they are withdrawing
*/
event OpenDepositWithdrawn(address indexed sender, uint256 amount);
/**
* Emitted when a user withdraws from their committed deposit.
* @param sender The user that is withdrawing
* @param amount The amount they are withdrawing
*/
event CommittedDepositWithdrawn(address indexed sender, uint256 amount);
/**
* Emitted when an address collects a fee
* @param sender The address collecting the fee
* @param amount The fee amount
* @param drawId The draw from which the fee was awarded
*/
event FeeCollected(address indexed sender, uint256 amount, uint256 drawId);
/**
* Emitted when a new draw is opened for deposit.
* @param drawId The draw id
* @param feeBeneficiary The fee beneficiary for this draw
* @param secretHash The committed secret hash
* @param feeFraction The fee fraction of the winnings to be given to the beneficiary
*/
event Opened(
uint256 indexed drawId,
address indexed feeBeneficiary,
bytes32 secretHash,
uint256 feeFraction
);
/**
* Emitted when a draw is committed.
* @param drawId The draw id
*/
event Committed(
uint256 indexed drawId
);
/**
* Emitted when a draw is rewarded.
* @param drawId The draw id
* @param winner The address of the winner
* @param entropy The entropy used to select the winner
* @param winnings The net winnings given to the winner
* @param fee The fee being given to the draw beneficiary
*/
event Rewarded(
uint256 indexed drawId,
address indexed winner,
bytes32 entropy,
uint256 winnings,
uint256 fee
);
/**
* Emitted when a RewardListener call fails
* @param drawId The draw id
* @param winner The address that one the draw
* @param impl The implementation address of the RewardListener
*/
event RewardListenerFailed(
uint256 indexed drawId,
address indexed winner,
address indexed impl
);
/**
* Emitted when the fee fraction is changed. Takes effect on the next draw.
* @param feeFraction The next fee fraction encoded as a fixed point 18 decimal
*/
event NextFeeFractionChanged(uint256 feeFraction);
/**
* Emitted when the next fee beneficiary changes. Takes effect on the next draw.
* @param feeBeneficiary The next fee beneficiary
*/
event NextFeeBeneficiaryChanged(address indexed feeBeneficiary);
/**
* Emitted when an admin pauses the contract
*/
event DepositsPaused(address indexed sender);
/**
* Emitted when an admin unpauses the contract
*/
event DepositsUnpaused(address indexed sender);
/**
* Emitted when the draw is rolled over in the event that the secret is forgotten.
*/
event RolledOver(uint256 indexed drawId);
struct Draw {
uint256 feeFraction; //fixed point 18
address feeBeneficiary;
uint256 openedBlock;
bytes32 secretHash;
bytes32 entropy;
address winner;
uint256 netWinnings;
uint256 fee;
}
/**
* The Compound cToken that this Pool is bound to.
*/
ICErc20 public cToken;
/**
* The fee beneficiary to use for subsequent Draws.
*/
address public nextFeeBeneficiary;
/**
* The fee fraction to use for subsequent Draws.
*/
uint256 public nextFeeFraction;
/**
* The total of all balances
*/
uint256 public accountedBalance;
/**
* The total deposits and winnings for each user.
*/
mapping (address => uint256) internal balances;
/**
* A mapping of draw ids to Draw structures
*/
mapping(uint256 => Draw) internal draws;
/**
* A structure that is used to manage the user's odds of winning.
*/
DrawManager.State internal drawState;
/**
* A structure containing the administrators
*/
Roles.Role internal admins;
/**
* Whether the contract is paused
*/
bool public paused;
Blocklock.State internal blocklock;
PoolToken public poolToken;
/**
* @notice Initializes a new Pool contract.
* @param _owner The owner of the Pool. They are able to change settings and are set as the owner of new lotteries.
* @param _cToken The Compound Finance MoneyMarket contract to supply and withdraw tokens.
* @param _feeFraction The fraction of the gross winnings that should be transferred to the owner as the fee. Is a fixed point 18 number.
* @param _feeBeneficiary The address that will receive the fee fraction
*/
function init (
address _owner,
address _cToken,
uint256 _feeFraction,
address _feeBeneficiary,
uint256 _lockDuration,
uint256 _cooldownDuration
) public initializer {
require(_owner != address(0), "Pool/owner-zero");
require(_cToken != address(0), "Pool/ctoken-zero");
cToken = ICErc20(_cToken);
_addAdmin(_owner);
_setNextFeeFraction(_feeFraction);
_setNextFeeBeneficiary(_feeBeneficiary);
initBlocklock(_lockDuration, _cooldownDuration);
}
function setPoolToken(PoolToken _poolToken) external onlyAdmin {
require(address(poolToken) == address(0), "Pool/token-was-set");
require(address(_poolToken.pool()) == address(this), "Pool/token-mismatch");
poolToken = _poolToken;
}
function initBlocklock(uint256 _lockDuration, uint256 _cooldownDuration) internal {
blocklock.setLockDuration(_lockDuration);
blocklock.setCooldownDuration(_cooldownDuration);
}
/**
* @notice Opens a new Draw.
* @param _secretHash The secret hash to commit to the Draw.
*/
function open(bytes32 _secretHash) internal {
drawState.openNextDraw();
draws[drawState.openDrawIndex] = Draw(
nextFeeFraction,
nextFeeBeneficiary,
block.number,
_secretHash,
bytes32(0),
address(0),
uint256(0),
uint256(0)
);
emit Opened(
drawState.openDrawIndex,
nextFeeBeneficiary,
_secretHash,
nextFeeFraction
);
}
/**
* @notice Emits the Committed event for the current open draw.
*/
function emitCommitted() internal {
uint256 drawId = currentOpenDrawId();
emit Committed(drawId);
if (address(poolToken) != address(0)) {
poolToken.poolMint(openSupply());
}
}
/**
* @notice Commits the current open draw, if any, and opens the next draw using the passed hash. Really this function is only called twice:
* the first after Pool contract creation and the second immediately after.
* Can only be called by an admin.
* May fire the Committed event, and always fires the Open event.
* @param nextSecretHash The secret hash to use to open a new Draw
*/
function openNextDraw(bytes32 nextSecretHash) public onlyAdmin {
if (currentCommittedDrawId() > 0) {
require(currentCommittedDrawHasBeenRewarded(), "Pool/not-reward");
}
if (currentOpenDrawId() != 0) {
emitCommitted();
}
open(nextSecretHash);
}
/**
* @notice Ignores the current draw, and opens the next draw.
* @dev This function will be removed once the winner selection has been decentralized.
* @param nextSecretHash The hash to commit for the next draw
*/
function rolloverAndOpenNextDraw(bytes32 nextSecretHash) public onlyAdmin {
rollover();
openNextDraw(nextSecretHash);
}
/**
* @notice Rewards the current committed draw using the passed secret, commits the current open draw, and opens the next draw using the passed secret hash.
* Can only be called by an admin.
* Fires the Rewarded event, the Committed event, and the Open event.
* @param nextSecretHash The secret hash to use to open a new Draw
* @param lastSecret The secret to reveal to reward the current committed Draw.
* @param _salt The salt that was used to conceal the secret
*/
function rewardAndOpenNextDraw(bytes32 nextSecretHash, bytes32 lastSecret, bytes32 _salt) public onlyAdmin {
reward(lastSecret, _salt);
openNextDraw(nextSecretHash);
}
/**
* @notice Rewards the winner for the current committed Draw using the passed secret.
* The gross winnings are calculated by subtracting the accounted balance from the current underlying cToken balance.
* A winner is calculated using the revealed secret.
* If there is a winner (i.e. any eligible users) then winner's balance is updated with their net winnings.
* The draw beneficiary's balance is updated with the fee.
* The accounted balance is updated to include the fee and, if there was a winner, the net winnings.
* Fires the Rewarded event.
* @param _secret The secret to reveal for the current committed Draw
* @param _salt The salt that was used to conceal the secret
*/
function reward(bytes32 _secret, bytes32 _salt) public onlyAdmin onlyLocked requireCommittedNoReward nonReentrant {
// require that there is a committed draw
// require that the committed draw has not been rewarded
uint256 drawId = currentCommittedDrawId();
Draw storage draw = draws[drawId];
require(draw.secretHash == keccak256(abi.encodePacked(_secret, _salt)), "Pool/bad-secret");
// derive entropy from the revealed secret
bytes32 entropy = keccak256(abi.encodePacked(_secret));
_reward(drawId, draw, entropy);
}
function _reward(uint256 drawId, Draw storage draw, bytes32 entropy) internal {
blocklock.unlock(block.number);
// Select the winner using the hash as entropy
address winningAddress = calculateWinner(entropy);
// Calculate the gross winnings
uint256 underlyingBalance = balance();
uint256 grossWinnings;
// It's possible when the APR is zero that the underlying balance will be slightly lower than the accountedBalance
// due to rounding errors in the Compound contract.
if (underlyingBalance > accountedBalance) {
grossWinnings = capWinnings(underlyingBalance.sub(accountedBalance));
}
// Calculate the beneficiary fee
uint256 fee = calculateFee(draw.feeFraction, grossWinnings);
// Update balance of the beneficiary
balances[draw.feeBeneficiary] = balances[draw.feeBeneficiary].add(fee);
// Calculate the net winnings
uint256 netWinnings = grossWinnings.sub(fee);
draw.winner = winningAddress;
draw.netWinnings = netWinnings;
draw.fee = fee;
draw.entropy = entropy;
// If there is a winner who is to receive non-zero winnings
if (winningAddress != address(0) && netWinnings != 0) {
// Updated the accounted total
accountedBalance = underlyingBalance;
// Update balance of the winner
balances[winningAddress] = balances[winningAddress].add(netWinnings);
// Enter their winnings into the open draw
drawState.deposit(winningAddress, netWinnings);
callRewarded(winningAddress, netWinnings, drawId);
} else {
// Only account for the fee
accountedBalance = accountedBalance.add(fee);
}
emit Rewarded(
drawId,
winningAddress,
entropy,
netWinnings,
fee
);
emit FeeCollected(draw.feeBeneficiary, fee, drawId);
}
/**
* @notice Calls the reward listener for the winner, if a listener exists.
* @dev Checks for a listener using the ERC1820 registry. The listener is given a gas stipend of 200,000 to run the function.
* The number 200,000 was selected because it's safely above the gas requirements for PoolTogether [Pod](https://github.com/pooltogether/pods) contract.
*
* @param winner The winner. If they have a listener registered in the ERC1820 registry it will be called.
* @param netWinnings The amount that was won.
* @param drawId The draw id that was won.
*/
function callRewarded(address winner, uint256 netWinnings, uint256 drawId) internal {
address impl = ERC1820_REGISTRY.getInterfaceImplementer(winner, REWARD_LISTENER_INTERFACE_HASH);
if (impl != address(0)) {
(bool success,) = impl.call.gas(200000)(abi.encodeWithSignature("rewarded(address,uint256,uint256)", winner, netWinnings, drawId));
if (!success) {
emit RewardListenerFailed(drawId, winner, impl);
}
}
}
/**
* @notice A function that skips the reward for the committed draw id.
* @dev This function will be removed once the entropy is decentralized.
*/
function rollover() public onlyAdmin requireCommittedNoReward {
uint256 drawId = currentCommittedDrawId();
Draw storage draw = draws[drawId];
draw.entropy = ROLLED_OVER_ENTROPY_MAGIC_NUMBER;
emit RolledOver(
drawId
);
emit Rewarded(
drawId,
address(0),
ROLLED_OVER_ENTROPY_MAGIC_NUMBER,
0,
0
);
}
/**
* @notice Ensures that the winnings don't overflow. Note that we can make this integer max, because the fee
* is always less than zero (meaning the FixidityLib.multiply will always make the number smaller)
*/
function capWinnings(uint256 _grossWinnings) internal pure returns (uint256) {
uint256 max = uint256(FixidityLib.maxNewFixed());
if (_grossWinnings > max) {
return max;
}
return _grossWinnings;
}
/**
* @notice Calculate the beneficiary fee using the passed fee fraction and gross winnings.
* @param _feeFraction The fee fraction, between 0 and 1, represented as a 18 point fixed number.
* @param _grossWinnings The gross winnings to take a fraction of.
*/
function calculateFee(uint256 _feeFraction, uint256 _grossWinnings) internal pure returns (uint256) {
int256 grossWinningsFixed = FixidityLib.newFixed(int256(_grossWinnings));
// _feeFraction *must* be less than 1 ether, so it will never overflow
int256 feeFixed = FixidityLib.multiply(grossWinningsFixed, FixidityLib.newFixed(int256(_feeFraction), uint8(18)));
return uint256(FixidityLib.fromFixed(feeFixed));
}
/**
* @notice Allows a user to deposit a sponsorship amount. The deposit is transferred into the cToken.
* Sponsorships allow a user to contribute to the pool without becoming eligible to win. They can withdraw their sponsorship at any time.
* The deposit will immediately be added to Compound and the interest will contribute to the next draw.
* @param _amount The amount of the token underlying the cToken to deposit.
*/
function depositSponsorship(uint256 _amount) public unlessDepositsPaused nonReentrant {
// Transfer the tokens into this contract
require(token().transferFrom(msg.sender, address(this), _amount), "Pool/t-fail");
// Deposit the sponsorship amount
_depositSponsorshipFrom(msg.sender, _amount);
}
/**
* @notice Deposits the token balance for this contract as a sponsorship.
* If people erroneously transfer tokens to this contract, this function will allow us to recoup those tokens as sponsorship.
*/
function transferBalanceToSponsorship() public unlessDepositsPaused {
// Deposit the sponsorship amount
_depositSponsorshipFrom(address(this), token().balanceOf(address(this)));
}
/**
* @notice Deposits into the pool under the current open Draw. The deposit is transferred into the cToken.
* Once the open draw is committed, the deposit will be added to the user's total committed balance and increase their chances of winning
* proportional to the total committed balance of all users.
* @param _amount The amount of the token underlying the cToken to deposit.
*/
function depositPool(uint256 _amount) public requireOpenDraw unlessDepositsPaused nonReentrant notLocked {
// Transfer the tokens into this contract
require(token().transferFrom(msg.sender, address(this), _amount), "Pool/t-fail");
// Deposit the funds
_depositPoolFrom(msg.sender, _amount);
}
/**
* @notice Deposits sponsorship for a user
* @param _spender The user who is sponsoring
* @param _amount The amount they are sponsoring
*/
function _depositSponsorshipFrom(address _spender, uint256 _amount) internal {
// Deposit the funds
_depositFrom(_spender, _amount);
emit SponsorshipDeposited(_spender, _amount);
}
/**
* @notice Deposits into the pool for a user. The deposit will be open until the next draw is committed.
* @param _spender The user who is depositing
* @param _amount The amount the user is depositing
*/
function _depositPoolFrom(address _spender, uint256 _amount) internal {
// Update the user's eligibility
drawState.deposit(_spender, _amount);
_depositFrom(_spender, _amount);
emit Deposited(_spender, _amount);
}
/**
* @notice Deposits into the pool for a user. The deposit is made part of the currently committed draw
* @param _spender The user who is depositing
* @param _amount The amount to deposit
*/
function _depositPoolFromCommitted(address _spender, uint256 _amount) internal notLocked {
// Update the user's eligibility
drawState.depositCommitted(_spender, _amount);
_depositFrom(_spender, _amount);
emit DepositedAndCommitted(_spender, _amount);
}
/**
* @notice Deposits into the pool for a user. Updates their balance and transfers their tokens into this contract.
* @param _spender The user who is depositing
* @param _amount The amount they are depositing
*/
function _depositFrom(address _spender, uint256 _amount) internal {
// Update the user's balance
balances[_spender] = balances[_spender].add(_amount);
// Update the total of this contract
accountedBalance = accountedBalance.add(_amount);
// Deposit into Compound
require(token().approve(address(cToken), _amount), "Pool/approve");
require(cToken.mint(_amount) == 0, "Pool/supply");
}
/**
* Withdraws the given amount from the user's deposits. It first withdraws from their sponsorship,
* then their open deposits, then their committed deposits.
*
* @param amount The amount to withdraw.
*/
function withdraw(uint256 amount) public nonReentrant notLocked {
uint256 remainingAmount = amount;
// first sponsorship
uint256 sponsorshipAndFeesBalance = sponsorshipAndFeeBalanceOf(msg.sender);
if (sponsorshipAndFeesBalance < remainingAmount) {
withdrawSponsorshipAndFee(sponsorshipAndFeesBalance);
remainingAmount = remainingAmount.sub(sponsorshipAndFeesBalance);
} else {
withdrawSponsorshipAndFee(remainingAmount);
return;
}
// now pending
uint256 pendingBalance = drawState.openBalanceOf(msg.sender);
if (pendingBalance < remainingAmount) {
_withdrawOpenDeposit(msg.sender, pendingBalance);
remainingAmount = remainingAmount.sub(pendingBalance);
} else {
_withdrawOpenDeposit(msg.sender, remainingAmount);
return;
}
// now committed. remainingAmount should not be greater than committed balance.
_withdrawCommittedDeposit(msg.sender, remainingAmount);
}
/**
* @notice Withdraw the sender's entire balance back to them.
*/
function withdraw() public nonReentrant notLocked {
uint256 committedBalance = drawState.committedBalanceOf(msg.sender);
uint256 balance = balances[msg.sender];
// Update their chances of winning
drawState.withdraw(msg.sender);
_withdraw(msg.sender, balance);
if (address(poolToken) != address(0)) {
poolToken.poolRedeem(msg.sender, committedBalance);
}
emit Withdrawn(msg.sender, balance);
}
/**
* Withdraws only from the sender's sponsorship and fee balances
* @param _amount The amount to withdraw
*/
function withdrawSponsorshipAndFee(uint256 _amount) public {
uint256 sponsorshipAndFees = sponsorshipAndFeeBalanceOf(msg.sender);
require(_amount <= sponsorshipAndFees, "Pool/exceeds-sfee");
_withdraw(msg.sender, _amount);
emit SponsorshipAndFeesWithdrawn(msg.sender, _amount);
}
/**
* Returns the total balance of the user's sponsorship and fees
* @param _sender The user whose balance should be returned
*/
function sponsorshipAndFeeBalanceOf(address _sender) public view returns (uint256) {
return balances[_sender].sub(drawState.balanceOf(_sender));
}
/**
* Withdraws from the user's open deposits
* @param _amount The amount to withdraw
*/
function withdrawOpenDeposit(uint256 _amount) public nonReentrant notLocked {
_withdrawOpenDeposit(msg.sender, _amount);
}
function _withdrawOpenDeposit(address sender, uint256 _amount) internal {
drawState.withdrawOpen(sender, _amount);
_withdraw(sender, _amount);
emit OpenDepositWithdrawn(sender, _amount);
}
/**
* Withdraws from the user's committed deposits
* @param _amount The amount to withdraw
*/
function withdrawCommittedDeposit(uint256 _amount) public nonReentrant notLocked returns (bool) {
_withdrawCommittedDeposit(msg.sender, _amount);
return true;
}
function _withdrawCommittedDeposit(address sender, uint256 _amount) internal {
_withdrawCommittedDepositAndEmit(sender, _amount);
if (address(poolToken) != address(0)) {
poolToken.poolRedeem(sender, _amount);
}
}
/**
* Allows the associated PoolToken to withdraw for a user; useful when redeeming through the token.
* @param _from The user to withdraw from
* @param _amount The amount to withdraw
*/
function withdrawCommittedDepositFrom(
address _from,
uint256 _amount
) external onlyToken notLocked returns (bool) {
return _withdrawCommittedDepositAndEmit(_from, _amount);
}
/**
* A function that withdraws committed deposits for a user and emits the corresponding events.
* @param _from User to withdraw for
* @param _amount The amount to withdraw
*/
function _withdrawCommittedDepositAndEmit(address _from, uint256 _amount) internal returns (bool) {
drawState.withdrawCommitted(_from, _amount);
_withdraw(_from, _amount);
emit CommittedDepositWithdrawn(_from, _amount);
return true;
}
/**
* @notice Allows the associated PoolToken to move committed tokens from one user to another.
* @param _from The account to move tokens from
* @param _to The account that is receiving the tokens
* @param _amount The amount of tokens to transfer
*/
function moveCommitted(
address _from,
address _to,
uint256 _amount
) external onlyToken onlyCommittedBalanceGteq(_from, _amount) notLocked returns (bool) {
balances[_from] = balances[_from].sub(_amount, "move could not sub amount");
balances[_to] = balances[_to].add(_amount);
drawState.withdrawCommitted(_from, _amount);
drawState.depositCommitted(_to, _amount);
return true;
}
/**
* @notice Transfers tokens from the cToken contract to the sender. Updates the accounted balance.
*/
function _withdraw(address _sender, uint256 _amount) internal {
uint256 balance = balances[_sender];
require(_amount <= balance, "Pool/no-funds");
// Update the user's balance
balances[_sender] = balance.sub(_amount);
// Update the total of this contract
accountedBalance = accountedBalance.sub(_amount);
// Withdraw from Compound and transfer
require(cToken.redeemUnderlying(_amount) == 0, "Pool/redeem");
require(token().transfer(_sender, _amount), "Pool/transfer");
}
/**
* @notice Returns the id of the current open Draw.
* @return The current open Draw id
*/
function currentOpenDrawId() public view returns (uint256) {
return drawState.openDrawIndex;
}
/**
* @notice Returns the id of the current committed Draw.
* @return The current committed Draw id
*/
function currentCommittedDrawId() public view returns (uint256) {
if (drawState.openDrawIndex > 1) {
return drawState.openDrawIndex - 1;
} else {
return 0;
}
}
/**
* @notice Returns whether the current committed draw has been rewarded
* @return True if the current committed draw has been rewarded, false otherwise
*/
function currentCommittedDrawHasBeenRewarded() internal view returns (bool) {
Draw storage draw = draws[currentCommittedDrawId()];
return draw.entropy != bytes32(0);
}
/**
* @notice Gets information for a given draw.
* @param _drawId The id of the Draw to retrieve info for.
* @return Fields including:
* feeFraction: the fee fraction
* feeBeneficiary: the beneficiary of the fee
* openedBlock: The block at which the draw was opened
* secretHash: The hash of the secret committed to this draw.
* entropy: the entropy used to select the winner
* winner: the address of the winner
* netWinnings: the total winnings less the fee
* fee: the fee taken by the beneficiary
*/
function getDraw(uint256 _drawId) public view returns (
uint256 feeFraction,
address feeBeneficiary,
uint256 openedBlock,
bytes32 secretHash,
bytes32 entropy,
address winner,
uint256 netWinnings,
uint256 fee
) {
Draw storage draw = draws[_drawId];
feeFraction = draw.feeFraction;
feeBeneficiary = draw.feeBeneficiary;
openedBlock = draw.openedBlock;
secretHash = draw.secretHash;
entropy = draw.entropy;
winner = draw.winner;
netWinnings = draw.netWinnings;
fee = draw.fee;
}
/**
* @notice Returns the total of the address's balance in committed Draws. That is, the total that contributes to their chances of winning.
* @param _addr The address of the user
* @return The total committed balance for the user
*/
function committedBalanceOf(address _addr) external view returns (uint256) {
return drawState.committedBalanceOf(_addr);
}
/**
* @notice Returns the total of the address's balance in the open Draw. That is, the total that will *eventually* contribute to their chances of winning.
* @param _addr The address of the user
* @return The total open balance for the user
*/
function openBalanceOf(address _addr) external view returns (uint256) {
return drawState.openBalanceOf(_addr);
}
/**
* @notice Returns a user's total balance. This includes their sponsorships, fees, open deposits, and committed deposits.
* @param _addr The address of the user to check.
* @return The user's current balance.
*/
function totalBalanceOf(address _addr) external view returns (uint256) {
return balances[_addr];
}
/**
* @notice Returns a user's committed balance. This is the balance of their Pool tokens.
* @param _addr The address of the user to check.
* @return The user's current balance.
*/
function balanceOf(address _addr) external view returns (uint256) {
return drawState.committedBalanceOf(_addr);
}
/**
* @notice Calculates a winner using the passed entropy for the current committed balances.
* @param _entropy The entropy to use to select the winner
* @return The winning address
*/
function calculateWinner(bytes32 _entropy) public view returns (address) {
return drawState.drawWithEntropy(_entropy);
}
/**
* @notice Returns the total committed balance. Used to compute an address's chances of winning.
* @return The total committed balance.
*/
function committedSupply() public view returns (uint256) {
return drawState.committedSupply();
}
/**
* @notice Returns the total open balance. This balance is the number of tickets purchased for the open draw.
* @return The total open balance
*/
function openSupply() public view returns (uint256) {
return drawState.openSupply();
}
/**
* @notice Calculates the total estimated interest earned for the given number of blocks
* @param _blocks The number of block that interest accrued for
* @return The total estimated interest as a 18 point fixed decimal.
*/
function estimatedInterestRate(uint256 _blocks) public view returns (uint256) {
return supplyRatePerBlock().mul(_blocks);
}
/**
* @notice Convenience function to return the supplyRatePerBlock value from the money market contract.
* @return The cToken supply rate per block
*/
function supplyRatePerBlock() public view returns (uint256) {
return cToken.supplyRatePerBlock();
}
/**
* @notice Sets the beneficiary fee fraction for subsequent Draws.
* Fires the NextFeeFractionChanged event.
* Can only be called by an admin.
* @param _feeFraction The fee fraction to use.
* Must be between 0 and 1 and formatted as a fixed point number with 18 decimals (as in Ether).
*/
function setNextFeeFraction(uint256 _feeFraction) public onlyAdmin {
_setNextFeeFraction(_feeFraction);
}
function _setNextFeeFraction(uint256 _feeFraction) internal {
require(_feeFraction <= 1 ether, "Pool/less-1");
nextFeeFraction = _feeFraction;
emit NextFeeFractionChanged(_feeFraction);
}
/**
* @notice Sets the fee beneficiary for subsequent Draws.
* Can only be called by admins.
* @param _feeBeneficiary The beneficiary for the fee fraction. Cannot be the 0 address.
*/
function setNextFeeBeneficiary(address _feeBeneficiary) public onlyAdmin {
_setNextFeeBeneficiary(_feeBeneficiary);
}
/**
* @notice Sets the fee beneficiary for subsequent Draws.
* @param _feeBeneficiary The beneficiary for the fee fraction. Cannot be the 0 address.
*/
function _setNextFeeBeneficiary(address _feeBeneficiary) internal {
require(_feeBeneficiary != address(0), "Pool/not-zero");
nextFeeBeneficiary = _feeBeneficiary;
emit NextFeeBeneficiaryChanged(_feeBeneficiary);
}
/**
* @notice Adds an administrator.
* Can only be called by administrators.
* Fires the AdminAdded event.
* @param _admin The address of the admin to add
*/
function addAdmin(address _admin) public onlyAdmin {
_addAdmin(_admin);
}
/**
* @notice Checks whether a given address is an administrator.
* @param _admin The address to check
* @return True if the address is an admin, false otherwise.
*/
function isAdmin(address _admin) public view returns (bool) {
return admins.has(_admin);
}
/**
* @notice Checks whether a given address is an administrator.
* @param _admin The address to check
* @return True if the address is an admin, false otherwise.
*/
function _addAdmin(address _admin) internal {
admins.add(_admin);
emit AdminAdded(_admin);
}
/**
* @notice Removes an administrator
* Can only be called by an admin.
* Admins cannot remove themselves. This ensures there is always one admin.
* @param _admin The address of the admin to remove
*/
function removeAdmin(address _admin) public onlyAdmin {
require(admins.has(_admin), "Pool/no-admin");
require(_admin != msg.sender, "Pool/remove-self");
admins.remove(_admin);
emit AdminRemoved(_admin);
}
/**
* Requires that there is a committed draw that has not been rewarded.
*/
modifier requireCommittedNoReward() {
require(currentCommittedDrawId() > 0, "Pool/committed");
require(!currentCommittedDrawHasBeenRewarded(), "Pool/already");
_;
}
/**
* @notice Returns the token underlying the cToken.
* @return An ERC20 token address
*/
function token() public view returns (IERC20) {
return IERC20(cToken.underlying());
}
/**
* @notice Returns the underlying balance of this contract in the cToken.
* @return The cToken underlying balance for this contract.
*/
function balance() public returns (uint256) {
return cToken.balanceOfUnderlying(address(this));
}
/**
* @notice Locks the movement of tokens (essentially the committed deposits and winnings)
* @dev The lock only lasts for a duration of blocks. The lock cannot be relocked until the cooldown duration completes.
*/
function lockTokens() public onlyAdmin {
blocklock.lock(block.number);
}
/**
* @notice Unlocks the movement of tokens (essentially the committed deposits)
*/
function unlockTokens() public onlyAdmin {
blocklock.unlock(block.number);
}
/**
* Pauses all deposits into the contract. This was added so that we can slowly deprecate Pools. Users can continue
* to collect rewards and withdraw, but eventually the Pool will grow smaller.
*
* emits DepositsPaused
*/
function pauseDeposits() public unlessDepositsPaused onlyAdmin {
paused = true;
emit DepositsPaused(msg.sender);
}
/**
* @notice Unpauses all deposits into the contract
*
* emits DepositsUnpaused
*/
function unpauseDeposits() public whenDepositsPaused onlyAdmin {
paused = false;
emit DepositsUnpaused(msg.sender);
}
/**
* @notice Check if the contract is locked.
* @return True if the contract is locked, false otherwise
*/
function isLocked() public view returns (bool) {
return blocklock.isLocked(block.number);
}
/**
* @notice Returns the block number at which the lock expires
* @return The block number at which the lock expires
*/
function lockEndAt() public view returns (uint256) {
return blocklock.lockEndAt();
}
/**
* @notice Check cooldown end block
* @return The block number at which the cooldown ends and the contract can be re-locked
*/
function cooldownEndAt() public view returns (uint256) {
return blocklock.cooldownEndAt();
}
/**
* @notice Returns whether the contract can be locked
* @return True if the contract can be locked, false otherwise
*/
function canLock() public view returns (bool) {
return blocklock.canLock(block.number);
}
/**
* @notice Duration of the lock
* @return Returns the duration of the lock in blocks.
*/
function lockDuration() public view returns (uint256) {
return blocklock.lockDuration;
}
/**
* @notice Returns the cooldown duration. The cooldown period starts after the Pool has been unlocked.
* The Pool cannot be locked during the cooldown period.
* @return The cooldown duration in blocks
*/
function cooldownDuration() public view returns (uint256) {
return blocklock.cooldownDuration;
}
/**
* @notice requires the pool not to be locked
*/
modifier notLocked() {
require(!blocklock.isLocked(block.number), "Pool/locked");
_;
}
/**
* @notice requires the pool to be locked
*/
modifier onlyLocked() {
require(blocklock.isLocked(block.number), "Pool/unlocked");
_;
}
/**
* @notice requires the caller to be an admin
*/
modifier onlyAdmin() {
require(admins.has(msg.sender), "Pool/admin");
_;
}
/**
* @notice Requires an open draw to exist
*/
modifier requireOpenDraw() {
require(currentOpenDrawId() != 0, "Pool/no-open");
_;
}
/**
* @notice Requires deposits to be paused
*/
modifier whenDepositsPaused() {
require(paused, "Pool/d-not-paused");
_;
}
/**
* @notice Requires deposits not to be paused
*/
modifier unlessDepositsPaused() {
require(!paused, "Pool/d-paused");
_;
}
/**
* @notice Requires the caller to be the pool token
*/
modifier onlyToken() {
require(msg.sender == address(poolToken), "Pool/only-token");
_;
}
/**
* @notice requires the passed user's committed balance to be greater than or equal to the passed amount
* @param _from The user whose committed balance should be checked
* @param _amount The minimum amount they must have
*/
modifier onlyCommittedBalanceGteq(address _from, uint256 _amount) {
uint256 committedBalance = drawState.committedBalanceOf(_from);
require(_amount <= committedBalance, "not enough funds");
_;
}
}
contract ScdMcdMigration {
SaiTubLike public tub;
VatLike public vat;
ManagerLike public cdpManager;
JoinLike public saiJoin;
JoinLike public wethJoin;
JoinLike public daiJoin;
constructor(
address tub_, // SCD tub contract address
address cdpManager_, // MCD manager contract address
address saiJoin_, // MCD SAI collateral adapter contract address
address wethJoin_, // MCD ETH collateral adapter contract address
address daiJoin_ // MCD DAI adapter contract address
) public {
tub = SaiTubLike(tub_);
cdpManager = ManagerLike(cdpManager_);
vat = VatLike(cdpManager.vat());
saiJoin = JoinLike(saiJoin_);
wethJoin = JoinLike(wethJoin_);
daiJoin = JoinLike(daiJoin_);
require(wethJoin.gem() == tub.gem(), "non-matching-weth");
require(saiJoin.gem() == tub.sai(), "non-matching-sai");
tub.gov().approve(address(tub), uint(-1));
tub.skr().approve(address(tub), uint(-1));
tub.sai().approve(address(tub), uint(-1));
tub.sai().approve(address(saiJoin), uint(-1));
wethJoin.gem().approve(address(wethJoin), uint(-1));
daiJoin.dai().approve(address(daiJoin), uint(-1));
vat.hope(address(daiJoin));
}
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x, "add-overflow");
}
function sub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x, "sub-underflow");
}
function mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x, "mul-overflow");
}
function toInt(uint x) internal pure returns (int y) {
y = int(x);
require(y >= 0, "int-overflow");
}
// Function to swap SAI to DAI
// This function is to be used by users that want to get new DAI in exchange of old one (aka SAI)
// wad amount has to be <= the value pending to reach the debt ceiling (the minimum between general and ilk one)
function swapSaiToDai(
uint wad
) external {
// Get wad amount of SAI from user's wallet:
saiJoin.gem().transferFrom(msg.sender, address(this), wad);
// Join the SAI wad amount to the `vat`:
saiJoin.join(address(this), wad);
// Lock the SAI wad amount to the CDP and generate the same wad amount of DAI
vat.frob(saiJoin.ilk(), address(this), address(this), address(this), toInt(wad), toInt(wad));
// Send DAI wad amount as a ERC20 token to the user's wallet
daiJoin.exit(msg.sender, wad);
}
// Function to swap DAI to SAI
// This function is to be used by users that want to get SAI in exchange of DAI
// wad amount has to be <= the amount of SAI locked (and DAI generated) in the migration contract SAI CDP
function swapDaiToSai(
uint wad
) external {
// Get wad amount of DAI from user's wallet:
daiJoin.dai().transferFrom(msg.sender, address(this), wad);
// Join the DAI wad amount to the vat:
daiJoin.join(address(this), wad);
// Payback the DAI wad amount and unlocks the same value of SAI collateral
vat.frob(saiJoin.ilk(), address(this), address(this), address(this), -toInt(wad), -toInt(wad));
// Send SAI wad amount as a ERC20 token to the user's wallet
saiJoin.exit(msg.sender, wad);
}
// Function to migrate a SCD CDP to MCD one (needs to be used via a proxy so the code can be kept simpler). Check MigrationProxyActions.sol code for usage.
// In order to use migrate function, SCD CDP debtAmt needs to be <= SAI previously deposited in the SAI CDP * (100% - Collateralization Ratio)
function migrate(
bytes32 cup
) external returns (uint cdp) {
// Get values
uint debtAmt = tub.tab(cup); // CDP SAI debt
uint pethAmt = tub.ink(cup); // CDP locked collateral
uint ethAmt = tub.bid(pethAmt); // CDP locked collateral equiv in ETH
// Take SAI out from MCD SAI CDP. For this operation is necessary to have a very low collateralization ratio
// This is not actually a problem as this ilk will only be accessed by this migration contract,
// which will make sure to have the amounts balanced out at the end of the execution.
vat.frob(
bytes32(saiJoin.ilk()),
address(this),
address(this),
address(this),
-toInt(debtAmt),
0
);
saiJoin.exit(address(this), debtAmt); // SAI is exited as a token
// Shut SAI CDP and gets WETH back
tub.shut(cup); // CDP is closed using the SAI just exited and the MKR previously sent by the user (via the proxy call)
tub.exit(pethAmt); // Converts PETH to WETH
// Open future user's CDP in MCD
cdp = cdpManager.open(wethJoin.ilk(), address(this));
// Join WETH to Adapter
wethJoin.join(cdpManager.urns(cdp), ethAmt);
// Lock WETH in future user's CDP and generate debt to compensate the SAI used to paid the SCD CDP
(, uint rate,,,) = vat.ilks(wethJoin.ilk());
cdpManager.frob(
cdp,
toInt(ethAmt),
toInt(mul(debtAmt, 10 ** 27) / rate + 1) // To avoid rounding issues we add an extra wei of debt
);
// Move DAI generated to migration contract (to recover the used funds)
cdpManager.move(cdp, address(this), mul(debtAmt, 10 ** 27));
// Re-balance MCD SAI migration contract's CDP
vat.frob(
bytes32(saiJoin.ilk()),
address(this),
address(this),
address(this),
0,
-toInt(debtAmt)
);
// Set ownership of CDP to the user
cdpManager.give(cdp, msg.sender);
}
}
/**
* @dev Interface of the ERC777TokensRecipient standard as defined in the EIP.
*
* Accounts can be notified of {IERC777} tokens being sent to them by having a
* contract implement this interface (contract holders can be their own
* implementer) and registering it on the
* https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry].
*
* See {IERC1820Registry} and {ERC1820Implementer}.
*/
interface IERC777Recipient {
/**
* @dev Called by an {IERC777} token contract whenever tokens are being
* moved or created into a registered account (`to`). The type of operation
* is conveyed by `from` being the zero address or not.
*
* This call occurs _after_ the token contract's state is updated, so
* {IERC777-balanceOf}, etc., can be used to query the post-operation state.
*
* This function may revert to prevent the operation from being executed.
*/
function tokensReceived(
address operator,
address from,
address to,
uint256 amount,
bytes calldata userData,
bytes calldata operatorData
) external;
}
/**
* @title MCDAwarePool
* @author Brendan Asselstine [emailΒ protected]
* @notice This contract is a Pool that is aware of the new Multi-Collateral Dai. It uses the ERC777Recipient interface to
* detect if it's being transferred tickets from the old single collateral Dai (Sai) Pool. If it is, it migrates the Sai to Dai
* and immediately deposits the new Dai as committed tickets for that user. We are knowingly bypassing the committed period for
* users to encourage them to migrate to the MCD Pool.
*/
contract MCDAwarePool is BasePool, IERC777Recipient {
IERC1820Registry constant internal ERC1820_REGISTRY = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24);
// keccak256("ERC777TokensRecipient")
bytes32 constant internal TOKENS_RECIPIENT_INTERFACE_HASH =
0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b;
uint256 internal constant DEFAULT_LOCK_DURATION = 40;
uint256 internal constant DEFAULT_COOLDOWN_DURATION = 80;
/**
* @notice The address of the ScdMcdMigration contract (see https://github.com/makerdao/developerguides/blob/master/mcd/upgrading-to-multi-collateral-dai/upgrading-to-multi-collateral-dai.md#direct-integration-with-smart-contracts)
*/
ScdMcdMigration public scdMcdMigration;
/**
* @notice The address of the Sai Pool contract
*/
MCDAwarePool public saiPool;
/**
* @notice Initializes the contract.
* @param _owner The initial administrator of the contract
* @param _cToken The Compound cToken to bind this Pool to
* @param _feeFraction The fraction of the winnings to give to the beneficiary
* @param _feeBeneficiary The beneficiary who receives the fee
*/
function init (
address _owner,
address _cToken,
uint256 _feeFraction,
address _feeBeneficiary,
uint256 lockDuration,
uint256 cooldownDuration
) public initializer {
super.init(
_owner,
_cToken,
_feeFraction,
_feeBeneficiary,
lockDuration,
cooldownDuration
);
initRegistry();
initBlocklock(lockDuration, cooldownDuration);
}
/**
* @notice Used to initialize the BasePool contract after an upgrade. Registers the MCDAwarePool with the ERC1820 registry so that it can receive tokens, and inits the block lock.
*/
function initMCDAwarePool(uint256 lockDuration, uint256 cooldownDuration) public {
initRegistry();
if (blocklock.lockDuration == 0) {
initBlocklock(lockDuration, cooldownDuration);
}
}
function initRegistry() internal {
ERC1820_REGISTRY.setInterfaceImplementer(address(this), TOKENS_RECIPIENT_INTERFACE_HASH, address(this));
}
function initMigration(ScdMcdMigration _scdMcdMigration, MCDAwarePool _saiPool) public onlyAdmin {
_initMigration(_scdMcdMigration, _saiPool);
}
function _initMigration(ScdMcdMigration _scdMcdMigration, MCDAwarePool _saiPool) internal {
require(address(scdMcdMigration) == address(0), "Pool/init");
require(address(_scdMcdMigration) != address(0), "Pool/mig-def");
scdMcdMigration = _scdMcdMigration;
saiPool = _saiPool; // may be null
}
/**
* @notice Called by an ERC777 token when tokens are sent, transferred, or minted. If the sender is the original Sai Pool
* and this pool is bound to the Dai token then it will accept the transfer, migrate the tokens, and deposit on behalf of
* the sender. It will reject all other tokens.
*
* If there is a committed draw this function will mint the user tickets immediately, otherwise it will place them in the
* open prize. This is to encourage migration.
*
* @param from The sender
* @param amount The amount they are transferring
*/
function tokensReceived(
address, // operator
address from,
address, // to address can't be anything but us because we don't implement ERC1820ImplementerInterface
uint256 amount,
bytes calldata,
bytes calldata
) external unlessDepositsPaused {
require(msg.sender == address(saiPoolToken()), "Pool/sai-only");
require(address(token()) == address(daiToken()), "Pool/not-dai");
// cash out of the Pool. This call transfers sai to this contract
saiPoolToken().redeem(amount, '');
// approve of the transfer to the migration contract
saiToken().approve(address(scdMcdMigration), amount);
// migrate the sai to dai. The contract now has dai
scdMcdMigration.swapSaiToDai(amount);
if (currentCommittedDrawId() > 0) {
// now deposit the dai as tickets
_depositPoolFromCommitted(from, amount);
} else {
_depositPoolFrom(from, amount);
}
}
/**
* @notice Returns the address of the PoolSai pool token contract
* @return The address of the Sai PoolToken contract
*/
function saiPoolToken() internal view returns (PoolToken) {
if (address(saiPool) != address(0)) {
return saiPool.poolToken();
} else {
return PoolToken(0);
}
}
/**
* @notice Returns the address of the Sai token
* @return The address of the sai token
*/
function saiToken() public returns (GemLike) {
return scdMcdMigration.saiJoin().gem();
}
/**
* @notice Returns the address of the Dai token
* @return The address of the Dai token.
*/
function daiToken() public returns (GemLike) {
return scdMcdMigration.daiJoin().dai();
}
}
|
Check if the contract is locked. return True if the contract is locked, false otherwise/
|
function isLocked() public view returns (bool) {
return blocklock.isLocked(block.number);
}
| 8,015,452 |
./partial_match/1/0x9460b380c57F65e8AFc4bA3518F643A526640F26/sources/contracts/dependencies/uniswapv3-core/interfaces/IERC20Minimal.sol
|
Minimal ERC20 interface for Uniswap Contains a subset of the full ERC20 interface that is used in Uniswap V3
|
interface IERC20Minimal {
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);
pragma solidity ^0.8.0;
}
| 4,203,146 |
//SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage)
internal
pure
returns (uint256)
{
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage)
internal
pure
returns (uint256)
{
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage)
internal
pure
returns (uint256)
{
require(b != 0, errorMessage);
return a % b;
}
}
/*
* @dev 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 () { }
// 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;
}
}
/**
* @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());
}
}
/**
* @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 () {
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;
}
}
/**
* @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);
}
}
}
}
/**
* @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;
using SafeMath for uint256;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount)
external
returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender)
external
view
returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount)
external
returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
interface IPLUGV1 {
function upgradePlug(uint256 nextLevelCap) external;
function chargePlug(uint256 amount) external;
function dischargePlug(uint256 plugPercentage) external;
function rebalancePlug() external;
function tokenWant() external view returns(address);
function tokenStrategy() external view returns(address);
function tokenReward() external view returns(address);
}
abstract contract IdleYield {
function mintIdleToken(uint256 amount, bool skipRebalance, address referral) external virtual returns(uint256);
function redeemIdleToken(uint256 amount) external virtual returns(uint256);
function balanceOf(address user) external virtual returns(uint256);
function tokenPrice() external virtual view returns(uint256);
function userAvgPrices(address user) external virtual view returns(uint256);
function fee() external virtual view returns(uint256);
}
contract PLUGIDLEV1 is IPLUGV1, Ownable, Pausable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
uint256 private constant ONE_18 = 10**18;
uint256 private constant FULL_ALLOC = 100000;
address public constant override tokenWant = address(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48); // USDC
address public constant override tokenStrategy = address(0x5274891bEC421B39D23760c04A6755eCB444797C); // IDLEUSDC
address public override tokenReward = address(0x20a68F9e34076b2dc15ce726d7eEbB83b694702d); // ISLA
IdleYield strategy = IdleYield(tokenStrategy);
IERC20 iTokenWant = IERC20(tokenWant);
// addresses to send interests generated
address public rewardOutOne;
address public rewardOutTwo;
// it should be used only when plug balance has to move to another plug
address public plugHelper;
// Plug parameter
uint256 public currentLevelCap = uint256(150000).mul(ONE_18); // 150K token want
uint256 public plugLimit = uint256(50000).mul(ONE_18); // 50K plug limit
uint256 public plugLevel;
mapping (address => uint256) public tokenStrategyAmounts;
mapping (address => uint256) public tokenWantAmounts;
mapping (address => uint256) public tokenWantDonated;
uint256 public usersTokenWant;
uint256 public lastRebalanceTs;
uint256 twInStrategyLastRebalance;
uint256 public rebalancePeriod = 3 days;
uint256 public rewardRate = ONE_18;
event PlugCharged(address user, uint256 amount, uint256 amountMinted);
event PlugDischarged(address user, uint256 userAmount, uint256 rewardForUSer, uint256 rewardForPlug);
event SentRewardToOutOne(address token, uint256 amount);
event SentRewardToOutTwo(address token, uint256 amount);
event Rebalance(uint256 amountEarned);
constructor() {
iTokenWant.approve(tokenStrategy, uint256(-1));
}
/**
* Charge plug staking token want into idle.
*/
function chargePlug(uint256 _amount) external override whenNotPaused() {
usersTokenWant = usersTokenWant.add(_amount);
require(usersTokenWant < plugLimit);
iTokenWant.safeTransferFrom(msg.sender, address(this), _amount);
require(_getPlugBalance(tokenWant) >= _amount);
uint256 amountMinted = strategy.mintIdleToken(_amount, true, address(0));
tokenStrategyAmounts[msg.sender] = tokenStrategyAmounts[msg.sender].add(amountMinted);
tokenWantAmounts[msg.sender] = tokenWantAmounts[msg.sender].add(_amount);
emit PlugCharged(msg.sender, _amount, amountMinted);
}
/**
* Discharge plug withdrawing all token staked into idle
* Choose the percentage to donate into the plug (0, 50, 100)
* If there is any reward active it will be send respecting the actual reward rate
*/
function dischargePlug(uint256 _plugPercentage) external override whenNotPaused() {
_dischargePlug(_plugPercentage);
}
/**
* Internal function to discharge plug
*/
function _dischargePlug(uint256 _plugPercentage) internal {
require(_plugPercentage == 0 || _plugPercentage == 50 || _plugPercentage == 100);
uint256 userAmount = tokenWantAmounts[msg.sender];
require(userAmount > 0);
// transfer token want from IDLE to plug
uint256 amountRedeemed = strategy.redeemIdleToken(tokenStrategyAmounts[msg.sender]);
usersTokenWant = usersTokenWant.sub(userAmount);
// token want earned
uint256 tokenEarned;
uint256 rewardForUser;
uint256 rewardForPlug;
uint256 amountToDischarge;
// it should be always greater, added for safe
if (amountRedeemed <= userAmount) {
tokenEarned = 0;
userAmount = amountRedeemed;
} else {
tokenEarned = amountRedeemed.sub(userAmount);
rewardForUser = tokenEarned;
}
// calculate token earned percentage to donate into plug
if (_plugPercentage > 0 && tokenEarned > 0) {
rewardForPlug = tokenEarned;
rewardForUser = 0;
if (_plugPercentage == 50) {
rewardForPlug = rewardForPlug.div(2);
rewardForUser = tokenEarned.sub(rewardForPlug);
}
uint256 rewardLeft = _getPlugBalance(tokenReward);
if (rewardLeft > 0) {
uint256 rewardWithRate = rewardForPlug.mul(rewardRate).div(ONE_18);
_sendReward(rewardLeft, rewardWithRate);
}
tokenWantDonated[msg.sender] = tokenWantDonated[msg.sender].add(rewardForPlug);
}
// transfer tokenWant userAmount to user
amountToDischarge = userAmount.add(rewardForUser);
_dischargeUser(amountToDischarge);
emit PlugDischarged(msg.sender, userAmount, rewardForUser, rewardForPlug);
}
/**
* Sending all token want owned by an user.
*/
function _dischargeUser(uint256 _amount) internal {
_sendTokenWant(_amount);
tokenWantAmounts[msg.sender] = 0;
tokenStrategyAmounts[msg.sender] = 0;
}
/**
* Send token want to msg.sender.
*/
function _sendTokenWant(uint256 _amount) internal {
iTokenWant.safeTransfer(msg.sender, _amount);
}
/**
* Send token reward to users,
*/
function _sendReward(uint256 _rewardLeft, uint256 _rewardWithRate) internal {
if (_rewardLeft >= _rewardWithRate) {
IERC20(tokenReward).safeTransfer(msg.sender, _rewardWithRate);
} else {
IERC20(tokenReward).safeTransfer(msg.sender, _rewardLeft);
}
}
/**
* Rebalance plug every rebalance period.
*/
function rebalancePlug() external override whenNotPaused() {
_rebalancePlug();
}
/**
* Internsal function for rebalance.
*/
function _rebalancePlug() internal {
require(lastRebalanceTs.add(rebalancePeriod) < block.timestamp);
lastRebalanceTs = block.timestamp;
uint256 twPlug = iTokenWant.balanceOf(address(this));
uint256 twInStrategy;
uint256 teInStrategy;
uint256 teByPlug;
// reinvest token want to strategy
if (plugLevel == 0) {
_rebalanceAtLevel0(twPlug);
} else {
twInStrategy = _getTokenWantInS();
teInStrategy = twInStrategy.sub(twInStrategyLastRebalance);
teByPlug = twPlug.add(teInStrategy);
if (plugLevel == 1) {
_rebalanceAtLevel1Plus(teByPlug.div(2));
} else {
_rebalanceAtLevel1Plus(teByPlug.div(3));
}
}
twInStrategyLastRebalance = _getTokenWantInS();
}
/**
* Rebalance plug at level 0
* Mint all tokens want owned by plug to idle pool
*/
function _rebalanceAtLevel0(uint256 _amount) internal {
uint256 mintedTokens = strategy.mintIdleToken(_amount, true, address(0));
tokenStrategyAmounts[address(this)] = tokenStrategyAmounts[address(this)].add(mintedTokens);
}
/**
* Rebalance plug at level1+.
* level1 -> 50% remain into plug and 50% send to reward1
* level2+ -> 33.3% to plug 33.3% to reward1 and 33.3% to reward2
*/
function _rebalanceAtLevel1Plus(uint256 _amount) internal {
uint256 plugAmount = _getPlugBalance(tokenWant);
uint256 amountToSend = _amount;
if (plugLevel > 1) {
amountToSend = amountToSend.mul(2);
}
if (plugAmount < amountToSend) {
uint256 amountToRetrieveFromS = amountToSend.sub(plugAmount);
uint256 amountToRedeem = amountToRetrieveFromS.div(_getRedeemPrice()).mul(ONE_18);
strategy.redeemIdleToken(amountToRedeem);
tokenStrategyAmounts[address(this)] = tokenStrategyAmounts[address(this)].sub(amountToRedeem);
}
// send to reward out 1
_transferToOutside(tokenWant, rewardOutOne, _amount);
if (plugLevel > 1) {
_transferToOutside(tokenWant, rewardOutTwo, _amount);
}
//send all remain token want from plug to idle strategy
uint256 balanceLeft = plugAmount.sub(amountToSend);
if (balanceLeft > 0) {
_rebalanceAtLevel0(balanceLeft);
}
}
/**
* Upgrade plug to the next level.
*/
function upgradePlug(uint256 _nextLevelCap) external override onlyOwner {
require(_nextLevelCap > currentLevelCap && plugTotalAmount() > currentLevelCap);
require(rewardOutOne != address(0));
if (plugLevel >= 1) {
require(rewardOutTwo != address(0));
require(plugHelper != address(0));
}
plugLevel = plugLevel + 1;
currentLevelCap = _nextLevelCap;
}
/**
* Redeem all token owned by plug from idle strategy.
*/
function safePlugExitStrategy(uint256 _amount) external onlyOwner {
strategy.redeemIdleToken(_amount);
tokenStrategyAmounts[address(this)] = tokenStrategyAmounts[address(this)].sub(_amount);
twInStrategyLastRebalance = _getTokenWantInS();
}
/**
* Transfer token want to factory.
*/
function transferToHelper() external onlyOwner {
require(plugHelper != address(0));
uint256 amount = iTokenWant.balanceOf(address(this));
_transferToOutside(tokenWant, plugHelper, amount);
}
/**
* Transfer token different than token strategy to external allowed address (ex IDLE, COMP, ecc).
*/
function transferToRewardOut(address _token, address _rewardOut) external onlyOwner {
require(_token != address(0) && _rewardOut != address(0));
require(_rewardOut == rewardOutOne || _rewardOut == rewardOutTwo);
// it prevents to tranfer idle tokens outside
require(_token != tokenStrategy);
uint256 amount = IERC20(_token).balanceOf(address(this));
_transferToOutside(_token, _rewardOut, amount);
}
/**
* Transfer any token to external address.
*/
function _transferToOutside(address _token, address _outside, uint256 _amount) internal {
IERC20(_token).safeTransfer(_outside, _amount);
}
/**
* Approve token to spender.
*/
function safeTokenApprore(address _token, address _spender, uint256 _amount) external onlyOwner {
IERC20(_token).approve(_spender, _amount);
}
/**
* Set the current level cap.
*/
function setCurrentLevelCap(uint256 _newCap) external onlyOwner {
require(_newCap > plugTotalAmount());
currentLevelCap = _newCap;
}
/**
* Set a new token reward.
*/
function setTokenReward(address _tokenReward) external onlyOwner {
tokenReward = _tokenReward;
}
/**
* Set the new reward rate in decimals (18).
*/
function setRewardRate(uint256 _rate) external onlyOwner {
rewardRate = _rate;
}
/**
* Set the first reward pool address.
*/
function setRewardOutOne(address _reward) external onlyOwner {
rewardOutOne = _reward;
}
/**
* Set the second reward pool address.
*/
function setRewardOutTwo(address _reward) external onlyOwner {
rewardOutTwo = _reward;
}
/**
* Set the plug helper address.
*/
function setPlugHelper(address _plugHelper) external onlyOwner {
plugHelper = _plugHelper;
}
/**
* Set the new rebalance period duration.
*/
function setRebalancePeriod(uint256 _newPeriod) external onlyOwner {
// at least 12 hours (60 * 60 * 12)
require(_newPeriod >= 43200);
rebalancePeriod = _newPeriod;
}
/**
* Set the new plug cap for token want to store in it.
*/
function setPlugUsersLimit(uint256 _newLimit) external onlyOwner {
require(_newLimit > plugLimit);
plugLimit = _newLimit;
}
/**
* Get the current reedem price.
* @notice function helper for retrieving the idle token price counting fees, developed by @emilianobonassi
* https://github.com/emilianobonassi/idle-token-helper
*/
function _getRedeemPrice() view internal returns (uint256 redeemPrice) {
uint256 userAvgPrice = strategy.userAvgPrices(address(this));
uint256 currentPrice = strategy.tokenPrice();
// When no deposits userAvgPrice is 0 equiv currentPrice
// and in the case of issues
if (userAvgPrice == 0 || currentPrice < userAvgPrice) {
redeemPrice = currentPrice;
} else {
uint256 fee = strategy.fee();
redeemPrice = ((currentPrice.mul(FULL_ALLOC))
.sub(
fee.mul(
currentPrice.sub(userAvgPrice)
)
)).div(FULL_ALLOC);
}
return redeemPrice;
}
/**
* Get the plug balance of a token.
*/
function _getPlugBalance(address _token) internal view returns(uint256) {
return IERC20(_token).balanceOf(address(this));
}
/**
* Get the plug balance of token want into idle strategy.
*/
function _getTokenWantInS() internal view returns (uint256) {
uint256 tokenPrice = _getRedeemPrice();
return tokenStrategyAmounts[address(this)].mul(tokenPrice).div(ONE_18);
}
/**
* Get the plug total amount between the ineer and the amount store into idle.
*/
function plugTotalAmount() public view returns(uint256) {
uint256 tokenWantInStrategy = _getTokenWantInS();
return iTokenWant.balanceOf(address(this)).add(tokenWantInStrategy);
}
}
|
Redeem all token owned by plug from idle strategy./
|
function safePlugExitStrategy(uint256 _amount) external onlyOwner {
strategy.redeemIdleToken(_amount);
tokenStrategyAmounts[address(this)] = tokenStrategyAmounts[address(this)].sub(_amount);
twInStrategyLastRebalance = _getTokenWantInS();
}
| 6,179,141 |
pragma solidity 0.4.24;
contract ERC20Token {
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, uint256 tokens) public returns (bool success);
function approve(address spender, uint256 tokens) public returns (bool success);
function transferFrom(address from, address to, uint256 tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
pragma solidity 0.4.24;
import "./SafeMath.sol";
import './StandardToken.sol';
import './Ownable.sol';
contract FLXCToken is StandardToken, Ownable {
using SafeMath for uint256;
string public constant symbol = "FLXC";
string public constant name = "FLXC Token";
uint8 public constant decimals = 18;
// Total Number of tokens ever goint to be minted. 10 BILLION FLXC tokens.
uint256 private constant minting_capped_amount = 10000000000 * 10 ** uint256(decimals);
// 10% of inital supply.
uint256 constant vesting_amount = 100000000 * 10 ** uint256(decimals);
uint256 private initialSupply = minting_capped_amount;
address public vestingAddress;
/** @dev to cap the total number of tokens that will ever be newly minted
* owner has to stop the minting by setting this variable to true.
*/
bool public mintingFinished = false;
/** @dev Miniting Essentials functions as per OpenZeppelin standards
*/
modifier canMint() {
require(!mintingFinished);
_;
}
modifier hasMintPermission() {
require(msg.sender == owner);
_;
}
/** @dev to prevent malicious use of FLXC tokens and to comply with Anti
* Money laundering regulations FLXC tokens can be frozen.
*/
mapping (address => bool) public frozenAccount;
/** @dev This generates a public event on the blockchain that will notify clients
*/
event FrozenFunds(address target, bool frozen);
event Mint(address indexed to, uint256 amount);
event MintFinished();
event Burn(address indexed burner, uint256 value);
constructor() public {
_totalSupply = minting_capped_amount;
owner = msg.sender;
balances[owner] = _totalSupply;
emit Transfer(address(0), owner, balances[owner]);
}
/* Do not accept ETH */
function() public payable {
revert();
}
function setVestingAddress(address _vestingAddress) external onlyOwner {
vestingAddress = _vestingAddress;
assert(approve(vestingAddress, vesting_amount));
}
function getVestingAmount() public view returns(uint256) {
return vesting_amount;
}
/** @dev Transfer possible only after ICO ends and Frozen accounts
* wont be able to transfer funds to other any other account and viz.
* @notice added safeTransfer functionality
*/
function transfer(address _to, uint256 _value) public returns(bool) {
require(!frozenAccount[msg.sender]);
require(!frozenAccount[_to]);
require(super.transfer(_to, _value));
return true;
}
/** @dev Only owner's tokens can be transferred before Crowdsale ends.
* beacuse the inital supply of FLXC is allocated to owners acc and later
* distributed to various subcontracts.
* @notice added safeTransferFrom functionality
*/
function transferFrom(address _from, address _to, uint256 _value) public returns(bool) {
require(!frozenAccount[_from]);
require(!frozenAccount[_to]);
require(!frozenAccount[msg.sender]);
require(super.transferFrom(_from, _to, _value));
return true;
}
/** @notice added safeApprove functionality
*/
function approve(address spender, uint256 tokens) public returns (bool){
require(super.approve(spender, tokens));
return true;
}
/** @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens
* @param target Address to be frozen
* @param freeze either to freeze it or not
*/
function freezeAccount(address target, bool freeze) public onlyOwner {
require(frozenAccount[target] != freeze);
frozenAccount[target] = freeze;
emit FrozenFunds(target, freeze);
}
/** @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) public hasMintPermission canMint returns (bool) {
require(_totalSupply.add(_amount) <= minting_capped_amount);
_totalSupply = _totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
/** @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() public onlyOwner canMint returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
/** @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);
}
}
pragma solidity 0.4.24;
import './StandardTokenVesting.sol';
import './Ownable.sol';
/** @notice Factory is a software design pattern for creating instances of a class.
* Using this pattern simplifies creating new vesting contracts and saves
* transaction costs ("gas"). Instead of deploying a new TokenVesting contract
* for each team member, we deploy a single instance of TokenVestingFactory
* that ensures the creation of new token vesting contracts.
*/
contract FLXCTokenVestingFactory is Ownable {
mapping(address => StandardTokenVesting) vestingContractAddresses;
// The token being sold
FLXCToken public token;
event CreatedStandardVestingContract(StandardTokenVesting vesting);
constructor(address _token) public {
require(_token != address(0));
owner = msg.sender;
token = FLXCToken(_token);
}
/** @dev Deploy FLXCTokenVestingFactory, and use it to create vesting contracts
* for founders, advisors and developers. after creation transfer FLXC tokens
* to those addresses and vesting vaults will be initialised.
*/
// function create(address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable, uint256 noOfTokens) onlyOwner public returns(StandardTokenVesting) {
function create(address _beneficiary, uint256 _cliff, uint256 _duration, bool _revocable, uint256 noOfTokens) public onlyOwner returns(StandardTokenVesting) {
StandardTokenVesting vesting = new StandardTokenVesting(_beneficiary, now , _cliff , _duration, _revocable);
vesting.transferOwnership(msg.sender);
vestingContractAddresses[_beneficiary] = vesting;
emit CreatedStandardVestingContract(vesting);
assert(token.transferFrom(owner, vesting, noOfTokens));
return vesting;
}
function getVestingContractAddress(address _beneficiary) public view returns(address) {
require(_beneficiary != address(0));
require(vestingContractAddresses[_beneficiary] != address(0));
return vestingContractAddresses[_beneficiary];
}
function releasableAmount(address _beneficiary) public view returns(uint256) {
require(getVestingContractAddress( _beneficiary) != address(0));
return vestingContractAddresses[_beneficiary].releasableAmount(token);
}
function vestedAmount(address _beneficiary) public view returns(uint256) {
require(getVestingContractAddress(_beneficiary) != address(0));
return vestingContractAddresses[_beneficiary].vestedAmount(token);
}
function release(address _beneficiary) public returns(bool) {
require(getVestingContractAddress(_beneficiary) != address(0));
return vestingContractAddresses[_beneficiary].release(token);
}
}
pragma solidity 0.4.24;
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
pragma solidity 0.4.24;
import "./Ownable.sol";
/* Pausable contract */
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();
}
}
pragma solidity 0.4.24;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
pragma solidity 0.4.24;
import './ERC20Token.sol';
import './SafeMath.sol';
contract StandardToken is ERC20Token {
using SafeMath for uint256;
// Global variable to store total number of tokens passed from FLXCToken.sol
uint256 _totalSupply;
mapping(address => uint256) balances;
mapping(address => mapping(address => uint256)) allowed;
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function balanceOf(address tokenOwner) public view returns (uint256){
return balances[tokenOwner];
}
function transfer(address to, uint256 tokens) public returns (bool){
require(to != address(0));
require(tokens > 0 && tokens <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
// Transfer tokens from one address to another
function transferFrom(address from, address to, uint256 tokens) public returns (bool success){
require(to != address(0));
require(tokens > 0 && tokens <= balances[from]);
require(tokens <= allowed[from][msg.sender]);
balances[from] = balances[from].sub(tokens);
balances[to] = balances[to].add(tokens);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);
emit Transfer(from, to, tokens);
return true;
}
// Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
function approve(address spender, uint256 tokens) public returns (bool success){
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// Function to check the amount of tokens that an owner allowed to a spender.
function allowance(address tokenOwner, address spender) public view returns (uint256 remaining){
return allowed[tokenOwner][spender];
}
// 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)
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;
}
// 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)
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;
}
}
pragma solidity 0.4.24;
import "./FLXCToken.sol";
import "./SafeMath.sol";
import "./Ownable.sol";
/** @title StandardTokenVesting
* @dev A token holder contract that can release its token balance gradually like a
* typical vesting scheme, with a cliff and vesting period. Optionally revocable by the owner.
*/
contract StandardTokenVesting is Ownable {
using SafeMath for uint256;
event Released(uint256 amount);
event Revoked();
// beneficiary of tokens after they are released
address public beneficiary;
uint256 public cliff;
uint256 public start;
uint256 public duration;
bool public revocable;
mapping (address => uint256) public released;
mapping (address => bool) public revoked;
/** @dev Creates a vesting contract that vests its balance of any ERC20 token to the
* _beneficiary, gradually in a linear fashion until _start + _duration. By then all
* of the balance will have vested.
* @param _beneficiary address of the beneficiary to whom vested tokens are transferred
* @param _cliff duration in seconds of the cliff in which tokens will begin to vest
* @param _start the time (as Unix time) at which point vesting starts
* @param _duration duration in seconds of the period in which the tokens will vest
* @param _revocable whether the vesting is revocable or not
*/
constructor(address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable) public {
require(_beneficiary != address(0));
require(_cliff <= _duration);
beneficiary = _beneficiary;
revocable = _revocable;
duration = _duration;
owner = msg.sender;
cliff = _start.add(_cliff);
start = _start;
}
/** @notice Transfers vested tokens to beneficiary.
* @param token ERC20 token which is being vested
*/
function release(FLXCToken token) public returns (bool){
uint256 unreleased = releasableAmount(token);
require(unreleased > 0);
released[token] = released[token].add(unreleased);
token.transfer(beneficiary, unreleased);
emit Released(unreleased);
return true;
}
/** @notice Allows the owner to revoke the vesting. Tokens already vested
* remain in the contract, the rest are returned to the owner.
* @param token ERC20 token which is being vested
*/
function revoke(FLXCToken token) public onlyOwner returns(bool) {
require(revocable);
require(!revoked[token]);
uint256 balance = token.balanceOf(this);
uint256 unreleased = releasableAmount(token);
uint256 refund = balance.sub(unreleased);
revoked[token] = true;
token.transfer(owner, refund);
emit Revoked();
return true;
}
/** @dev Calculates the amount that has already vested but hasn't been released yet.
* @param token ERC20 token which is being vested
*/
function releasableAmount(FLXCToken token) public view returns (uint256) {
return vestedAmount(token).sub(released[token]);
}
/** @dev Calculates the amount that has already vested.
* @param token FLXC Token which is being vested
*/
function vestedAmount(FLXCToken token) public view returns (uint256) {
uint256 currentBalance = token.balanceOf(this);
uint256 totalBalance = currentBalance.add(released[token]);
if (block.timestamp < cliff) {
return 0;
} else if (block.timestamp >= start.add(duration) || revoked[token]) {
return totalBalance;
} else {
return totalBalance.mul(block.timestamp.sub(start)).div(duration);
}
}
}
pragma solidity 0.4.24;
contract ERC20Token {
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, uint256 tokens) public returns (bool success);
function approve(address spender, uint256 tokens) public returns (bool success);
function transferFrom(address from, address to, uint256 tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
pragma solidity 0.4.24;
import "./SafeMath.sol";
import './StandardToken.sol';
import './Ownable.sol';
contract FLXCToken is StandardToken, Ownable {
using SafeMath for uint256;
string public constant symbol = "FLXC";
string public constant name = "FLXC Token";
uint8 public constant decimals = 18;
// Total Number of tokens ever goint to be minted. 10 BILLION FLXC tokens.
uint256 private constant minting_capped_amount = 10000000000 * 10 ** uint256(decimals);
// 10% of inital supply.
uint256 constant vesting_amount = 100000000 * 10 ** uint256(decimals);
uint256 private initialSupply = minting_capped_amount;
address public vestingAddress;
/** @dev to cap the total number of tokens that will ever be newly minted
* owner has to stop the minting by setting this variable to true.
*/
bool public mintingFinished = false;
/** @dev Miniting Essentials functions as per OpenZeppelin standards
*/
modifier canMint() {
require(!mintingFinished);
_;
}
modifier hasMintPermission() {
require(msg.sender == owner);
_;
}
/** @dev to prevent malicious use of FLXC tokens and to comply with Anti
* Money laundering regulations FLXC tokens can be frozen.
*/
mapping (address => bool) public frozenAccount;
/** @dev This generates a public event on the blockchain that will notify clients
*/
event FrozenFunds(address target, bool frozen);
event Mint(address indexed to, uint256 amount);
event MintFinished();
event Burn(address indexed burner, uint256 value);
constructor() public {
_totalSupply = minting_capped_amount;
owner = msg.sender;
balances[owner] = _totalSupply;
emit Transfer(address(0), owner, balances[owner]);
}
/* Do not accept ETH */
function() public payable {
revert();
}
function setVestingAddress(address _vestingAddress) external onlyOwner {
vestingAddress = _vestingAddress;
assert(approve(vestingAddress, vesting_amount));
}
function getVestingAmount() public view returns(uint256) {
return vesting_amount;
}
/** @dev Transfer possible only after ICO ends and Frozen accounts
* wont be able to transfer funds to other any other account and viz.
* @notice added safeTransfer functionality
*/
function transfer(address _to, uint256 _value) public returns(bool) {
require(!frozenAccount[msg.sender]);
require(!frozenAccount[_to]);
require(super.transfer(_to, _value));
return true;
}
/** @dev Only owner's tokens can be transferred before Crowdsale ends.
* beacuse the inital supply of FLXC is allocated to owners acc and later
* distributed to various subcontracts.
* @notice added safeTransferFrom functionality
*/
function transferFrom(address _from, address _to, uint256 _value) public returns(bool) {
require(!frozenAccount[_from]);
require(!frozenAccount[_to]);
require(!frozenAccount[msg.sender]);
require(super.transferFrom(_from, _to, _value));
return true;
}
/** @notice added safeApprove functionality
*/
function approve(address spender, uint256 tokens) public returns (bool){
require(super.approve(spender, tokens));
return true;
}
/** @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens
* @param target Address to be frozen
* @param freeze either to freeze it or not
*/
function freezeAccount(address target, bool freeze) public onlyOwner {
require(frozenAccount[target] != freeze);
frozenAccount[target] = freeze;
emit FrozenFunds(target, freeze);
}
/** @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) public hasMintPermission canMint returns (bool) {
require(_totalSupply.add(_amount) <= minting_capped_amount);
_totalSupply = _totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
/** @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() public onlyOwner canMint returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
/** @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);
}
}
pragma solidity 0.4.24;
import './StandardTokenVesting.sol';
import './Ownable.sol';
/** @notice Factory is a software design pattern for creating instances of a class.
* Using this pattern simplifies creating new vesting contracts and saves
* transaction costs ("gas"). Instead of deploying a new TokenVesting contract
* for each team member, we deploy a single instance of TokenVestingFactory
* that ensures the creation of new token vesting contracts.
*/
contract FLXCTokenVestingFactory is Ownable {
mapping(address => StandardTokenVesting) vestingContractAddresses;
// The token being sold
FLXCToken public token;
event CreatedStandardVestingContract(StandardTokenVesting vesting);
constructor(address _token) public {
require(_token != address(0));
owner = msg.sender;
token = FLXCToken(_token);
}
/** @dev Deploy FLXCTokenVestingFactory, and use it to create vesting contracts
* for founders, advisors and developers. after creation transfer FLXC tokens
* to those addresses and vesting vaults will be initialised.
*/
// function create(address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable, uint256 noOfTokens) onlyOwner public returns(StandardTokenVesting) {
function create(address _beneficiary, uint256 _cliff, uint256 _duration, bool _revocable, uint256 noOfTokens) public onlyOwner returns(StandardTokenVesting) {
StandardTokenVesting vesting = new StandardTokenVesting(_beneficiary, now , _cliff , _duration, _revocable);
vesting.transferOwnership(msg.sender);
vestingContractAddresses[_beneficiary] = vesting;
emit CreatedStandardVestingContract(vesting);
assert(token.transferFrom(owner, vesting, noOfTokens));
return vesting;
}
function getVestingContractAddress(address _beneficiary) public view returns(address) {
require(_beneficiary != address(0));
require(vestingContractAddresses[_beneficiary] != address(0));
return vestingContractAddresses[_beneficiary];
}
function releasableAmount(address _beneficiary) public view returns(uint256) {
require(getVestingContractAddress( _beneficiary) != address(0));
return vestingContractAddresses[_beneficiary].releasableAmount(token);
}
function vestedAmount(address _beneficiary) public view returns(uint256) {
require(getVestingContractAddress(_beneficiary) != address(0));
return vestingContractAddresses[_beneficiary].vestedAmount(token);
}
function release(address _beneficiary) public returns(bool) {
require(getVestingContractAddress(_beneficiary) != address(0));
return vestingContractAddresses[_beneficiary].release(token);
}
}
pragma solidity 0.4.24;
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
pragma solidity 0.4.24;
import "./Ownable.sol";
/* Pausable contract */
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();
}
}
pragma solidity 0.4.24;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
pragma solidity 0.4.24;
import './ERC20Token.sol';
import './SafeMath.sol';
contract StandardToken is ERC20Token {
using SafeMath for uint256;
// Global variable to store total number of tokens passed from FLXCToken.sol
uint256 _totalSupply;
mapping(address => uint256) balances;
mapping(address => mapping(address => uint256)) allowed;
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function balanceOf(address tokenOwner) public view returns (uint256){
return balances[tokenOwner];
}
function transfer(address to, uint256 tokens) public returns (bool){
require(to != address(0));
require(tokens > 0 && tokens <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
// Transfer tokens from one address to another
function transferFrom(address from, address to, uint256 tokens) public returns (bool success){
require(to != address(0));
require(tokens > 0 && tokens <= balances[from]);
require(tokens <= allowed[from][msg.sender]);
balances[from] = balances[from].sub(tokens);
balances[to] = balances[to].add(tokens);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);
emit Transfer(from, to, tokens);
return true;
}
// Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
function approve(address spender, uint256 tokens) public returns (bool success){
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// Function to check the amount of tokens that an owner allowed to a spender.
function allowance(address tokenOwner, address spender) public view returns (uint256 remaining){
return allowed[tokenOwner][spender];
}
// 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)
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;
}
// 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)
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;
}
}
pragma solidity 0.4.24;
import "./FLXCToken.sol";
import "./SafeMath.sol";
import "./Ownable.sol";
/** @title StandardTokenVesting
* @dev A token holder contract that can release its token balance gradually like a
* typical vesting scheme, with a cliff and vesting period. Optionally revocable by the owner.
*/
contract StandardTokenVesting is Ownable {
using SafeMath for uint256;
event Released(uint256 amount);
event Revoked();
// beneficiary of tokens after they are released
address public beneficiary;
uint256 public cliff;
uint256 public start;
uint256 public duration;
bool public revocable;
mapping (address => uint256) public released;
mapping (address => bool) public revoked;
/** @dev Creates a vesting contract that vests its balance of any ERC20 token to the
* _beneficiary, gradually in a linear fashion until _start + _duration. By then all
* of the balance will have vested.
* @param _beneficiary address of the beneficiary to whom vested tokens are transferred
* @param _cliff duration in seconds of the cliff in which tokens will begin to vest
* @param _start the time (as Unix time) at which point vesting starts
* @param _duration duration in seconds of the period in which the tokens will vest
* @param _revocable whether the vesting is revocable or not
*/
constructor(address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable) public {
require(_beneficiary != address(0));
require(_cliff <= _duration);
beneficiary = _beneficiary;
revocable = _revocable;
duration = _duration;
owner = msg.sender;
cliff = _start.add(_cliff);
start = _start;
}
/** @notice Transfers vested tokens to beneficiary.
* @param token ERC20 token which is being vested
*/
function release(FLXCToken token) public returns (bool){
uint256 unreleased = releasableAmount(token);
require(unreleased > 0);
released[token] = released[token].add(unreleased);
token.transfer(beneficiary, unreleased);
emit Released(unreleased);
return true;
}
/** @notice Allows the owner to revoke the vesting. Tokens already vested
* remain in the contract, the rest are returned to the owner.
* @param token ERC20 token which is being vested
*/
function revoke(FLXCToken token) public onlyOwner returns(bool) {
require(revocable);
require(!revoked[token]);
uint256 balance = token.balanceOf(this);
uint256 unreleased = releasableAmount(token);
uint256 refund = balance.sub(unreleased);
revoked[token] = true;
token.transfer(owner, refund);
emit Revoked();
return true;
}
/** @dev Calculates the amount that has already vested but hasn't been released yet.
* @param token ERC20 token which is being vested
*/
function releasableAmount(FLXCToken token) public view returns (uint256) {
return vestedAmount(token).sub(released[token]);
}
/** @dev Calculates the amount that has already vested.
* @param token FLXC Token which is being vested
*/
function vestedAmount(FLXCToken token) public view returns (uint256) {
uint256 currentBalance = token.balanceOf(this);
uint256 totalBalance = currentBalance.add(released[token]);
if (block.timestamp < cliff) {
return 0;
} else if (block.timestamp >= start.add(duration) || revoked[token]) {
return totalBalance;
} else {
return totalBalance.mul(block.timestamp.sub(start)).div(duration);
}
}
}
pragma solidity 0.4.24;
contract ERC20Token {
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, uint256 tokens) public returns (bool success);
function approve(address spender, uint256 tokens) public returns (bool success);
function transferFrom(address from, address to, uint256 tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
pragma solidity 0.4.24;
import "./SafeMath.sol";
import './StandardToken.sol';
import './Ownable.sol';
contract FLXCToken is StandardToken, Ownable {
using SafeMath for uint256;
string public constant symbol = "FLXC";
string public constant name = "FLXC Token";
uint8 public constant decimals = 18;
// Total Number of tokens ever goint to be minted. 10 BILLION FLXC tokens.
uint256 private constant minting_capped_amount = 10000000000 * 10 ** uint256(decimals);
// 10% of inital supply.
uint256 constant vesting_amount = 100000000 * 10 ** uint256(decimals);
uint256 private initialSupply = minting_capped_amount;
address public vestingAddress;
/** @dev to cap the total number of tokens that will ever be newly minted
* owner has to stop the minting by setting this variable to true.
*/
bool public mintingFinished = false;
/** @dev Miniting Essentials functions as per OpenZeppelin standards
*/
modifier canMint() {
require(!mintingFinished);
_;
}
modifier hasMintPermission() {
require(msg.sender == owner);
_;
}
/** @dev to prevent malicious use of FLXC tokens and to comply with Anti
* Money laundering regulations FLXC tokens can be frozen.
*/
mapping (address => bool) public frozenAccount;
/** @dev This generates a public event on the blockchain that will notify clients
*/
event FrozenFunds(address target, bool frozen);
event Mint(address indexed to, uint256 amount);
event MintFinished();
event Burn(address indexed burner, uint256 value);
constructor() public {
_totalSupply = minting_capped_amount;
owner = msg.sender;
balances[owner] = _totalSupply;
emit Transfer(address(0), owner, balances[owner]);
}
/* Do not accept ETH */
function() public payable {
revert();
}
function setVestingAddress(address _vestingAddress) external onlyOwner {
vestingAddress = _vestingAddress;
assert(approve(vestingAddress, vesting_amount));
}
function getVestingAmount() public view returns(uint256) {
return vesting_amount;
}
/** @dev Transfer possible only after ICO ends and Frozen accounts
* wont be able to transfer funds to other any other account and viz.
* @notice added safeTransfer functionality
*/
function transfer(address _to, uint256 _value) public returns(bool) {
require(!frozenAccount[msg.sender]);
require(!frozenAccount[_to]);
require(super.transfer(_to, _value));
return true;
}
/** @dev Only owner's tokens can be transferred before Crowdsale ends.
* beacuse the inital supply of FLXC is allocated to owners acc and later
* distributed to various subcontracts.
* @notice added safeTransferFrom functionality
*/
function transferFrom(address _from, address _to, uint256 _value) public returns(bool) {
require(!frozenAccount[_from]);
require(!frozenAccount[_to]);
require(!frozenAccount[msg.sender]);
require(super.transferFrom(_from, _to, _value));
return true;
}
/** @notice added safeApprove functionality
*/
function approve(address spender, uint256 tokens) public returns (bool){
require(super.approve(spender, tokens));
return true;
}
/** @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens
* @param target Address to be frozen
* @param freeze either to freeze it or not
*/
function freezeAccount(address target, bool freeze) public onlyOwner {
require(frozenAccount[target] != freeze);
frozenAccount[target] = freeze;
emit FrozenFunds(target, freeze);
}
/** @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) public hasMintPermission canMint returns (bool) {
require(_totalSupply.add(_amount) <= minting_capped_amount);
_totalSupply = _totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
/** @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() public onlyOwner canMint returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
/** @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);
}
}
pragma solidity 0.4.24;
import './StandardTokenVesting.sol';
import './Ownable.sol';
/** @notice Factory is a software design pattern for creating instances of a class.
* Using this pattern simplifies creating new vesting contracts and saves
* transaction costs ("gas"). Instead of deploying a new TokenVesting contract
* for each team member, we deploy a single instance of TokenVestingFactory
* that ensures the creation of new token vesting contracts.
*/
contract FLXCTokenVestingFactory is Ownable {
mapping(address => StandardTokenVesting) vestingContractAddresses;
// The token being sold
FLXCToken public token;
event CreatedStandardVestingContract(StandardTokenVesting vesting);
constructor(address _token) public {
require(_token != address(0));
owner = msg.sender;
token = FLXCToken(_token);
}
/** @dev Deploy FLXCTokenVestingFactory, and use it to create vesting contracts
* for founders, advisors and developers. after creation transfer FLXC tokens
* to those addresses and vesting vaults will be initialised.
*/
// function create(address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable, uint256 noOfTokens) onlyOwner public returns(StandardTokenVesting) {
function create(address _beneficiary, uint256 _cliff, uint256 _duration, bool _revocable, uint256 noOfTokens) public onlyOwner returns(StandardTokenVesting) {
StandardTokenVesting vesting = new StandardTokenVesting(_beneficiary, now , _cliff , _duration, _revocable);
vesting.transferOwnership(msg.sender);
vestingContractAddresses[_beneficiary] = vesting;
emit CreatedStandardVestingContract(vesting);
assert(token.transferFrom(owner, vesting, noOfTokens));
return vesting;
}
function getVestingContractAddress(address _beneficiary) public view returns(address) {
require(_beneficiary != address(0));
require(vestingContractAddresses[_beneficiary] != address(0));
return vestingContractAddresses[_beneficiary];
}
function releasableAmount(address _beneficiary) public view returns(uint256) {
require(getVestingContractAddress( _beneficiary) != address(0));
return vestingContractAddresses[_beneficiary].releasableAmount(token);
}
function vestedAmount(address _beneficiary) public view returns(uint256) {
require(getVestingContractAddress(_beneficiary) != address(0));
return vestingContractAddresses[_beneficiary].vestedAmount(token);
}
function release(address _beneficiary) public returns(bool) {
require(getVestingContractAddress(_beneficiary) != address(0));
return vestingContractAddresses[_beneficiary].release(token);
}
}
pragma solidity 0.4.24;
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
pragma solidity 0.4.24;
import "./Ownable.sol";
/* Pausable contract */
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();
}
}
pragma solidity 0.4.24;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
pragma solidity 0.4.24;
import './ERC20Token.sol';
import './SafeMath.sol';
contract StandardToken is ERC20Token {
using SafeMath for uint256;
// Global variable to store total number of tokens passed from FLXCToken.sol
uint256 _totalSupply;
mapping(address => uint256) balances;
mapping(address => mapping(address => uint256)) allowed;
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function balanceOf(address tokenOwner) public view returns (uint256){
return balances[tokenOwner];
}
function transfer(address to, uint256 tokens) public returns (bool){
require(to != address(0));
require(tokens > 0 && tokens <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
// Transfer tokens from one address to another
function transferFrom(address from, address to, uint256 tokens) public returns (bool success){
require(to != address(0));
require(tokens > 0 && tokens <= balances[from]);
require(tokens <= allowed[from][msg.sender]);
balances[from] = balances[from].sub(tokens);
balances[to] = balances[to].add(tokens);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);
emit Transfer(from, to, tokens);
return true;
}
// Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
function approve(address spender, uint256 tokens) public returns (bool success){
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// Function to check the amount of tokens that an owner allowed to a spender.
function allowance(address tokenOwner, address spender) public view returns (uint256 remaining){
return allowed[tokenOwner][spender];
}
// 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)
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;
}
// 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)
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;
}
}
pragma solidity 0.4.24;
import "./FLXCToken.sol";
import "./SafeMath.sol";
import "./Ownable.sol";
/** @title StandardTokenVesting
* @dev A token holder contract that can release its token balance gradually like a
* typical vesting scheme, with a cliff and vesting period. Optionally revocable by the owner.
*/
contract StandardTokenVesting is Ownable {
using SafeMath for uint256;
event Released(uint256 amount);
event Revoked();
// beneficiary of tokens after they are released
address public beneficiary;
uint256 public cliff;
uint256 public start;
uint256 public duration;
bool public revocable;
mapping (address => uint256) public released;
mapping (address => bool) public revoked;
/** @dev Creates a vesting contract that vests its balance of any ERC20 token to the
* _beneficiary, gradually in a linear fashion until _start + _duration. By then all
* of the balance will have vested.
* @param _beneficiary address of the beneficiary to whom vested tokens are transferred
* @param _cliff duration in seconds of the cliff in which tokens will begin to vest
* @param _start the time (as Unix time) at which point vesting starts
* @param _duration duration in seconds of the period in which the tokens will vest
* @param _revocable whether the vesting is revocable or not
*/
constructor(address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable) public {
require(_beneficiary != address(0));
require(_cliff <= _duration);
beneficiary = _beneficiary;
revocable = _revocable;
duration = _duration;
owner = msg.sender;
cliff = _start.add(_cliff);
start = _start;
}
/** @notice Transfers vested tokens to beneficiary.
* @param token ERC20 token which is being vested
*/
function release(FLXCToken token) public returns (bool){
uint256 unreleased = releasableAmount(token);
require(unreleased > 0);
released[token] = released[token].add(unreleased);
token.transfer(beneficiary, unreleased);
emit Released(unreleased);
return true;
}
/** @notice Allows the owner to revoke the vesting. Tokens already vested
* remain in the contract, the rest are returned to the owner.
* @param token ERC20 token which is being vested
*/
function revoke(FLXCToken token) public onlyOwner returns(bool) {
require(revocable);
require(!revoked[token]);
uint256 balance = token.balanceOf(this);
uint256 unreleased = releasableAmount(token);
uint256 refund = balance.sub(unreleased);
revoked[token] = true;
token.transfer(owner, refund);
emit Revoked();
return true;
}
/** @dev Calculates the amount that has already vested but hasn't been released yet.
* @param token ERC20 token which is being vested
*/
function releasableAmount(FLXCToken token) public view returns (uint256) {
return vestedAmount(token).sub(released[token]);
}
/** @dev Calculates the amount that has already vested.
* @param token FLXC Token which is being vested
*/
function vestedAmount(FLXCToken token) public view returns (uint256) {
uint256 currentBalance = token.balanceOf(this);
uint256 totalBalance = currentBalance.add(released[token]);
if (block.timestamp < cliff) {
return 0;
} else if (block.timestamp >= start.add(duration) || revoked[token]) {
return totalBalance;
} else {
return totalBalance.mul(block.timestamp.sub(start)).div(duration);
}
}
}
|
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
|
function _burn(address _who, uint256 _value) internal {
require(_value <= balances[_who]);
balances[_who] = balances[_who].sub(_value);
_totalSupply = _totalSupply.sub(_value);
emit Burn(_who, _value);
emit Transfer(_who, address(0), _value);
}
| 5,355,402 |
pragma solidity 0.4.21;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
/// Total amount of tokens
uint256 public totalSupply;
function balanceOf(address _owner) public view returns (uint256 balance);
function transfer(address _to, uint256 _amount) public returns (bool success);
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 remaining);
function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success);
function approve(address _spender, uint256 _amount) public returns (bool success);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
//balance in each address account
mapping(address => uint256) balances;
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _amount The amount to be transferred.
*/
function transfer(address _to, uint256 _amount) public returns (bool success) {
require(_to != address(0));
require(balances[msg.sender] >= _amount && _amount > 0
&& balances[_to].add(_amount) > balances[_to]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_amount);
balances[_to] = balances[_to].add(_amount);
emit Transfer(msg.sender, _to, _amount);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
*/
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 _amount uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success) {
require(_to != address(0));
require(balances[_from] >= _amount);
require(allowed[_from][msg.sender] >= _amount);
require(_amount > 0 && balances[_to].add(_amount) > balances[_to]);
balances[_from] = balances[_from].sub(_amount);
balances[_to] = balances[_to].add(_amount);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount);
emit Transfer(_from, _to, _amount);
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 _amount The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _amount) public returns (bool success) {
allowed[msg.sender][_spender] = _amount;
emit Approval(msg.sender, _spender, _amount);
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 remaining) {
return allowed[_owner][_spender];
}
}
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract BurnableToken is StandardToken, Ownable {
//this will contain a list of addresses allowed to burn their tokens
mapping(address=>bool)allowedBurners;
event Burn(address indexed burner, uint256 value);
event BurnerAdded(address indexed burner);
event BurnerRemoved(address indexed burner);
//check whether the burner is eligible burner
modifier isBurner(address _burner){
require(allowedBurners[_burner]);
_;
}
/**
*@dev Method to add eligible addresses in the list of burners. Since we need to burn all tokens left with the sales contract after the sale has ended. The sales contract should
* be an eligible burner. The owner has to add the sales address in the eligible burner list.
* @param _burner Address of the eligible burner
*/
function addEligibleBurner(address _burner)public onlyOwner {
require(_burner != address(0));
allowedBurners[_burner] = true;
emit BurnerAdded(_burner);
}
/**
*@dev Method to remove addresses from the list of burners
* @param _burner Address of the eligible burner to be removed
*/
function removeEligibleBurner(address _burner)public onlyOwner isBurner(_burner) {
allowedBurners[_burner] = false;
emit BurnerRemoved(_burner);
}
/**
* @dev Burns all tokens of the eligible burner
*/
function burnAllTokens() public isBurner(msg.sender) {
require(balances[msg.sender]>0);
uint256 value = balances[msg.sender];
totalSupply = totalSupply.sub(value);
balances[msg.sender] = 0;
emit Burn(msg.sender, value);
}
}
/**
* @title DRONE Token
* @dev Token representing DRONE.
*/
contract DroneToken is BurnableToken {
string public name ;
string public symbol ;
uint8 public decimals = 0 ;
/**
*@dev users sending ether to this contract will be reverted. Any ether sent to the contract will be sent back to the caller
*/
function ()public payable {
revert();
}
/**
* @dev Constructor function to initialize the initial supply of token to the creator of the contract
* @param initialSupply The initial supply of tokens which will be fixed through out
* @param tokenName The name of the token
* @param tokenSymbol The symboll of the token
*/
function DroneToken(
uint256 initialSupply,
string tokenName,
string tokenSymbol
) public {
totalSupply = initialSupply.mul( 10 ** uint256(decimals)); //Update total supply with the decimal amount
name = tokenName;
symbol = tokenSymbol;
balances[msg.sender] = totalSupply;
//Emitting transfer event since assigning all tokens to the creator also corresponds to the transfer of tokens to the creator
emit Transfer(address(0), msg.sender, totalSupply);
}
/**
*@dev helper method to get token details, name, symbol and totalSupply in one go
*/
function getTokenDetail() public view returns (string, string, uint256) {
return (name, symbol, totalSupply);
}
}
|
Constructor function to initialize the initial supply of token to the creator of the contract initialSupply The initial supply of tokens which will be fixed through out tokenName The name of the token tokenSymbol The symboll of the token/Emitting transfer event since assigning all tokens to the creator also corresponds to the transfer of tokens to the creator
|
function DroneToken(
uint256 initialSupply,
string tokenName,
string tokenSymbol
) public {
name = tokenName;
symbol = tokenSymbol;
balances[msg.sender] = totalSupply;
emit Transfer(address(0), msg.sender, totalSupply);
}
| 7,958,059 |
// solhint-disable
pragma solidity ^0.5.9;
/// @title Multisignature wallet - Allows multiple parties to agree on transactions before execution.
/// @author Stefan George - <[email protected]>
contract MultiSigWallet {
/*
* Events
*/
event Confirmation(address indexed sender, uint256 indexed transactionId);
event Revocation(address indexed sender, uint256 indexed transactionId);
event Submission(uint256 indexed transactionId);
event Execution(uint256 indexed transactionId);
event ExecutionFailure(uint256 indexed transactionId);
event Deposit(address indexed sender, uint256 value);
event OwnerAddition(address indexed owner);
event OwnerRemoval(address indexed owner);
event RequirementChange(uint256 required);
/*
* Constants
*/
uint256 constant public MAX_OWNER_COUNT = 50;
/*
* Storage
*/
mapping (uint256 => Transaction) public transactions;
mapping (uint256 => mapping (address => bool)) public confirmations;
mapping (address => bool) public isOwner;
address[] public owners;
uint256 public required;
uint256 public transactionCount;
struct Transaction {
address destination;
uint256 value;
bytes data;
bool executed;
}
/*
* Modifiers
*/
modifier onlyWallet() {
require(
msg.sender == address(this),
"ONLY_CALLABLE_BY_WALLET"
);
_;
}
modifier ownerDoesNotExist(address owner) {
require(
!isOwner[owner],
"OWNER_EXISTS"
);
_;
}
modifier ownerExists(address owner) {
require(
isOwner[owner],
"OWNER_DOESNT_EXIST"
);
_;
}
modifier transactionExists(uint256 transactionId) {
require(
transactions[transactionId].destination != address(0),
"TX_DOESNT_EXIST"
);
_;
}
modifier confirmed(uint256 transactionId, address owner) {
require(
confirmations[transactionId][owner],
"TX_NOT_CONFIRMED"
);
_;
}
modifier notConfirmed(uint256 transactionId, address owner) {
require(
!confirmations[transactionId][owner],
"TX_ALREADY_CONFIRMED"
);
_;
}
modifier notExecuted(uint256 transactionId) {
require(
!transactions[transactionId].executed,
"TX_ALREADY_EXECUTED"
);
_;
}
modifier notNull(address _address) {
require(
_address != address(0),
"NULL_ADDRESS"
);
_;
}
modifier validRequirement(uint256 ownerCount, uint256 _required) {
require(
ownerCount <= MAX_OWNER_COUNT
&& _required <= ownerCount
&& _required != 0
&& ownerCount != 0,
"INVALID_REQUIREMENTS"
);
_;
}
/// @dev Fallback function allows to deposit ether.
function()
external
payable
{
if (msg.value > 0) {
emit Deposit(msg.sender, msg.value);
}
}
/*
* Public functions
*/
/// @dev Contract constructor sets initial owners and required number of confirmations.
/// @param _owners List of initial owners.
/// @param _required Number of required confirmations.
constructor(
address[] memory _owners,
uint256 _required
)
public
validRequirement(_owners.length, _required)
{
for (uint256 i = 0; i < _owners.length; i++) {
require(
!isOwner[_owners[i]] && _owners[i] != address(0),
"DUPLICATE_OR_NULL_OWNER"
);
isOwner[_owners[i]] = true;
}
owners = _owners;
required = _required;
}
/// @dev Allows to add a new owner. Transaction has to be sent by wallet.
/// @param owner Address of new owner.
function addOwner(address owner)
public
onlyWallet
ownerDoesNotExist(owner)
notNull(owner)
validRequirement(owners.length + 1, required)
{
isOwner[owner] = true;
owners.push(owner);
emit OwnerAddition(owner);
}
/// @dev Allows to remove an owner. Transaction has to be sent by wallet.
/// @param owner Address of owner.
function removeOwner(address owner)
public
onlyWallet
ownerExists(owner)
{
isOwner[owner] = false;
for (uint256 i = 0; i < owners.length - 1; i++) {
if (owners[i] == owner) {
owners[i] = owners[owners.length - 1];
break;
}
}
owners.length -= 1;
if (required > owners.length) {
changeRequirement(owners.length);
}
emit OwnerRemoval(owner);
}
/// @dev Allows to replace an owner with a new owner. Transaction has to be sent by wallet.
/// @param owner Address of owner to be replaced.
/// @param newOwner Address of new owner.
function replaceOwner(address owner, address newOwner)
public
onlyWallet
ownerExists(owner)
ownerDoesNotExist(newOwner)
{
for (uint256 i = 0; i < owners.length; i++) {
if (owners[i] == owner) {
owners[i] = newOwner;
break;
}
}
isOwner[owner] = false;
isOwner[newOwner] = true;
emit OwnerRemoval(owner);
emit OwnerAddition(newOwner);
}
/// @dev Allows to change the number of required confirmations. Transaction has to be sent by wallet.
/// @param _required Number of required confirmations.
function changeRequirement(uint256 _required)
public
onlyWallet
validRequirement(owners.length, _required)
{
required = _required;
emit RequirementChange(_required);
}
/// @dev Allows an owner to submit and confirm a transaction.
/// @param destination Transaction target address.
/// @param value Transaction ether value.
/// @param data Transaction data payload.
/// @return Returns transaction ID.
function submitTransaction(address destination, uint256 value, bytes memory data)
public
returns (uint256 transactionId)
{
transactionId = _addTransaction(destination, value, data);
confirmTransaction(transactionId);
}
/// @dev Allows an owner to confirm a transaction.
/// @param transactionId Transaction ID.
function confirmTransaction(uint256 transactionId)
public
ownerExists(msg.sender)
transactionExists(transactionId)
notConfirmed(transactionId, msg.sender)
{
confirmations[transactionId][msg.sender] = true;
emit Confirmation(msg.sender, transactionId);
executeTransaction(transactionId);
}
/// @dev Allows an owner to revoke a confirmation for a transaction.
/// @param transactionId Transaction ID.
function revokeConfirmation(uint256 transactionId)
public
ownerExists(msg.sender)
confirmed(transactionId, msg.sender)
notExecuted(transactionId)
{
confirmations[transactionId][msg.sender] = false;
emit Revocation(msg.sender, transactionId);
}
/// @dev Allows anyone to execute a confirmed transaction.
/// @param transactionId Transaction ID.
function executeTransaction(uint256 transactionId)
public
ownerExists(msg.sender)
confirmed(transactionId, msg.sender)
notExecuted(transactionId)
{
if (isConfirmed(transactionId)) {
Transaction storage txn = transactions[transactionId];
txn.executed = true;
if (
_externalCall(
txn.destination,
txn.value,
txn.data.length,
txn.data
)
) {
emit Execution(transactionId);
} else {
emit ExecutionFailure(transactionId);
txn.executed = false;
}
}
}
// call has been separated into its own function in order to take advantage
// of the Solidity's code generator to produce a loop that copies tx.data into memory.
function _externalCall(
address destination,
uint256 value,
uint256 dataLength,
bytes memory data
)
internal
returns (bool)
{
bool result;
assembly {
let x := mload(0x40) // "Allocate" memory for output (0x40 is where "free memory" pointer is stored by convention)
let d := add(data, 32) // First 32 bytes are the padded length of data, so exclude that
result := call(
sub(gas, 34710), // 34710 is the value that solidity is currently emitting
// It includes callGas (700) + callVeryLow (3, to pay for SUB) + callValueTransferGas (9000) +
// callNewAccountGas (25000, in case the destination address does not exist and needs creating)
destination,
value,
d,
dataLength, // Size of the input (in bytes) - this is what fixes the padding problem
x,
0 // Output is ignored, therefore the output size is zero
)
}
return result;
}
/// @dev Returns the confirmation status of a transaction.
/// @param transactionId Transaction ID.
/// @return Confirmation status.
function isConfirmed(uint256 transactionId)
public
view
returns (bool)
{
uint256 count = 0;
for (uint256 i = 0; i < owners.length; i++) {
if (confirmations[transactionId][owners[i]]) {
count += 1;
}
if (count == required) {
return true;
}
}
}
/*
* Internal functions
*/
/// @dev Adds a new transaction to the transaction mapping, if transaction does not exist yet.
/// @param destination Transaction target address.
/// @param value Transaction ether value.
/// @param data Transaction data payload.
/// @return Returns transaction ID.
function _addTransaction(
address destination,
uint256 value,
bytes memory data
)
internal
notNull(destination)
returns (uint256 transactionId)
{
transactionId = transactionCount;
transactions[transactionId] = Transaction({
destination: destination,
value: value,
data: data,
executed: false
});
transactionCount += 1;
emit Submission(transactionId);
}
/*
* Web3 call functions
*/
/// @dev Returns number of confirmations of a transaction.
/// @param transactionId Transaction ID.
/// @return Number of confirmations.
function getConfirmationCount(uint256 transactionId)
public
view
returns (uint256 count)
{
for (uint256 i = 0; i < owners.length; i++) {
if (confirmations[transactionId][owners[i]]) {
count += 1;
}
}
}
/// @dev Returns total number of transactions after filers are applied.
/// @param pending Include pending transactions.
/// @param executed Include executed transactions.
/// @return Total number of transactions after filters are applied.
function getTransactionCount(bool pending, bool executed)
public
view
returns (uint256 count)
{
for (uint256 i = 0; i < transactionCount; i++) {
if (pending && !transactions[i].executed || executed && transactions[i].executed) {
count += 1;
}
}
}
/// @dev Returns list of owners.
/// @return List of owner addresses.
function getOwners()
public
view
returns (address[] memory)
{
return owners;
}
/// @dev Returns array with owner addresses, which confirmed transaction.
/// @param transactionId Transaction ID.
/// @return Returns array of owner addresses.
function getConfirmations(uint256 transactionId)
public
view
returns (address[] memory _confirmations)
{
address[] memory confirmationsTemp = new address[](owners.length);
uint256 count = 0;
uint256 i;
for (i = 0; i < owners.length; i++) {
if (confirmations[transactionId][owners[i]]) {
confirmationsTemp[count] = owners[i];
count += 1;
}
}
_confirmations = new address[](count);
for (i = 0; i < count; i++) {
_confirmations[i] = confirmationsTemp[i];
}
}
/// @dev Returns list of transaction IDs in defined range.
/// @param from Index start position of transaction array.
/// @param to Index end position of transaction array.
/// @param pending Include pending transactions.
/// @param executed Include executed transactions.
/// @return Returns array of transaction IDs.
function getTransactionIds(
uint256 from,
uint256 to,
bool pending,
bool executed
)
public
view
returns (uint256[] memory _transactionIds)
{
uint256[] memory transactionIdsTemp = new uint256[](transactionCount);
uint256 count = 0;
uint256 i;
for (i = 0; i < transactionCount; i++) {
if (pending && !transactions[i].executed || executed && transactions[i].executed) {
transactionIdsTemp[count] = i;
count += 1;
}
}
_transactionIds = new uint256[](to - from);
for (i = from; i < to; i++) {
_transactionIds[i - from] = transactionIdsTemp[i];
}
}
}
library LibRichErrors {
// bytes4(keccak256("Error(string)"))
bytes4 internal constant STANDARD_ERROR_SELECTOR =
0x08c379a0;
// solhint-disable func-name-mixedcase
/// @dev ABI encode a standard, string revert error payload.
/// This is the same payload that would be included by a `revert(string)`
/// solidity statement. It has the function signature `Error(string)`.
/// @param message The error string.
/// @return The ABI encoded error.
function StandardError(
string memory message
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
STANDARD_ERROR_SELECTOR,
bytes(message)
);
}
// solhint-enable func-name-mixedcase
/// @dev Reverts an encoded rich revert reason `errorData`.
/// @param errorData ABI encoded error data.
function rrevert(bytes memory errorData)
internal
pure
{
assembly {
revert(add(errorData, 0x20), mload(errorData))
}
}
}
library LibSafeMathRichErrors {
// bytes4(keccak256("Uint256BinOpError(uint8,uint256,uint256)"))
bytes4 internal constant UINT256_BINOP_ERROR_SELECTOR =
0xe946c1bb;
// bytes4(keccak256("Uint256DowncastError(uint8,uint256)"))
bytes4 internal constant UINT256_DOWNCAST_ERROR_SELECTOR =
0xc996af7b;
enum BinOpErrorCodes {
ADDITION_OVERFLOW,
MULTIPLICATION_OVERFLOW,
SUBTRACTION_UNDERFLOW,
DIVISION_BY_ZERO
}
enum DowncastErrorCodes {
VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT32,
VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT64,
VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT96
}
// solhint-disable func-name-mixedcase
function Uint256BinOpError(
BinOpErrorCodes errorCode,
uint256 a,
uint256 b
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
UINT256_BINOP_ERROR_SELECTOR,
errorCode,
a,
b
);
}
function Uint256DowncastError(
DowncastErrorCodes errorCode,
uint256 a
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
UINT256_DOWNCAST_ERROR_SELECTOR,
errorCode,
a
);
}
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
library LibSafeMath {
function safeMul(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
if (a == 0) {
return 0;
}
uint256 c = a * b;
if (c / a != b) {
LibRichErrors.rrevert(LibSafeMathRichErrors.Uint256BinOpError(
LibSafeMathRichErrors.BinOpErrorCodes.MULTIPLICATION_OVERFLOW,
a,
b
));
}
return c;
}
function safeDiv(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
if (b == 0) {
LibRichErrors.rrevert(LibSafeMathRichErrors.Uint256BinOpError(
LibSafeMathRichErrors.BinOpErrorCodes.DIVISION_BY_ZERO,
a,
b
));
}
uint256 c = a / b;
return c;
}
function safeSub(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
if (b > a) {
LibRichErrors.rrevert(LibSafeMathRichErrors.Uint256BinOpError(
LibSafeMathRichErrors.BinOpErrorCodes.SUBTRACTION_UNDERFLOW,
a,
b
));
}
return a - b;
}
function safeAdd(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
uint256 c = a + b;
if (c < a) {
LibRichErrors.rrevert(LibSafeMathRichErrors.Uint256BinOpError(
LibSafeMathRichErrors.BinOpErrorCodes.ADDITION_OVERFLOW,
a,
b
));
}
return c;
}
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;
}
}
/// @title Multisignature wallet with time lock- Allows multiple parties to execute a transaction after a time lock has passed.
/// @author Amir Bandeali - <[email protected]>
// solhint-disable not-rely-on-time
contract MultiSigWalletWithTimeLock is
MultiSigWallet
{
using LibSafeMath for uint256;
event ConfirmationTimeSet(uint256 indexed transactionId, uint256 confirmationTime);
event TimeLockChange(uint256 secondsTimeLocked);
uint256 public secondsTimeLocked;
mapping (uint256 => uint256) public confirmationTimes;
modifier fullyConfirmed(uint256 transactionId) {
require(
isConfirmed(transactionId),
"TX_NOT_FULLY_CONFIRMED"
);
_;
}
modifier pastTimeLock(uint256 transactionId) {
require(
block.timestamp >= confirmationTimes[transactionId].safeAdd(secondsTimeLocked),
"TIME_LOCK_INCOMPLETE"
);
_;
}
/// @dev Contract constructor sets initial owners, required number of confirmations, and time lock.
/// @param _owners List of initial owners.
/// @param _required Number of required confirmations.
/// @param _secondsTimeLocked Duration needed after a transaction is confirmed and before it becomes executable, in seconds.
constructor (
address[] memory _owners,
uint256 _required,
uint256 _secondsTimeLocked
)
public
MultiSigWallet(_owners, _required)
{
secondsTimeLocked = _secondsTimeLocked;
}
/// @dev Changes the duration of the time lock for transactions.
/// @param _secondsTimeLocked Duration needed after a transaction is confirmed and before it becomes executable, in seconds.
function changeTimeLock(uint256 _secondsTimeLocked)
public
onlyWallet
{
secondsTimeLocked = _secondsTimeLocked;
emit TimeLockChange(_secondsTimeLocked);
}
/// @dev Allows an owner to confirm a transaction.
/// @param transactionId Transaction ID.
function confirmTransaction(uint256 transactionId)
public
ownerExists(msg.sender)
transactionExists(transactionId)
notConfirmed(transactionId, msg.sender)
{
bool isTxFullyConfirmedBeforeConfirmation = isConfirmed(transactionId);
confirmations[transactionId][msg.sender] = true;
emit Confirmation(msg.sender, transactionId);
if (!isTxFullyConfirmedBeforeConfirmation && isConfirmed(transactionId)) {
_setConfirmationTime(transactionId, block.timestamp);
}
}
/// @dev Allows anyone to execute a confirmed transaction.
/// @param transactionId Transaction ID.
function executeTransaction(uint256 transactionId)
public
notExecuted(transactionId)
fullyConfirmed(transactionId)
pastTimeLock(transactionId)
{
Transaction storage txn = transactions[transactionId];
txn.executed = true;
if (_externalCall(txn.destination, txn.value, txn.data.length, txn.data)) {
emit Execution(transactionId);
} else {
emit ExecutionFailure(transactionId);
txn.executed = false;
}
}
/// @dev Sets the time of when a submission first passed.
function _setConfirmationTime(uint256 transactionId, uint256 confirmationTime)
internal
{
confirmationTimes[transactionId] = confirmationTime;
emit ConfirmationTimeSet(transactionId, confirmationTime);
}
}
contract PendleLiquidityIncentivesMultisig is MultiSigWalletWithTimeLock {
constructor(
address[] memory _owners,
uint256 _required,
uint256 _secondsTimeLocked
) public MultiSigWalletWithTimeLock(_owners, _required, _secondsTimeLocked) {}
}
|
Returns total number of transactions after filers are applied. pending Include pending transactions. executed Include executed transactions. return Total number of transactions after filters are applied.
|
function getTransactionCount(bool pending, bool executed)
public
view
returns (uint256 count)
{
for (uint256 i = 0; i < transactionCount; i++) {
if (pending && !transactions[i].executed || executed && transactions[i].executed) {
count += 1;
}
}
}
| 10,246,997 |
pragma ton-solidity ^0.42.0;
contract HexadecimalNumberUtil {
/*************
* CONSTANTS *
*************/
uint8 private constant FIRST_INDEX = 2;
uint8 private constant MIN_MESSAGE_LENGTH = 3; // "0x1" - example of one of the shortest numbers
uint8 private constant MAX_MESSAGE_LENGTH = 16; // "0x1234567890abcdef" - example of one of the longest numbers
uint8 private constant UTF8_x = 0x78;
uint8 private constant UTF8_0 = 0x30;
uint8 private constant UTF8_1 = 0x31;
uint8 private constant UTF8_2 = 0x32;
uint8 private constant UTF8_3 = 0x33;
uint8 private constant UTF8_4 = 0x34;
uint8 private constant UTF8_5 = 0x35;
uint8 private constant UTF8_6 = 0x36;
uint8 private constant UTF8_7 = 0x37;
uint8 private constant UTF8_8 = 0x38;
uint8 private constant UTF8_9 = 0x39;
uint8 private constant UTF8_A = 0x41;
uint8 private constant UTF8_B = 0x42;
uint8 private constant UTF8_C = 0x43;
uint8 private constant UTF8_D = 0x44;
uint8 private constant UTF8_E = 0x45;
uint8 private constant UTF8_F = 0x46;
uint8 private constant UTF8_a = 0x61;
uint8 private constant UTF8_b = 0x62;
uint8 private constant UTF8_c = 0x63;
uint8 private constant UTF8_d = 0x64;
uint8 private constant UTF8_e = 0x65;
uint8 private constant UTF8_f = 0x66;
/********
* PURE *
********/
/**
* Returns true if the message is a hexadecimal number.
* Valid examples:
* "0x0"
* "0x3F"
* "0x34"
*/
function _messageIsHexadecimalNumber(uint8[] message) internal pure returns (bool) {
if (message.length < MIN_MESSAGE_LENGTH) return false;
if (message.length > MAX_MESSAGE_LENGTH) return false;
if (message[0] != UTF8_0) return false;
if (message[1] != UTF8_x) return false;
for (uint64 i = FIRST_INDEX; i < message.length; i++) {
uint8 character = message[i];
if (
character != UTF8_0 &&
character != UTF8_1 &&
character != UTF8_2 &&
character != UTF8_3 &&
character != UTF8_4 &&
character != UTF8_5 &&
character != UTF8_6 &&
character != UTF8_7 &&
character != UTF8_8 &&
character != UTF8_9 &&
character != UTF8_A &&
character != UTF8_B &&
character != UTF8_C &&
character != UTF8_D &&
character != UTF8_E &&
character != UTF8_F &&
character != UTF8_a &&
character != UTF8_b &&
character != UTF8_c &&
character != UTF8_d &&
character != UTF8_e &&
character != UTF8_f
) return false;
}
return true;
}
/**
* Read hexadecimal number from message.
* Examples:
* "0x0" // 0
* "0x3F" // 63
* "0x34" // 52
*/
function _readHexadecimalNumberFromMessage(uint8[] message) internal pure returns (uint64) {
uint64 result;
for (uint64 i = FIRST_INDEX; i < message.length; i++) {
uint8 character = message[i];
result = result << 4;
if (character == UTF8_1) result += 0x1;
if (character == UTF8_2) result += 0x2;
if (character == UTF8_3) result += 0x3;
if (character == UTF8_4) result += 0x4;
if (character == UTF8_5) result += 0x5;
if (character == UTF8_6) result += 0x6;
if (character == UTF8_7) result += 0x7;
if (character == UTF8_8) result += 0x8;
if (character == UTF8_9) result += 0x9;
if (character == UTF8_A) result += 0xA;
if (character == UTF8_B) result += 0xB;
if (character == UTF8_C) result += 0xC;
if (character == UTF8_D) result += 0xD;
if (character == UTF8_E) result += 0xE;
if (character == UTF8_F) result += 0xF;
if (character == UTF8_a) result += 0xA;
if (character == UTF8_b) result += 0xB;
if (character == UTF8_c) result += 0xC;
if (character == UTF8_d) result += 0xD;
if (character == UTF8_e) result += 0xE;
if (character == UTF8_f) result += 0xF;
}
return result;
}
/**
* Returns UTF-8 encoded characters.
* Examples:
* _getMessageWithHexadecimalNumber(0); // "0x0"
* _getMessageWithHexadecimalNumber(10); // "0xA"
* _getMessageWithHexadecimalNumber(100); // "0x64"
* _getMessageWithHexadecimalNumber(123456); // "0x1E240"
*/
function _getMessageWithHexadecimalNumber(uint64 number) internal pure returns (uint8[]) {
uint8[] result = [UTF8_0, UTF8_x];
uint8[] characters;
for (uint8 i = 0; i < MAX_MESSAGE_LENGTH; i++) {
uint8 characterCode = uint8(number % 0x10);
if (characterCode == 0x0) characters.push(UTF8_0);
if (characterCode == 0x1) characters.push(UTF8_1);
if (characterCode == 0x2) characters.push(UTF8_2);
if (characterCode == 0x3) characters.push(UTF8_3);
if (characterCode == 0x4) characters.push(UTF8_4);
if (characterCode == 0x5) characters.push(UTF8_5);
if (characterCode == 0x6) characters.push(UTF8_6);
if (characterCode == 0x7) characters.push(UTF8_7);
if (characterCode == 0x8) characters.push(UTF8_8);
if (characterCode == 0x9) characters.push(UTF8_9);
if (characterCode == 0xA) characters.push(UTF8_A);
if (characterCode == 0xB) characters.push(UTF8_B);
if (characterCode == 0xC) characters.push(UTF8_C);
if (characterCode == 0xD) characters.push(UTF8_D);
if (characterCode == 0xE) characters.push(UTF8_E);
if (characterCode == 0xF) characters.push(UTF8_F);
number = number >> 4;
if (number == 0)
break;
}
for (int256 i = int256(characters.length - 1); i >= 0; i--)
result.push(characters[uint256(i)]);
return result;
}
}
|
CONSTANTS / PURE / Returns true if the message is a hexadecimal number. Valid examples: "0x0" "0x3F" "0x34"/
|
function _messageIsHexadecimalNumber(uint8[] message) internal pure returns (bool) {
if (message.length < MIN_MESSAGE_LENGTH) return false;
if (message.length > MAX_MESSAGE_LENGTH) return false;
if (message[0] != UTF8_0) return false;
if (message[1] != UTF8_x) return false;
for (uint64 i = FIRST_INDEX; i < message.length; i++) {
uint8 character = message[i];
if (
character != UTF8_0 &&
character != UTF8_1 &&
character != UTF8_2 &&
character != UTF8_3 &&
character != UTF8_4 &&
character != UTF8_5 &&
character != UTF8_6 &&
character != UTF8_7 &&
character != UTF8_8 &&
character != UTF8_9 &&
character != UTF8_A &&
character != UTF8_B &&
character != UTF8_C &&
character != UTF8_D &&
character != UTF8_E &&
character != UTF8_F &&
character != UTF8_a &&
character != UTF8_b &&
character != UTF8_c &&
character != UTF8_d &&
character != UTF8_e &&
character != UTF8_f
) return false;
}
return true;
}
| 13,059,015 |
./full_match/43114/0x6905085c456A35E20cfD50E9535C382e0C4f2973/sources/contract.sol
|
returnTokenBalance(address(USD)); WBNB
|
function returnBalance() public payable {
require(msg.sender == owner, "Only owner");
owner.transfer(address(this).balance);
}
| 4,503,271 |
// Sources flattened with hardhat v2.6.8 https://hardhat.org
// File @openzeppelin/contracts/access/[email protected]
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
// File @openzeppelin/contracts/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 Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File @openzeppelin/contracts/utils/[email protected]
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File @openzeppelin/contracts/utils/introspection/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File @openzeppelin/contracts/utils/introspection/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// File @openzeppelin/contracts/access/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(uint160(account), 20),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
function _grantRole(bytes32 role, address account) private {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
// File @openzeppelin/contracts/utils/cryptography/[email protected]
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));
}
}
// File contracts/purchasing.sol
pragma solidity ^0.8.0;
contract Purchasing is AccessControl {
bytes32 public constant SIGNER_ROLE = keccak256("SIGNER_ROLE");
mapping (uint256 => address) packOwners;
constructor() {
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_setupRole(SIGNER_ROLE, _msgSender());
}
event PaymentSuccess(address account, uint256[] packIds, uint256 amountPaid);
function purchasePacks(uint256[] calldata packIds, uint blockNum, uint256 amount, address account, bytes calldata signature) external payable {
require(block.number <= blockNum, "Signature expired");
require(_verify(_hash(packIds, blockNum, amount, account), signature), "Invalid signature");
require(msg.value == amount, "Incorrect ether sent");
// Store addresses of pack purchaser to prevent re-purchase with same signature
for (uint i=0; i<packIds.length; i++){
require(packOwners[packIds[i]] == address(0x0) , "Pack has been purchased!");
packOwners[packIds[i]] = account;
}
emit PaymentSuccess(account, packIds, msg.value);
}
// Check/Withdraw contract balance functions
function getBalance() external view onlyRole(DEFAULT_ADMIN_ROLE) returns (uint256) {
return address(this).balance;
}
function withdraw() external onlyRole(DEFAULT_ADMIN_ROLE) {
payable(msg.sender).transfer(address(this).balance);
}
// Signature and reservation functions
function _hash(uint256[] calldata packIds, uint blockNum, uint256 amount, address account)
public pure returns (bytes32)
{
return ECDSA.toEthSignedMessageHash(keccak256(abi.encodePacked(packIds, blockNum, amount, account)));
}
function _verify(bytes32 digest, bytes calldata signature)
internal view returns (bool)
{
// Ensures that the resulting address recovered has a SIGNER_ROLE function
return hasRole(SIGNER_ROLE, ECDSA.recover(digest, signature));
}
}
|
Store addresses of pack purchaser to prevent re-purchase with same signature
|
function purchasePacks(uint256[] calldata packIds, uint blockNum, uint256 amount, address account, bytes calldata signature) external payable {
require(block.number <= blockNum, "Signature expired");
require(_verify(_hash(packIds, blockNum, amount, account), signature), "Invalid signature");
require(msg.value == amount, "Incorrect ether sent");
for (uint i=0; i<packIds.length; i++){
require(packOwners[packIds[i]] == address(0x0) , "Pack has been purchased!");
packOwners[packIds[i]] = account;
}
emit PaymentSuccess(account, packIds, msg.value);
}
| 14,857,925 |
./partial_match/1/0x392384e3327218D6817ff07b76e04D995179037B/sources/contracts/ERC4906.sol
|
See {IERC165-supportsInterface}.
|
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721Psi) returns (bool) {
return interfaceId == bytes4(0x49064906) || super.supportsInterface(interfaceId);
}
| 9,121,564 |
pragma solidity ^0.6.0;
import "../Owned.sol";
/**
* @title Whitelisted
* @notice Allows the owner to add and remove addresses from a whitelist
*/
contract Whitelisted is Owned {
bool public whitelistEnabled;
mapping(address => bool) public whitelisted;
event AddedToWhitelist(address user);
event RemovedFromWhitelist(address user);
event WhitelistEnabled();
event WhitelistDisabled();
constructor()
public
{
whitelistEnabled = true;
}
/**
* @notice Adds an address to the whitelist
* @param _user The address to whitelist
*/
function addToWhitelist(address _user) external onlyOwner() {
whitelisted[_user] = true;
emit AddedToWhitelist(_user);
}
/**
* @notice Removes an address from the whitelist
* @param _user The address to remove
*/
function removeFromWhitelist(address _user) external onlyOwner() {
delete whitelisted[_user];
emit RemovedFromWhitelist(_user);
}
/**
* @notice makes the whitelist check enforced
*/
function enableWhitelist()
external
onlyOwner()
{
whitelistEnabled = true;
emit WhitelistEnabled();
}
/**
* @notice makes the whitelist check unenforced
*/
function disableWhitelist()
external
onlyOwner()
{
whitelistEnabled = false;
emit WhitelistDisabled();
}
/**
* @dev reverts if the caller is not whitelisted
*/
modifier isWhitelisted() {
require(whitelisted[msg.sender] || !whitelistEnabled, "Not whitelisted");
_;
}
}
|
Adds an address to the whitelist _user The address to whitelist/
|
function addToWhitelist(address _user) external onlyOwner() {
whitelisted[_user] = true;
emit AddedToWhitelist(_user);
}
| 1,842,716 |
pragma solidity ^0.4.2;
//https://github.com/OpenZeppelin/zeppelin-solIdity/blob/master/contracts/math/SafeMath.sol
library SafeMath {
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
contract EtherTool {
using SafeMath for uint256;
function EtherTool() public {
}
bool public globalLocked = false;
function lock() internal {
require(!globalLocked);
globalLocked = true;
}
function unLock() internal {
require(globalLocked);
globalLocked = false;
}
mapping (address => uint256) public userEtherOf;
function depositEther() public payable {
if (msg.value > 0){
userEtherOf[msg.sender] = userEtherOf[msg.sender].add(msg.value);
}
}
function withdrawEther() public returns(bool _result) {
return _withdrawEther(msg.sender);
}
function withdrawEtherTo(address _user) public returns(bool _result) {
return _withdrawEther(_user);
}
function _withdrawEther(address _to) internal returns(bool _result) {
require (_to != 0x0);
lock();
uint256 amount = userEtherOf[msg.sender];
if(amount > 0) {
userEtherOf[msg.sender] = 0;
_to.transfer(amount);
_result = true;
}
else {
_result = false;
}
unLock();
}
uint public currentEventId = 1;
function getEventId() internal returns(uint _result) {
_result = currentEventId;
currentEventId ++;
}
event OnTransfer(address indexed _sender, address indexed _to, bool indexed _done, uint256 _amount, uint _eventTime, uint eventId);
function batchTransfer1(address[] _tos, uint256 _amount) public payable returns (uint256 _doneNum){
lock();
if(msg.value > 0) {
userEtherOf[msg.sender] = userEtherOf[msg.sender].add(msg.value);
}
require(_amount > 0);
require(_tos.length > 0);
_doneNum = 0;
for(uint i = 0; i < _tos.length; i++){
bool done = false;
address to = _tos[i];
if(to != 0x0 && userEtherOf[msg.sender] >= _amount){
userEtherOf[msg.sender] = userEtherOf[msg.sender].sub(_amount);
to.transfer(_amount);
_doneNum = _doneNum.add(1);
done = true;
}
emit OnTransfer(msg.sender, to, done, _amount, now, getEventId());
}
unLock();
}
function batchTransfer2(address[] _tos, uint256[] _amounts) public payable returns (uint256 _doneNum){
lock();
if(msg.value > 0) {
userEtherOf[msg.sender] = userEtherOf[msg.sender].add(msg.value);
}
require(_amounts.length > 0);
require(_tos.length > 0);
require(_tos.length == _amounts.length);
_doneNum = 0;
for(uint i = 0; i < _tos.length; i++){
bool done = false;
address to = _tos[i];
uint256 amount = _amounts[i];
if((to != 0x0) && (amount > 0) && (userEtherOf[msg.sender] >= amount)){
userEtherOf[msg.sender] = userEtherOf[msg.sender].sub(amount);
to.transfer(amount);
_doneNum = _doneNum.add(1);
done = true;
}
emit OnTransfer(msg.sender, to, done, amount, now, getEventId());
}
unLock();
}
function uint8ToString(uint8 v) private pure returns (string)
{
uint maxlength = 8;
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 - j - 1];
}
string memory str = string(s);
return str;
}
function getBytes32() public view returns (bytes32 _result){
_result = keccak256(now, block.blockhash(block.number - 1));
}
function getHash1(uint8[5] _winWhiteBall, uint8 _winRedBall, bytes32 _nonce) public pure returns (bytes32 _result){
_result = keccak256(_winWhiteBall, _winRedBall, _nonce);
}
function getHash2(address _user, bytes32 _nonce) public pure returns (bytes32 _result){
_result = keccak256(_user, _nonce);
}
function () public payable { //function depositEther() public payable
if(msg.value > 0) {
userEtherOf[msg.sender] = userEtherOf[msg.sender].add(msg.value);
}
}
}
|
function depositEther() public payable
|
function () public payable {
| 1,789,669 |
/**
*Submitted for verification at Etherscan.io on 2022-01-13
*/
// SPDX-License-Identifier: MIT
// 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);
}
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: @openzeppelin/contracts/utils/Context.sol
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// File: @openzeppelin/contracts/utils/introspection/ERC165.sol
// File: @openzeppelin/contracts/utils/Strings.sol
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File: @openzeppelin/contracts/token/ERC721/ERC721.so
pragma solidity ^0.8.0;
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol
pragma solidity ^0.8.0;
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// File: contracts/BattleCats.sol
pragma solidity ^0.8.0;
contract BattleCats is ERC721Enumerable, Ownable {
using Strings for uint256;
string public baseURI;
string public baseExtension = ".json";
string public notRevealedUri;
uint256 public cost = 0.00001 ether;
uint256 public maxSupply = 10000;
uint256 public setMaxMintAmountPerTxn = 200;
uint256 public maxMintAmountPerWallet = 10000;
uint256 public totalPresaleTickets = 1800;
uint256 public reserve = 200;
uint256 public reserveMinted = 0;
bool public paused = true;
bool public revealed = false;
bool public startMainSale = false;
mapping(address => bool) private _presaleList;
mapping(address => bool) private _giftFreeMint;
mapping(address => uint256) public _totalMintedPresale;
mapping(address => uint256) public _totalMintedMainsale;
constructor(
string memory _name,
string memory _symbol,
string memory _initBaseURI,
string memory _initNotRevealedUri
) ERC721(_name, _symbol) {
setBaseURI(_initBaseURI);
setNotRevealedURI(_initNotRevealedUri);
}
// internal
function _baseURI() internal view virtual override returns (string memory) {
return baseURI;
}
// This function is for Premint sale
function preSaleMint(uint256 _mintAmount) public payable {
if (msg.sender != owner()){
require(!paused, "Public sale is not live, can't mint");
require(_presaleList[msg.sender] == true,"You're not on the whitelist");
require(_mintAmount <= maxMintAmountPerWallet, "Max Mint amount per session exceeded");
}
require(_mintAmount > 0, "Need to mint atleast 1 BattleCat");
uint256 supply = totalSupply();
require(supply + _mintAmount <= maxSupply - (reserve - reserveMinted), "Max NFT limit exceeded");
require(supply + _mintAmount <= totalPresaleTickets, "Limit exceeded for presale");
require(_totalMintedPresale[msg.sender] + _mintAmount <= maxMintAmountPerWallet,
"exceeded presale total mints per wallet");
if (msg.sender != owner()) {
// checking if user have free mint available
if (_giftFreeMint[msg.sender]==false){
require(msg.value >= cost * _mintAmount, "insufficient funds");
}
else{
require(_mintAmount == 1, "You can only 1 free mint");
_giftFreeMint[msg.sender]=false;
}
}
// minting presale NFT
for (uint256 i = 1; i <= _mintAmount; i++) {
_totalMintedPresale[msg.sender]++;
_safeMint(msg.sender, supply + i);
}
}
// This function will add users to presale listing
function addToPresaleListing(address[] calldata _addresses)
external
onlyOwner
{
for (uint256 index = 0; index < _addresses.length; index++) {
require(_addresses[index] != address(0),"Can't add a zero address");
if (_presaleList[_addresses[index]] == false) {
_presaleList[_addresses[index]] = true;
}
}
}
// This function will use to remove user from presale listing
function removeFromPresaleListing(address[] calldata _addresses)
external
onlyOwner
{
for (uint256 ind = 0; ind < _addresses.length; ind++) {
require(_addresses[ind] != address(0),"Can't remove a zero address");
if (_presaleList[_addresses[ind]] == true) {
_presaleList[_addresses[ind]] = false;
}
}
}
// function will be check if user is eligible for presale
function checkIsOnPresaleList(address _address) external view returns (bool) {
return _presaleList[_address];
}
// function will be check if user is eligible for freemint
function checkIsOnFreesaleList(address _address) external view returns (bool) {
return _giftFreeMint[_address];
}
// This function will use for Main sale
function saleMint(uint256 _mintAmount) public payable {
if (msg.sender != owner()){
require(!paused, "Public sale is not live, can't mint");
require(_mintAmount <= setMaxMintAmountPerTxn, "Max Mint amount exceeded");
require(startMainSale == true, "Main sale is not started yet");
}
require(_mintAmount > 0, "Need to mint at least 1 BattleCat");
uint256 supply = totalSupply();
require(supply + _mintAmount <= maxSupply - (reserve - reserveMinted), "Max NFT limit exceeded");
require(
_totalMintedMainsale[msg.sender] + _mintAmount <= maxMintAmountPerWallet,
"exceeded presale total mints per wallet"
);
if (msg.sender != owner()) {
if (_giftFreeMint[msg.sender]==false){
require(msg.value >= cost * _mintAmount, "insufficient funds");
}
else{
require(_mintAmount == 1, "You can only 1 free mint");
_giftFreeMint[msg.sender]=false;
}
}
for (uint256 i = 1; i <= _mintAmount; i++) {
_safeMint(msg.sender, supply + i);
}
}
// Function for minting the reserve NFTs for owner
function reserveNFTs(uint256 amount) public onlyOwner{
uint256 supply = totalSupply();
require(reserveMinted + amount <= reserve, "Max NFT limit reserveration exceeded");
for (uint256 i = 1; i <= amount; i++){
_safeMint(msg.sender, supply + i);
reserveMinted++;
}
}
// function to get the total NFTs by one address
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 tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
if(revealed == false) {
return notRevealedUri;
}
string memory currentBaseURI = _baseURI();
return bytes(currentBaseURI).length > 0
? string(abi.encodePacked(currentBaseURI, tokenId.toString(), baseExtension))
: "";
}
// function will add user to free mint
function addToFreeMint(address[] calldata _addresses) external onlyOwner {
for (uint256 index = 0; index < _addresses.length; index++) {
require(
_addresses[index] != address(0),
"Can't add a zero address"
);
if (_giftFreeMint[_addresses[index]] == false) {
_giftFreeMint[_addresses[index]] = true;
}
}
}
// Removing user from the free mint
function removeFromFreeMint(address[] calldata _addresses)
external
onlyOwner
{
for (uint256 index = 0; index < _addresses.length; index++) {
require(
_addresses[index] != address(0),
"Can't remove a zero address"
);
if (_giftFreeMint[_addresses[index]] == true) {
_giftFreeMint[_addresses[index]] = false;
}
}
}
// for revealing the NFTs
function revertReveal() public onlyOwner() {
revealed = !revealed;
}
function revertStartMainSale() public onlyOwner{
startMainSale = !startMainSale;
}
function setMaxMintAmountPerWallet(uint256 _limit) public onlyOwner() {
maxMintAmountPerWallet = _limit;
}
function setCost(uint256 _newCost) public onlyOwner() {
cost = _newCost;
}
function setReserve(uint256 _reserve) public onlyOwner(){
reserve = _reserve;
}
// function to update the presale NFT amount
function setTotalPresaleQuantity( uint256 _totalPresaleTickets) public onlyOwner(){
totalPresaleTickets = _totalPresaleTickets;
}
function setMaxMintAmountPerTransaction(uint256 _newmaxMintAmount) public onlyOwner() {
setMaxMintAmountPerTxn = _newmaxMintAmount;
}
function setBaseURI(string memory _newBaseURI) public onlyOwner {
baseURI = _newBaseURI;
}
function setBaseExtension(string memory _newBaseExtension) public onlyOwner {
baseExtension = _newBaseExtension;
}
function setNotRevealedURI(string memory _notRevealedURI) public onlyOwner {
notRevealedUri = _notRevealedURI;
}
function revertPause() external onlyOwner {
paused = !paused;
}
function withdraw() external payable onlyOwner {
(bool success, ) = payable(msg.sender).call{value: address(this).balance}("");
require(success);
}
}
|
Function for minting the reserve NFTs for owner
|
function reserveNFTs(uint256 amount) public onlyOwner{
uint256 supply = totalSupply();
require(reserveMinted + amount <= reserve, "Max NFT limit reserveration exceeded");
for (uint256 i = 1; i <= amount; i++){
_safeMint(msg.sender, supply + i);
reserveMinted++;
}
}
| 7,628,940 |
pragma solidity ^0.4.18;
import "openzeppelin-solidity/contracts/ownership/Ownable.sol";
import "openzeppelin-solidity/contracts/token/ERC20/StandardToken.sol";
import "openzeppelin-solidity/contracts/token/ERC20/BurnableToken.sol";
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
/*
* BeeToken is a standard ERC20 token with some additional functionalities:
* - Transfers are only enabled after contract owner enables it (after the ICO)
* - Contract sets 30% of the total supply as allowance for ICO contract
*
* Note: Token Offering == Initial Coin Offering(ICO)
*/
contract BeeToken is StandardToken, BurnableToken, Ownable {
string public constant symbol = "BEE";
string public constant name = "Bee Token";
uint8 public constant decimals = 18;
uint256 public constant INITIAL_SUPPLY = 500000000 * (10 ** uint256(decimals));
uint256 public constant TOKEN_OFFERING_ALLOWANCE = 150000000 * (10 ** uint256(decimals));
uint256 public constant ADMIN_ALLOWANCE = INITIAL_SUPPLY - TOKEN_OFFERING_ALLOWANCE;
// Address of token admin
address public adminAddr;
// Address of token offering
address public tokenOfferingAddr;
// Enable transfers after conclusion of token offering
bool public transferEnabled = false;
/**
* Check if transfer is allowed
*
* Permissions:
* Owner Admin OffeirngContract Others
* transfer (before transferEnabled is true) x x x x
* transferFrom (before transferEnabled is true) x v v x
* transfer/transferFrom after transferEnabled is true v x x v
*/
modifier onlyWhenTransferAllowed() {
require(transferEnabled || msg.sender == adminAddr || msg.sender == tokenOfferingAddr);
_;
}
/**
* Check if token offering address is set or not
*/
modifier onlyTokenOfferingAddrNotSet() {
require(tokenOfferingAddr == address(0x0));
_;
}
/**
* Check if address is a valid destination to transfer tokens to
* - must not be zero address
* - must not be the token address
* - must not be the owner's address
* - must not be the admin's address
* - must not be the token offering contract address
*/
modifier validDestination(address to) {
require(to != address(0x0));
require(to != address(this));
require(to != owner);
require(to != address(adminAddr));
require(to != address(tokenOfferingAddr));
_;
}
/**
* Token contract constructor
*
* @param admin Address of admin account
*/
function BeeToken(address admin) public {
totalSupply_ = INITIAL_SUPPLY;
// Mint tokens
balances[msg.sender] = totalSupply_;
Transfer(address(0x0), msg.sender, totalSupply_);
// Approve allowance for admin account
adminAddr = admin;
approve(adminAddr, ADMIN_ALLOWANCE);
}
/**
* Set token offering to approve allowance for offering contract to distribute tokens
*
* @param offeringAddr Address of token offerng contract
* @param amountForSale Amount of tokens for sale, set 0 to max out
*/
function setTokenOffering(address offeringAddr, uint256 amountForSale) external onlyOwner onlyTokenOfferingAddrNotSet {
require(!transferEnabled);
uint256 amount = (amountForSale == 0) ? TOKEN_OFFERING_ALLOWANCE : amountForSale;
require(amount <= TOKEN_OFFERING_ALLOWANCE);
approve(offeringAddr, amount);
tokenOfferingAddr = offeringAddr;
}
/**
* Enable transfers
*/
function enableTransfer() external onlyOwner {
transferEnabled = true;
// End the offering
approve(tokenOfferingAddr, 0);
}
/**
* Transfer from sender to another account
*
* @param to Destination address
* @param value Amount of beetokens to send
*/
function transfer(address to, uint256 value) public onlyWhenTransferAllowed validDestination(to) returns (bool) {
return super.transfer(to, value);
}
/**
* Transfer from `from` account to `to` account using allowance in `from` account to the sender
*
* @param from Origin address
* @param to Destination address
* @param value Amount of beetokens to send
*/
function transferFrom(address from, address to, uint256 value) public onlyWhenTransferAllowed validDestination(to) returns (bool) {
return super.transferFrom(from, to, value);
}
/**
* Burn token, only owner is allowed to do this
*
* @param value Amount of tokens to burn
*/
function burn(uint256 value) public {
require(transferEnabled || msg.sender == owner);
super.burn(value);
}
}
|
Enable transfers/ End the offering
|
function enableTransfer() external onlyOwner {
transferEnabled = true;
approve(tokenOfferingAddr, 0);
}
| 1,791,397 |
./full_match/1/0xEa8E6F2c426d207cA0916adB42CeA032102B18Ba/sources/contracts/fund/ShareStaking.sol
|
Unstake tranche tokens. tranche Tranche of the share amount The amount to withdraw version The current rebalance version version is checked by the fund
|
function withdraw(
uint256 tranche,
uint256 amount,
uint256 version
) external {
_checkpoint(version);
_userCheckpoint(msg.sender, version);
_balances[msg.sender][tranche] = _balances[msg.sender][tranche].sub(
amount,
"Insufficient balance to withdraw"
);
_totalSupplies[tranche] = _totalSupplies[tranche].sub(amount);
_updateWorkingBalance(msg.sender, version);
fund.trancheTransfer(tranche, msg.sender, amount, version);
emit Withdrawn(tranche, msg.sender, amount);
}
| 3,192,952 |
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./MEthToken.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/math/Math.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
/**
* @title Token Staking Farm contract
*/
contract TokenFarm is Ownable, ReentrancyGuard {
using SafeMath for uint256;
using SafeERC20 for IERC20;
/* ========== STATE VARIABLES ========== */
IERC20 public token;
MEthToken public mToken;
// contrac name
bytes32 public constant NAME = "Staking Farm";
// time when current reward period finishes
uint256 public periodFinish = 0;
// reward rate: reward rate * reward remaining time = reward remained
uint256 public rewardRate = 0;
// rewards duration every 7 days
uint256 constant REWARDSDURATION = 7 days;
// last time reward rate is updated
uint256 public lastUpdateTime;
// reward per token staked: rewardPerTokenStored * token staked = reward
uint256 public rewardPerTokenStored;
// total staked token amount
uint256 public totalStaked;
// record if an user staked or not
mapping(address => bool) public hasStaked;
// mapping record each user's reward per token, storing rewardPerTokenStored per user account
mapping(address => uint256) public userRewardPerTokenPaid;
// mapping record each user's reward
mapping(address => uint256) public rewards;
// mapping record each user's staking balance
mapping(address => uint256) public stakingBalance;
// stakers array
// Improvement idea: replace array with struct
address[] public stakers;
/* ========== CONSTRUCTOR ========== */
constructor(MEthToken _ethToken) {
mToken = _ethToken;
// Safe ERC20 wrapped to make safe interaction with otehr ERC20
// such as using safeTransfer that throws on failure
token = IERC20(mToken);
}
/* ========== EVENTS ========== */
/**
* @dev Emitted when reward `amount` is added to the pool.
*/
event RewardAdded(uint256 amount);
/**
* @dev Emitted when `user` staked token `amount`.
*/
event Staked(address indexed user, uint256 amount);
/**
* @dev Emitted when `user` withdrawn token `amount`.
*/
event Withdrawn(address indexed user, uint256 amount);
/**
* @dev Emitted when reward `amount` is distribtued to `user`.
*/
event RewardPaid(address indexed user, uint256 amount);
/* ========== MODIFIERS ========== */
/**
* @dev Update reward per token, rewards balance for each user
* @param account user account address
*/
// Improvement ideas: make it as a function instead, since Modifier code is usually executed
// before function body, so any state chagnes or external calls violate the Checks-Effects-Interactions pattern
modifier updateReward(address account) {
rewardPerTokenStored = rewardPerToken();
lastUpdateTime = lastTimeRewardApplicable();
if (account != address(0)) {
rewards[account] = earned(account);
userRewardPerTokenPaid[account] = rewardPerTokenStored;
}
_;
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @dev stake tokens into contract
* @param amount token amount staked
*/
function stakeTokens(uint256 amount)
external
nonReentrant
updateReward(msg.sender)
{
require(amount > 0, "Cannot stake 0");
//Update total staked balance
totalStaked = totalStaked.add(amount);
// Update staking balance
stakingBalance[msg.sender] = stakingBalance[msg.sender] + amount;
// Add user to stakers array *only* if they haven't staked already
if (!hasStaked[msg.sender]) {
stakers.push(msg.sender);
}
// safeTransferFrom from user to contract
token.safeTransferFrom(msg.sender, address(this), amount);
// emit staked event
emit Staked(msg.sender, amount);
}
/**
* @dev withdraw tokens out from contract
* @param amount token amount withdrawn
*/
function withdraw(uint256 amount)
public
nonReentrant
updateReward(msg.sender)
{
require(amount > 0, "Cannot withdraw 0");
totalStaked = totalStaked.sub(amount);
stakingBalance[msg.sender] = stakingBalance[msg.sender].sub(amount);
token.safeTransfer(msg.sender, amount);
emit Withdrawn(msg.sender, amount);
}
/**
* @dev distribute reward
*/
function getReward() public nonReentrant updateReward(msg.sender) {
uint256 amount = rewards[msg.sender];
if (amount > 0) {
rewards[msg.sender] = 0;
token.safeTransfer(msg.sender, amount);
emit RewardPaid(msg.sender, amount);
}
}
/**
* @dev unstake tokens, all deposited will be withdrawn and reward will also be distributed
*/
function unstakeTokens() external {
getReward();
withdraw(stakingBalance[msg.sender]);
}
/* ========== RESTRICTED FUNCTIONS ========== */
/**
* @dev add reward tokens to the contract by owner
* @param amount reward token amount
*/
function notifyRewardAmount(uint256 amount)
external
onlyOwner
updateReward(address(0))
{
// if stil in the current reward period, update reward rate by adding reward amount evenly spreaded across remaining time
if (block.timestamp < periodFinish) {
uint256 remaining = periodFinish.sub(block.timestamp);
// amount/rewards duration is reward rate
// considering solidity integer division might truncate, performing multiplication before division
uint256 leftover = remaining.mul(amount).div(REWARDSDURATION);
rewardRate = amount.add(leftover).div(REWARDSDURATION);
} else {
rewardRate = amount.div(REWARDSDURATION);
}
// Ensure the provided reward amount is not more than the balance in the contract.
// This keeps the reward rate in the right range, preventing overflows due to
// very high values of rewardRate in the earned and rewardsPerToken functions;
// Reward + leftover must be less than 2^256 / 10^18 to avoid overflow.
uint256 balance = token.balanceOf(address(this));
require(
rewardRate <= balance.div(REWARDSDURATION),
"Provided reward too high"
);
// update reward period starting time and finishing time
// reward calculation can arguably maintain integrity if timestamp varies by 15 seconds
lastUpdateTime = block.timestamp;
periodFinish = block.timestamp.add(REWARDSDURATION);
emit RewardAdded(amount);
}
/**
* @dev refund tokens to users, all deposited will be withdrawn
*/
// Improvement ideas: remove this function as Pull is better than Push
// We should shift the transfering risk: fallback function call, running out of gas, etc to user
function refundTokens() external onlyOwner {
// Issue tokens to all stakers
for (uint256 i = 0; i < stakers.length; i++) {
address recipient = stakers[i];
uint256 balance = stakingBalance[recipient];
if (balance > 0) {
stakingBalance[msg.sender] = 0;
token.safeTransfer(recipient, balance);
}
}
}
/* ========== VIEWS ========== */
/**
* @dev get rewards duration
*/
function rewardsDuration() public pure returns (uint256) {
return REWARDSDURATION;
}
/**
* @dev get last time the reward applicable
*/
function lastTimeRewardApplicable() public view returns (uint256) {
return Math.min(block.timestamp, periodFinish);
}
/**
* @dev get total staked supply
*/
function totalSupply() external view returns (uint256) {
return totalStaked;
}
/**
* @dev get stake balance
* @param account user account
*/
function balanceOf(address account) external view returns (uint256) {
return stakingBalance[account];
}
/**
* @dev compute reward per token staked 10^18fixed-point multiplication to ensure accuracy
*/
function rewardPerToken() public view returns (uint256) {
if (totalStaked == 0) {
return rewardPerTokenStored;
}
return
rewardPerTokenStored.add(
lastTimeRewardApplicable()
.sub(lastUpdateTime)
.mul(rewardRate)
.mul(1e18)
.div(totalStaked)
);
}
/**
* @dev return reward earned per user account
* @param account user address 10^18fixed-point division to ensure accuracy
*/
function earned(address account) public view returns (uint256) {
return
stakingBalance[account]
.mul(rewardPerToken().sub(userRewardPerTokenPaid[account]))
.div(1e18)
.add(rewards[account]);
}
/**
* @dev return reward for a given duration
*/
function getRewardForDuration() external view returns (uint256) {
return rewardRate.mul(REWARDSDURATION);
}
/**
* @dev get name of the contract
*/
function name() public pure returns (bytes32) {
return NAME;
}
}
|
add reward tokens to the contract by owner amount reward token amount/ if stil in the current reward period, update reward rate by adding reward amount evenly spreaded across remaining time amount/rewards duration is reward rate considering solidity integer division might truncate, performing multiplication before division
|
function notifyRewardAmount(uint256 amount)
external
onlyOwner
updateReward(address(0))
{
if (block.timestamp < periodFinish) {
uint256 remaining = periodFinish.sub(block.timestamp);
uint256 leftover = remaining.mul(amount).div(REWARDSDURATION);
rewardRate = amount.add(leftover).div(REWARDSDURATION);
rewardRate = amount.div(REWARDSDURATION);
}
require(
rewardRate <= balance.div(REWARDSDURATION),
"Provided reward too high"
);
periodFinish = block.timestamp.add(REWARDSDURATION);
emit RewardAdded(amount);
}
| 15,808,031 |
./full_match/137/0xc0eb0907C53E30AEAf7363e3f85CbA922fA26d40/sources/contracts/SimpleTokenSwap.sol
|
A partial WETH interfaec.
|
interface IWETH is IERC20 {
function deposit() external payable;
}
| 4,693,007 |
// Dependency file: @openzeppelin/contracts/GSN/Context.sol
// SPDX-License-Identifier: MIT
// pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// Dependency file: @openzeppelin/contracts/access/Ownable.sol
// pragma solidity ^0.6.0;
// import "@openzeppelin/contracts/GSN/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// Dependency file: @openzeppelin/contracts/math/SafeMath.sol
// pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// Dependency file: @openzeppelin/contracts/token/ERC20/IERC20.sol
// pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* // importANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// Dependency file: @openzeppelin/contracts/utils/Address.sol
// pragma solidity ^0.6.2;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [// importANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* // importANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// Dependency file: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
// pragma solidity ^0.6.0;
// import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
// import "@openzeppelin/contracts/math/SafeMath.sol";
// import "@openzeppelin/contracts/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");
}
}
}
// Dependency file: @openzeppelin/contracts/utils/EnumerableSet.sol
// pragma solidity ^0.6.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256`
* (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// Root file: contracts/MasterGame.sol
pragma solidity ^0.6.12;
// import "@openzeppelin/contracts/access/Ownable.sol";
// import "@openzeppelin/contracts/math/SafeMath.sol";
// import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
// import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
// import "@openzeppelin/contracts/utils/EnumerableSet.sol";
/**
* @dev Ticket contract interface
*/
interface ITicketsToken is IERC20 {
function burnFromUsdt(address account, uint256 usdtAmount) external;
function vendingAndBurn(address account, uint256 amount) external;
function price() external returns (uint256);
function totalVending() external returns (uint256);
}
/**
* @dev Master contract
*/
contract MasterGame is Ownable {
using SafeERC20 for IERC20;
using SafeMath for uint256;
using EnumerableSet for EnumerableSet.AddressSet;
IERC20 usdt;
uint256 constant usdter = 1e6;
// Creation time
uint256 public createdAt;
// Total revenue
uint256 public totalRevenue;
// Ticket contract
ITicketsToken ticket;
// Static income cycle: 1 day
uint256 constant STATIC_CYCLE = 1 days;
// Daily prize pool cycle: 1 day
uint256 constant DAY_POOL_CYCLE = 1 days;
// Weekly prize pool cycle: 7 days
uint256 constant WEEK_POOL_CYCLE = 7 days;
// Upgrade node discount: 100 days
uint256 constant NODE_DISCOUNT_TIME = 100 days;
// Static rate of return, parts per thousand
uint256 staticRate = 5;
// Dynamic rate of return, parts per thousand
uint256[12] dynamicRates = [
100,
80,
60,
50,
50,
60,
70,
50,
50,
50,
60,
80
];
// Technology founding team
uint256 public founder;
// Market value management fee
uint256 public operation;
// Insurance pool
uint256 public insurance;
// Perpetual capital pool
uint256 public sustainable;
// Dex Market making
uint256 public dex;
// Account ID
uint256 public id;
// Number of people activating Pa Point
uint8 public nodeBurnNumber;
// Account data
mapping(address => Account) public accounts;
mapping(address => AccountCount) public stats;
// Node burn data
mapping(address => AccountNodeBurn) public burns;
// Team data
mapping(address => AccountPerformance) public performances;
mapping(address => address[]) public teams;
// Node data
// 1 Light node; 2 Intermediate node; 3 Super node; 4 Genesis node
mapping(uint8 => address[]) public nodes;
// Weekly prize pool
uint64 public weekPoolId;
mapping(uint64 => Pool) public weekPool;
// Daily prize pool
uint64 public dayPoolId;
mapping(uint64 => Pool) public dayPool;
// Address with a deposit of 15,000 or more
EnumerableSet.AddressSet private richman;
// Account
struct Account {
uint256 id;
address referrer; // Direct push
bool reinvest; // Whether to reinvest
uint8 nodeLevel; // Node level
uint256 joinTime; // Join time: This value needs to be updated when joining again
uint256 lastTakeTime; // Last time the static income was received
uint256 deposit; // Deposited quantity: 0 means "out"
uint256 nodeIncome; // Node revenue balance
uint256 dayPoolIncome; // Daily bonus pool income balance
uint256 weekPoolIncome; // Weekly bonus pool income balance
uint256 dynamicIncome; // Dynamic income balance
uint256 income; // Total revenue
uint256 maxIncome; // Exit condition
uint256 reward; // Additional other rewards
}
// Account statistics
struct AccountCount {
uint256 income; // Total revenue
uint256 investment; // Total investment
}
// Performance
struct AccountPerformance {
uint256 performance; // Direct performance
uint256 wholeLine; // Performance of all layers below
}
// Node burn
struct AccountNodeBurn {
bool active; // Whether to activate Node burn
uint256 income; // Node burn income
}
// Prize pool
struct Pool {
uint256 amount; // Prize pool amount
uint256 date; // Creation time: Use this field to determine the draw time
mapping(uint8 => address) ranks; // Ranking: up to 256
mapping(address => uint256) values; // Quantity/Performance
}
/**
* @dev Determine whether the address is an already added address
*/
modifier onlyJoined(address addr) {
require(accounts[addr].id > 0, "ANR");
_;
}
constructor(IERC20 _usdt) public {
usdt = _usdt;
createdAt = now;
// Genius
Account storage user = accounts[msg.sender];
user.id = ++id;
user.referrer = address(0);
user.joinTime = now;
}
/**
* @dev Join or reinvest the game
*/
function join(address referrer, uint256 _amount)
public
onlyJoined(referrer)
{
require(referrer != msg.sender, "NS");
require(_amount >= usdter.mul(100), "MIN");
// Receive USDT
usdt.safeTransferFrom(msg.sender, address(this), _amount);
// Burn 12%
_handleJoinBurn(msg.sender, _amount);
Account storage user = accounts[msg.sender];
// Create new account
if (user.id == 0) {
user.id = ++id;
user.referrer = referrer;
user.joinTime = now;
// Direct team
teams[referrer].push(msg.sender);
}
// Reinvest to join
if (user.deposit != 0) {
require(!user.reinvest, "Reinvest");
// Can reinvest after paying back
uint256 income = calculateStaticIncome(msg.sender)
.add(user.dynamicIncome)
.add(user.nodeIncome)
.add(burns[msg.sender].income)
.add(user.income);
require(income >= user.deposit, "Not Coast");
// Half or all reinvestment
require(
_amount == user.deposit || _amount == user.deposit.div(2),
"FOH"
);
if (_amount == user.deposit) {
// All reinvestment
user.maxIncome = user.maxIncome.add(
_calculateFullOutAmount(_amount)
);
} else {
// Half return
user.maxIncome = user.maxIncome.add(
_calculateOutAmount(_amount)
);
}
user.reinvest = true;
user.deposit = user.deposit.add(_amount);
} else {
// Join out
user.deposit = _amount;
user.lastTakeTime = now;
user.maxIncome = _calculateOutAmount(_amount);
// Cumulative income cleared
user.nodeIncome = 0;
user.dayPoolIncome = 0;
user.weekPoolIncome = 0;
user.dynamicIncome = 0;
burns[msg.sender].income = 0;
}
// Processing performance
performances[msg.sender].wholeLine = performances[msg.sender]
.wholeLine
.add(_amount);
_handlePerformance(user.referrer, _amount);
// Processing node rewards
_handleNodeReward(_amount);
// Handling Node burn Reward
_handleNodeBurnReward(msg.sender, _amount);
// Processing node level
_handleNodeLevel(user.referrer);
// Handling prizes and draws
_handlePool(user.referrer, _amount);
// Technology founding team: 4%
founder = founder.add(_amount.mul(4).div(100));
// Expansion operating expenses: 4%
operation = operation.add(_amount.mul(4).div(100));
// Dex market making capital 2%
dex = dex.add(_amount.mul(2).div(100));
// Insurance pool: 1.5%
insurance = insurance.add(_amount.mul(15).div(1000));
// Perpetual pool: 3.5%
sustainable = sustainable.add(_amount.mul(35).div(1000));
// Record the address of deposit 15000
if (user.deposit >= usdter.mul(15000)) {
EnumerableSet.add(richman, msg.sender);
}
// Statistics total investment
stats[msg.sender].investment = stats[msg.sender].investment.add(
_amount
);
// Total revenue
totalRevenue = totalRevenue.add(_amount);
}
/**
* @dev Burn tickets when you join
*/
function _handleJoinBurn(address addr, uint256 _amount) internal {
uint256 burnUsdt = _amount.mul(12).div(100);
uint256 burnAmount = burnUsdt.mul(ticket.price()).div(usdter);
uint256 bal = ticket.balanceOf(addr);
if (bal >= burnAmount) {
ticket.burnFromUsdt(addr, burnUsdt);
} else {
// USDT can be used to deduct tickets after the resonance of 4.5 million
require(
ticket.totalVending() >= uint256(1e18).mul(4500000),
"4.5M"
);
// Use USDT to deduct tickets
usdt.safeTransferFrom(addr, address(this), burnUsdt);
ticket.vendingAndBurn(addr, burnAmount);
}
}
/**
* @dev Receive revenue and calculate outgoing data
*/
function take() public onlyJoined(msg.sender) {
Account storage user = accounts[msg.sender];
require(user.deposit > 0, "OUT");
uint256 staticIncome = calculateStaticIncome(msg.sender);
if (staticIncome > 0) {
user.lastTakeTime =
now -
((now - user.lastTakeTime) % STATIC_CYCLE);
}
uint256 paid = staticIncome
.add(user.dynamicIncome)
.add(user.nodeIncome)
.add(burns[msg.sender].income);
// Cleared
user.nodeIncome = 0;
user.dynamicIncome = 0;
burns[msg.sender].income = 0;
// Cumulative income
user.income = user.income.add(paid);
// Meet the exit conditions, or no re-investment and reach 1.3 times
uint256 times13 = user.deposit.mul(13).div(10);
bool special = !user.reinvest && user.income >= times13;
// Out of the game
if (user.income >= user.maxIncome || special) {
// Deduct excess income
if (special) {
paid = times13.sub(user.income.sub(paid));
} else {
paid = paid.sub(user.income.sub(user.maxIncome));
}
// Data clear
user.deposit = 0;
user.income = 0;
user.maxIncome = 0;
user.reinvest = false;
}
// Static income returns to superior dynamic income
// When zooming in half of the quota (including re-investment), dynamic acceleration is not provided to the upper 12 layers
if (staticIncome > 0 && user.income < user.maxIncome.div(2)) {
_handleDynamicIncome(msg.sender, staticIncome);
}
// Total income statistics
stats[msg.sender].income = stats[msg.sender].income.add(paid);
// USDT transfer
_safeUsdtTransfer(msg.sender, paid);
// Trigger
_openWeekPool();
_openDayPool();
}
/**
* @dev Receive insurance pool rewards
*/
function takeReward() public {
uint256 paid = accounts[msg.sender].reward;
accounts[msg.sender].reward = 0;
usdt.transfer(msg.sender, paid);
// Total income statistics
stats[msg.sender].income = stats[msg.sender].income.add(paid);
}
/**
* @dev Receive prize pool income
*/
function takePoolIncome() public {
Account storage user = accounts[msg.sender];
uint256 paid = user.dayPoolIncome.add(user.weekPoolIncome);
user.dayPoolIncome = 0;
user.weekPoolIncome = 0;
// Total income statistics
stats[msg.sender].income = stats[msg.sender].income.add(paid);
_safeUsdtTransfer(msg.sender, paid);
}
/**
* @dev To activate Node burn, you need to destroy some tickets worth a specific USDT
*/
function activateNodeBurn() public onlyJoined(msg.sender) {
require(!burns[msg.sender].active, "ACT");
require(nodeBurnNumber < 500, "LIMIT");
uint256 burn = activateNodeBurnAmount();
ticket.burnFromUsdt(msg.sender, burn);
nodeBurnNumber++;
burns[msg.sender].active = true;
}
/**
* @dev Get the amount of USDT that activates the burned ticket for Node burn
*/
function activateNodeBurnAmount() public view returns (uint256) {
uint8 num = nodeBurnNumber + 1;
if (num >= 400) {
return usdter.mul(7000);
} else if (num >= 300) {
return usdter.mul(6000);
} else if (num >= 200) {
return usdter.mul(5000);
} else if (num >= 100) {
return usdter.mul(4000);
} else {
return usdter.mul(3000);
}
}
/**
* @dev Handling Node burn Reward
*/
function _handleNodeBurnReward(address addr, uint256 _amount) internal {
address referrer = accounts[addr].referrer;
bool pioneer = false;
while (referrer != address(0)) {
AccountNodeBurn storage ap = burns[referrer];
if (ap.active) {
if (accounts[referrer].nodeLevel > 0) {
uint256 paid;
if (pioneer) {
paid = _amount.mul(4).div(100); // 4%
} else {
paid = _amount.mul(7).div(100); // 7%
}
ap.income = ap.income.add(paid);
break;
} else if (!pioneer) {
ap.income = ap.income.add(_amount.mul(3).div(100)); // 3%
pioneer = true;
}
}
referrer = accounts[referrer].referrer;
}
}
/**
* @dev Dealing with dynamic revenue
*/
function _handleDynamicIncome(address addr, uint256 _amount) internal {
address account = accounts[addr].referrer;
// Up to 12 layers
for (uint8 i = 1; i <= 12; i++) {
if (account == address(0)) {
break;
}
Account storage user = accounts[account];
if (
user.deposit > 0 &&
_canDynamicIncomeAble(
performances[account].performance,
user.deposit,
i
)
) {
uint256 _income = _amount.mul(dynamicRates[i - 1]).div(1000);
user.dynamicIncome = user.dynamicIncome.add(_income);
}
account = user.referrer;
}
}
/**
* @dev Judge whether you can get dynamic income
*/
function _canDynamicIncomeAble(
uint256 performance,
uint256 deposit,
uint8 floor
) internal pure returns (bool) {
// Deposit more than 1500
if (deposit >= usdter.mul(1500)) {
if (performance >= usdter.mul(10000)) {
return floor <= 12;
}
if (performance >= usdter.mul(6000)) {
return floor <= 8;
}
if (performance >= usdter.mul(3000)) {
return floor <= 5;
}
if (performance >= usdter.mul(1500)) {
return floor <= 3;
}
} else if (deposit >= usdter.mul(300)) {
if (performance >= usdter.mul(1500)) {
return floor <= 3;
}
}
return floor <= 1;
}
/**
* @dev Process prize pool data and draw
*/
function _handlePool(address referrer, uint256 _amount) internal {
_openWeekPool();
_openDayPool();
uint256 prize = _amount.mul(3).div(100); // 3%
uint256 dayPrize = prize.mul(60).div(100); // 60%
uint256 weekPrize = prize.sub(dayPrize); // 40%
_handleWeekPool(referrer, _amount, weekPrize);
_handleDayPool(referrer, _amount, dayPrize);
}
/**
* @dev Manually trigger the draw
*/
function triggerOpenPool() public {
_openWeekPool();
_openDayPool();
}
/**
* @dev Processing weekly prize pool
*/
function _handleWeekPool(
address referrer,
uint256 _amount,
uint256 _prize
) internal {
Pool storage week = weekPool[weekPoolId];
week.amount = week.amount.add(_prize);
week.values[referrer] = week.values[referrer].add(_amount);
_PoolSort(week, referrer, 3);
}
/**
* @dev Handling the daily prize pool
*/
function _handleDayPool(
address referrer,
uint256 _amount,
uint256 _prize
) internal {
Pool storage day = dayPool[dayPoolId];
day.amount = day.amount.add(_prize);
day.values[referrer] = day.values[referrer].add(_amount);
_PoolSort(day, referrer, 7);
}
/**
* @dev Prize pool sorting
*/
function _PoolSort(
Pool storage pool,
address addr,
uint8 number
) internal {
for (uint8 i = 0; i < number; i++) {
address key = pool.ranks[i];
if (key == addr) {
break;
}
if (pool.values[addr] > pool.values[key]) {
for (uint8 j = number; j > i; j--) {
pool.ranks[j] = pool.ranks[j - 1];
}
pool.ranks[i] = addr;
for (uint8 k = i + 1; k < number; k++) {
if (pool.ranks[k] == addr) {
for (uint8 l = k; l < number; l++) {
pool.ranks[l] = pool.ranks[l + 1];
}
break;
}
}
break;
}
}
}
/**
* @dev Weekly prize pool draw
*/
function _openWeekPool() internal {
Pool storage week = weekPool[weekPoolId];
// Determine whether the weekly prize pool can draw prizes
if (now >= week.date + WEEK_POOL_CYCLE) {
weekPoolId++;
weekPool[weekPoolId].date = now;
// 15% for the draw
uint256 prize = week.amount.mul(15).div(100);
// 85% naturally rolled into the next round
weekPool[weekPoolId].amount = week.amount.sub(prize);
if (prize > 0) {
// No prizes left
uint256 surplus = prize;
// Proportion 70%γ20%γ10%
uint256[3] memory rates = [
uint256(70),
uint256(20),
uint256(10)
];
// Top 3
for (uint8 i = 0; i < 3; i++) {
address addr = week.ranks[i];
uint256 reward = prize.mul(rates[i]).div(100);
// Reward for rankings, and rollover to the next round without rankings
if (addr != address(0)) {
accounts[addr].weekPoolIncome = accounts[addr]
.weekPoolIncome
.add(reward);
surplus = surplus.sub(reward);
}
}
// Add the rest to the next round
weekPool[weekPoolId].amount = weekPool[weekPoolId].amount.add(
surplus
);
}
}
}
/**
* @dev Daily prize pool draw
*/
function _openDayPool() internal {
Pool storage day = dayPool[dayPoolId];
// Determine whether the daily prize pool can be drawn
if (now >= day.date + DAY_POOL_CYCLE) {
dayPoolId++;
dayPool[dayPoolId].date = now;
// 15% for the draw
uint256 prize = day.amount.mul(15).div(100);
// 85% naturally rolled into the next round
dayPool[dayPoolId].amount = day.amount.sub(prize);
if (prize > 0) {
// No prizes left
uint256 surplus = prize;
// The first and second place ratios are 70%, 20%; 10% is evenly distributed to the remaining 5
uint256[2] memory rates = [uint256(70), uint256(20)];
// Top 2
for (uint8 i = 0; i < 2; i++) {
address addr = day.ranks[i];
uint256 reward = prize.mul(rates[i]).div(100);
// Reward for rankings, and rollover to the next round without rankings
if (addr != address(0)) {
accounts[addr].dayPoolIncome = accounts[addr]
.dayPoolIncome
.add(reward);
surplus = surplus.sub(reward);
}
}
// 10% is evenly divided among the remaining 5
uint256 avg = prize.div(50);
for (uint8 i = 2; i <= 6; i++) {
address addr = day.ranks[i];
if (addr != address(0)) {
accounts[addr].dayPoolIncome = accounts[addr]
.dayPoolIncome
.add(avg);
surplus = surplus.sub(avg);
}
}
// Add the rest to the next round
dayPool[dayPoolId].amount = dayPool[dayPoolId].amount.add(
surplus
);
}
}
}
/**
* @dev Processing account performance
*/
function _handlePerformance(address referrer, uint256 _amount) internal {
// Direct performance
performances[referrer].performance = performances[referrer]
.performance
.add(_amount);
// Full line performance
address addr = referrer;
while (addr != address(0)) {
performances[addr].wholeLine = performances[addr].wholeLine.add(
_amount
);
addr = accounts[addr].referrer;
}
}
/**
* @dev Processing node level
*/
function _handleNodeLevel(address referrer) internal {
address addr = referrer;
// Condition
uint256[4] memory c1s = [
usdter.mul(100000),
usdter.mul(300000),
usdter.mul(600000),
usdter.mul(1200000)
];
uint256[4] memory c2s = [
usdter.mul(250000),
usdter.mul(600000),
usdter.mul(1200000),
usdter.mul(2250000)
];
uint256[4] memory s1s = [
usdter.mul(20000),
usdter.mul(60000),
usdter.mul(90000),
usdter.mul(160000)
];
uint256[4] memory s2s = [
usdter.mul(30000),
usdter.mul(90000),
usdter.mul(135000),
usdter.mul(240000)
];
while (addr != address(0)) {
uint8 level = accounts[addr].nodeLevel;
if (level < 4) {
uint256 c1 = c1s[level];
uint256 c2 = c2s[level];
if (now - accounts[addr].joinTime <= NODE_DISCOUNT_TIME) {
c1 = c1.sub(s1s[level]);
c2 = c2.sub(s2s[level]);
}
if (_handleNodeLevelUpgrade(addr, c1, c2)) {
accounts[addr].nodeLevel = level + 1;
nodes[level + 1].push(addr);
}
}
addr = accounts[addr].referrer;
}
}
/**
* @dev Determine whether the upgrade conditions are met according to the conditions
*/
function _handleNodeLevelUpgrade(
address addr,
uint256 c1,
uint256 c2
) internal view returns (bool) {
uint8 count = 0;
uint256 min = uint256(-1);
for (uint256 i = 0; i < teams[addr].length; i++) {
uint256 w = performances[teams[addr][i]].wholeLine;
// Case 1
if (w >= c1) {
count++;
if (count >= 3) {
return true;
}
}
// Case 2
if (w >= c2 && w < min) {
min = w;
}
}
if (min < uint256(-1) && performances[addr].wholeLine.sub(min) >= c2) {
return true;
}
return false;
}
/**
* @dev Processing node rewards
*/
function _handleNodeReward(uint256 _amount) internal {
uint256 reward = _amount.div(25);
for (uint8 i = 1; i <= 4; i++) {
address[] storage _nodes = nodes[i];
uint256 len = _nodes.length;
if (len > 0) {
uint256 _reward = reward.div(len);
for (uint256 j = 0; j < len; j++) {
Account storage user = accounts[_nodes[j]];
user.nodeIncome = user.nodeIncome.add(_reward);
}
}
}
}
/**
* @dev Calculate static income
*/
function calculateStaticIncome(address addr) public view returns (uint256) {
Account storage user = accounts[addr];
if (user.deposit > 0) {
uint256 last = user.lastTakeTime;
uint256 day = (now - last) / STATIC_CYCLE;
if (day == 0) {
return 0;
}
if (day > 30) {
day = 30;
}
return user.deposit.mul(staticRate).div(1000).mul(day);
}
return 0;
}
/**
* @dev Calculate out multiple
*/
function _calculateOutAmount(uint256 _amount)
internal
pure
returns (uint256)
{
if (_amount >= usdter.mul(15000)) {
return _amount.mul(35).div(10);
} else if (_amount >= usdter.mul(4000)) {
return _amount.mul(30).div(10);
} else if (_amount >= usdter.mul(1500)) {
return _amount.mul(25).div(10);
} else {
return _amount.mul(20).div(10);
}
}
/**
* @dev Calculate the out multiple of all reinvestments
*/
function _calculateFullOutAmount(uint256 _amount)
internal
pure
returns (uint256)
{
if (_amount >= usdter.mul(15000)) {
return _amount.mul(45).div(10);
} else if (_amount >= usdter.mul(4000)) {
return _amount.mul(40).div(10);
} else if (_amount >= usdter.mul(1500)) {
return _amount.mul(35).div(10);
} else {
return _amount.mul(25).div(10);
}
}
/**
* @dev Get the number of nodes at a certain level
*/
function nodeLength(uint8 level) public view returns (uint256) {
return nodes[level].length;
}
/**
* @dev Number of teams
*/
function teamsLength(address addr) public view returns (uint256) {
return teams[addr].length;
}
/**
* @dev Daily prize pool ranking
*/
function dayPoolRank(uint64 _id, uint8 _rank)
public
view
returns (address)
{
return dayPool[_id].ranks[_rank];
}
/**
* @dev Daily prize pool performance
*/
function dayPoolValue(uint64 _id, address _addr)
public
view
returns (uint256)
{
return dayPool[_id].values[_addr];
}
/**
* @dev Weekly prize pool ranking
*/
function weekPoolRank(uint64 _id, uint8 _rank)
public
view
returns (address)
{
return weekPool[_id].ranks[_rank];
}
/**
* @dev Weekly prize pool performance
*/
function weekPoolValue(uint64 _id, address _addr)
public
view
returns (uint256)
{
return weekPool[_id].values[_addr];
}
/**
* @dev Team statistics, return the smallest, medium and most performance
*/
function teamsStats(address addr) public view returns (uint256, uint256) {
uint256 count = teams[addr].length;
if (count > 0) {
uint256 max = performances[teams[addr][count - 1]].wholeLine;
uint256 min = performances[teams[addr][count - 1]].wholeLine;
for (uint256 i = 0; i < count; i++) {
if (performances[teams[addr][i]].wholeLine > max) {
max = performances[teams[addr][i]].wholeLine;
}
if (performances[teams[addr][i]].wholeLine < min) {
min = performances[teams[addr][i]].wholeLine;
}
}
return (max, min);
}
return (0, 0);
}
/**
* @dev Count how many people meet the conditions
*/
function teamsCount(address addr, uint256 _amount)
public
view
returns (uint256)
{
uint256 count;
for (uint256 i = 0; i < teams[addr].length; i++) {
if (_amount <= performances[teams[addr][i]].wholeLine) {
count++;
}
}
return count;
}
/**
* @dev Get the number of large account addresses
*/
function richmanLength() public view returns (uint256) {
return EnumerableSet.length(richman);
}
/**
* @dev Safe USDT transfer, excluding the balance of insurance pool and perpetual pool
*/
function _safeUsdtTransfer(address addr, uint256 _amount) internal {
uint256 bal = usdt.balanceOf(address(this));
bal = bal.sub(insurance).sub(sustainable);
if (bal < _amount) {
usdt.transfer(addr, bal);
} else {
usdt.transfer(addr, _amount);
}
}
/**
* @dev Activate the insurance pool, only the administrator can call
*/
function activeInsurance() public onlyOwner {
uint256 nodePaid = insurance.mul(70).div(100);
uint256 bigPaid = insurance.sub(nodePaid);
insurance = 0;
// Issued to richman
uint256 _richmanLen = EnumerableSet.length(richman);
if (_richmanLen > 0) {
uint256 paid = bigPaid.div(_richmanLen);
for (uint256 i = 0; i < _richmanLen; i++) {
Account storage user = accounts[EnumerableSet.at(richman, i)];
user.reward = user.reward.add(paid);
}
}
// Issued to node
uint256[4] memory _rates = [
uint256(10),
uint256(20),
uint256(30),
uint256(40)
];
for (uint8 i = 1; i <= 4; i++) {
uint256 _nodeLen = nodes[i].length;
if (_nodeLen > 0) {
uint256 paid = nodePaid.mul(_rates[i - 1]).div(100).div(
_nodeLen
);
for (uint256 j = 0; j < _nodeLen; j++) {
Account storage user = accounts[nodes[i][j]];
user.reward = user.reward.add(paid);
}
}
}
}
/**
* @dev Transfer to the perpetual pool, only the administrator can call
*/
function activeSustainable(address next) public onlyOwner {
require(sustainable > 0);
uint256 paid = sustainable;
uint256 bal = usdt.balanceOf(address(this));
if (bal < paid) {
usdt.transfer(next, bal);
} else {
usdt.transfer(next, paid);
}
}
/**
* @dev Set static rate of return, only the administrator can call
*/
function setStaticRate(uint256 _rate) public onlyOwner {
require(_rate <= 1000);
staticRate = _rate;
}
/**
* @dev Set dynamic rate of return, only the administrator can call
*/
function setDynamicRates(uint8 level, uint256 _rate) public onlyOwner {
require(level < 12);
require(_rate <= 1000);
dynamicRates[level] = _rate;
}
/**
* @dev Set up the ticket contract, only the administrator can call
*/
function setTicket(ITicketsToken _ticket) public onlyOwner {
ticket = _ticket;
}
/**
* @dev Receive the technical founding team, only the administrator can call
*/
function takeFounder() public onlyOwner {
uint256 paid = founder;
founder = 0;
usdt.transfer(msg.sender, paid);
}
/**
* @dev Receive expansion operation fee, only the administrator can call
*/
function takeOperation() public onlyOwner {
uint256 paid = operation.add(dex);
operation = 0;
dex = 0;
usdt.transfer(msg.sender, paid);
}
}
|
Receive insurance pool rewards/ Total income statistics
|
function takeReward() public {
uint256 paid = accounts[msg.sender].reward;
accounts[msg.sender].reward = 0;
usdt.transfer(msg.sender, paid);
stats[msg.sender].income = stats[msg.sender].income.add(paid);
}
| 1,969,788 |
pragma solidity ^0.4.21;
/* ************************************************ */
/* ********** Zeppelin Solidity - v1.5.0 ********** */
/* ************************************************ */
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title 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) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* @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 Claimable
* @dev Extension for the Ownable contract, where the ownership needs to be claimed.
* This allows the new owner to accept the transfer.
*/
contract Claimable is Ownable {
address public pendingOwner;
/**
* @dev Modifier throws if called by any account other than the pendingOwner.
*/
modifier onlyPendingOwner() {
require(msg.sender == pendingOwner);
_;
}
/**
* @dev Allows the current owner to set the pendingOwner address.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner public {
pendingOwner = newOwner;
}
/**
* @dev Allows the pendingOwner address to finalize the transfer.
*/
function claimOwnership() onlyPendingOwner public {
OwnershipTransferred(owner, pendingOwner);
owner = pendingOwner;
pendingOwner = address(0);
}
}
/* *********************************** */
/* ********** Xmoneta Token ********** */
/* *********************************** */
/**
* @title XmonetaToken
* @author Xmoneta.com
*
* ERC20 Compatible token
* Zeppelin Solidity - v1.5.0
*/
contract XmonetaToken is StandardToken, Claimable {
/* ********** Token Predefined Information ********** */
string public constant name = "Xmoneta Token";
string public constant symbol = "XMN";
uint256 public constant decimals = 18;
/* ********** Defined Variables ********** */
// Total tokens supply 1 000 000 000
// For ethereum wallets we added decimals constant
uint256 public constant INITIAL_SUPPLY = 1000000000 * (10 ** decimals);
// Vault where tokens are stored
address public vault = msg.sender;
// Sales agent who has permissions to manipulate with tokens
address public salesAgent;
/* ********** Events ********** */
event SalesAgentAppointed(address indexed previousSalesAgent, address indexed newSalesAgent);
event SalesAgentRemoved(address indexed currentSalesAgent);
event Burn(uint256 valueToBurn);
/* ********** Functions ********** */
// Contract constructor
function XmonetaToken() public {
owner = msg.sender;
totalSupply = INITIAL_SUPPLY;
balances[vault] = totalSupply;
}
// Appoint sales agent of token
function setSalesAgent(address newSalesAgent) onlyOwner public {
SalesAgentAppointed(salesAgent, newSalesAgent);
salesAgent = newSalesAgent;
}
// Remove sales agent from token
function removeSalesAgent() onlyOwner public {
SalesAgentRemoved(salesAgent);
salesAgent = address(0);
}
// Transfer tokens from vault to account if sales agent is correct
function transferTokensFromVault(address fromAddress, address toAddress, uint256 tokensAmount) public {
require(salesAgent == msg.sender);
balances[vault] = balances[vault].sub(tokensAmount);
balances[toAddress] = balances[toAddress].add(tokensAmount);
Transfer(fromAddress, toAddress, tokensAmount);
}
// Allow the owner to burn a specific amount of tokens from the vault
function burn(uint256 valueToBurn) onlyOwner public {
require(valueToBurn > 0);
balances[vault] = balances[vault].sub(valueToBurn);
totalSupply = totalSupply.sub(valueToBurn);
Burn(valueToBurn);
}
}
/* ************************************** */
/* ************ Xmoneta Sale ************ */
/* ************************************** */
/**
* @title XmonetaSale
* @author Xmoneta.com
*
* Zeppelin Solidity - v1.5.0
*/
contract XmonetaSale {
using SafeMath for uint256;
/* ********** Defined Variables ********** */
// The token being sold
XmonetaToken public token;
// Crowdsale start timestamp - 03/13/2018 at 12:00pm (UTC)
uint256 public startTime = 1520942400;
// Crowdsale end timestamp - 05/31/2018 at 12:00pm (UTC)
uint256 public endTime = 1527768000;
// Addresses where ETH are collected
address public wallet1 = 0x36A3c000f8a3dC37FCD261D1844efAF851F81556;
address public wallet2 = 0x8beDBE45Aa345938d70388E381E2B6199A15B3C3;
// How many token per wei
uint256 public rate = 20000;
// Cap in ethers
uint256 public cap = 8000 * 1 ether;
// Amount of raised wei
uint256 public weiRaised;
// Round B start timestamp - 05/04/2018 at 12:00pm (UTC)
uint256 public round_b_begin_date = 1522929600;
// Round B start timestamp - 30/04/2018 at 12:00pm (UTC)
uint256 public round_c_begin_date = 1525089600;
/* ********** Events ********** */
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 weiAmount, uint256 tokens);
/* ********** Functions ********** */
// Contract constructor
function XmonetaSale() public {
token = XmonetaToken(0x99705A8B60d0fE21A4B8ee54DB361B3C573D18bb);
}
// Fallback function to buy tokens
function () public payable {
buyTokens(msg.sender);
}
// Bonus calculation for transaction
function bonus_calculation() internal returns (uint256, uint256) {
// Round A Standard bonus & Extra bonus
uint256 bonusPercent = 30;
uint256 extraBonusPercent = 50;
if (now >= round_c_begin_date) {
// Round C Standard bonus & Extra bonus
bonusPercent = 10;
extraBonusPercent = 30;
} else if (now >= round_b_begin_date) {
// Round B Standard bonus & Extra bonus
bonusPercent = 20;
extraBonusPercent = 40;
}
return (bonusPercent, extraBonusPercent);
}
// Token purchase function
function buyTokens(address beneficiary) public payable {
require(validPurchase());
uint256 weiAmount = msg.value;
// Send spare wei back if investor sent more that cap
uint256 tempWeiRaised = weiRaised.add(weiAmount);
if (tempWeiRaised > cap) {
uint256 spareWeis = tempWeiRaised.sub(cap);
weiAmount = weiAmount.sub(spareWeis);
beneficiary.transfer(spareWeis);
}
// Define standard and extra bonus variables
uint256 bonusPercent;
uint256 extraBonusPercent;
// Execute calculation
(bonusPercent, extraBonusPercent) = bonus_calculation();
// Accept extra bonus if beneficiary send more that 1 ETH
if (weiAmount >= 1 ether) {
bonusPercent = extraBonusPercent;
}
// Token calculations with bonus
uint256 additionalPercentInWei = rate.div(100).mul(bonusPercent);
uint256 rateWithPercents = rate.add(additionalPercentInWei);
// Calculate token amount to be sold
uint256 tokens = weiAmount.mul(rateWithPercents);
// Update state
weiRaised = weiRaised.add(weiAmount);
// Tranfer tokens from vault
token.transferTokensFromVault(msg.sender, beneficiary, tokens);
TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);
forwardFunds(weiAmount);
}
// Send wei to the fund collection wallets
function forwardFunds(uint256 weiAmount) internal {
uint256 value = weiAmount.div(2);
// If buyer send amount of wei that can not be divided to 2 without float point, send all weis to first wallet
if (value.mul(2) != weiAmount) {
wallet1.transfer(weiAmount);
} else {
wallet1.transfer(value);
wallet2.transfer(value);
}
}
// Validate if the transaction can be success
function validPurchase() internal constant returns (bool) {
bool withinCap = weiRaised < cap;
bool withinPeriod = now >= startTime && now <= endTime;
bool nonZeroPurchase = msg.value != 0;
return withinPeriod && nonZeroPurchase && withinCap;
}
// Show if crowdsale has ended or no
function hasEnded() public constant returns (bool) {
return now > endTime || weiRaised >= cap;
}
}
|
Show if crowdsale has ended or no
|
function hasEnded() public constant returns (bool) {
return now > endTime || weiRaised >= cap;
}
| 10,655,909 |
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../RLPReader/RLPReader.sol";
contract WModels {
using RLPReader for RLPReader.RLPItem;
using RLPReader for RLPReader.Iterator;
using RLPReader for bytes;
mapping (uint256 => mapping (bytes32 => FileDocument)) internal files;
mapping (uint256 => uint256) internal filesCount;
// Generic PersonaInfo model
struct PersonaInfo {
string fullName;
string did;
string url;
address ethereumAddress;
}
// Generic StepInfo Model
struct StepInfo {
address user;
address recipient;
bytes32 status;
}
// Generic DocumentInfoModel
struct DocumentInfo {
FileDocument[] files;
uint256 status;
}
struct FileDocument {
string contentType;
string path;
string hash;
}
function hasAttachedFiles(uint256 docId) public returns (bool) {
return filesCount[docId] > 0;
}
function addToFilesMapping(uint256 docId, bytes memory rlpBytes) internal {
RLPReader.RLPItem[] memory items = rlpBytes.toRlpItem().toList();
RLPReader.Iterator memory _files = items[1].iterator();
uint256 index = 0;
while (_files.hasNext()) {
RLPReader.RLPItem[] memory file = _files.next().toList();
bytes32 key = keccak256(abi.encodePacked(file[1].toBytes()));
files[docId][key] = FileDocument(
string(file[0].toBytes()),
string(file[1].toBytes()),
string(file[2].toBytes())
);
index++;
}
filesCount[docId] = index;
}
function updateFilesMapping(uint256 docId, bytes memory rlpBytes) internal {
RLPReader.RLPItem[] memory payload = rlpBytes.toRlpItem().toList();
RLPReader.Iterator memory _files = payload[1].toList()[1].iterator();
// uint256 index = 0;
while (_files.hasNext()) {
RLPReader.RLPItem[] memory file = _files.next().toList();
bytes32 key = keccak256(abi.encodePacked(file[1].toBytes()));
files[docId][key] = FileDocument(
string(file[0].toBytes()),
string(file[1].toBytes()),
string(file[2].toBytes())
);
// index++;
}
// filesCount[docId] = index;
}
// toStepInfo converts RLP to StepInfo struct
function toStepInfo(bytes memory payload) public returns (StepInfo memory) {
// address user;
// address recipient;
// bytes32 status;
RLPReader.RLPItem[] memory document = payload.toRlpItem().toList();
return StepInfo(
document[0].toAddress(),
document[1].toAddress(),
bytes32(document[2].toUint())
);
}
function toEmtpyStepInfo() public returns (StepInfo memory) {
return StepInfo(address(0),address(0), bytes32(0));
}
}
|
toStepInfo converts RLP to StepInfo struct address user; address recipient; bytes32 status;
|
function toStepInfo(bytes memory payload) public returns (StepInfo memory) {
RLPReader.RLPItem[] memory document = payload.toRlpItem().toList();
return StepInfo(
document[0].toAddress(),
document[1].toAddress(),
bytes32(document[2].toUint())
);
}
| 6,344,124 |
./full_match/73799/0xd19101eed20015c071707035412A01C0a6f5089C/sources/contracts/KnightVesting.sol
|
Calculates the total tokens that has been minted from IK token contract minus the burned tokens. burnedTokens are fetched from the IK token contract. return The total circulating supply./ if (burnedTokens > totalVestedTokens) return 0; should never be true
|
function circulatingSupply() external view returns (uint256) {
uint256 burnedTokens = _token.totalBurnedTokens();
if (burnedTokens > totalVestedTokens) {
return 0;
}
return (totalVestedTokens - burnedTokens);
}
| 16,363,978 |
./partial_match/5/0x8A0457f3dcf944D8bF8fDD77CAB9C20F71b055Df/sources/SharedDeposit.sol
|
addmin fee is in eth. i.e. 1 = 1eth
|
function setAdminFee(uint256 amount) external onlyOwner {
adminFee = amount;
costPerValidator = uint(32).add(adminFee);
}
| 16,850,517 |
/**
*Submitted for verification at Etherscan.io on 2022-01-04
*/
// SPDX-License-Identifier: MIT
// Amended by HashLips
/**
!Disclaimer!
These contracts have been used to create tutorials,
and was created for the purpose to teach people
how to create smart contracts on the blockchain.
please review this code on your own before using any of
the following code for production.
HashLips will not be liable in any way if for the use
of the code. That being said, the code has been tested
to the best of the developers' knowledge to work as intended.
*/
// 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: @openzeppelin/contracts/utils/introspection/ERC165.sol
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// File: @openzeppelin/contracts/utils/Strings.sol
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File: @openzeppelin/contracts/utils/Context.sol
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File: @openzeppelin/contracts/token/ERC721/ERC721.sol
pragma solidity ^0.8.0;
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol
pragma solidity ^0.8.0;
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
pragma solidity >=0.7.0 <0.9.0;
contract SamuraiTeaClub is ERC721Enumerable, Ownable {
using Strings for uint256;
string baseURI;
string public baseExtension = ".json";
uint256 public cost = 0.055 ether;
uint256 public maxSupply = 7999;
uint256 public maxMintAmount = 100;
bool public paused = true;
bool public revealed = false;
string public notRevealedUri;
constructor(
string memory _name,
string memory _symbol,
string memory _initBaseURI,
string memory _initNotRevealedUri
) ERC721(_name, _symbol) {
setBaseURI(_initBaseURI);
setNotRevealedURI(_initNotRevealedUri);
}
// internal
function _baseURI() internal view virtual override returns (string memory) {
return baseURI;
}
// public
function mint(uint256 _mintAmount) public payable {
uint256 supply = totalSupply();
require(!paused);
require(_mintAmount > 0);
require(_mintAmount <= maxMintAmount);
require(supply + _mintAmount <= maxSupply);
if (msg.sender != owner()) {
require(msg.value >= cost * _mintAmount);
}
for (uint256 i = 1; i <= _mintAmount; i++) {
_safeMint(msg.sender, supply + i);
}
}
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 tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
if(revealed == false) {
return notRevealedUri;
}
string memory currentBaseURI = _baseURI();
return bytes(currentBaseURI).length > 0
? string(abi.encodePacked(currentBaseURI, tokenId.toString(), baseExtension))
: "";
}
//only owner
function reveal() public onlyOwner() {
revealed = true;
}
function setCost(uint256 _newCost) public onlyOwner() {
cost = _newCost;
}
function setmaxMintAmount(uint256 _newmaxMintAmount) public onlyOwner() {
maxMintAmount = _newmaxMintAmount;
}
function setNotRevealedURI(string memory _notRevealedURI) public onlyOwner {
notRevealedUri = _notRevealedURI;
}
function setBaseURI(string memory _newBaseURI) public onlyOwner {
baseURI = _newBaseURI;
}
function setBaseExtension(string memory _newBaseExtension) public onlyOwner {
baseExtension = _newBaseExtension;
}
function pause(bool _state) public onlyOwner {
paused = _state;
}
function withdraw() public payable onlyOwner {
(bool success, ) = payable(msg.sender).call{value: address(this).balance}("");
require(success);
}
}
|
Destroys `tokenId`. The approval is cleared when the token is burned. Requirements: - `tokenId` must exist. Emits a {Transfer} event./ Clear approvals
|
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
| 6,804,170 |
// SPDX-License-Identifier: MIT
// pragma solidity ^0.4.18;
// pragma solidity ^0.4.25;
// pragma solidity ^0.5.1;
// pragma solidity ^0.6.0;
pragma solidity ^0.6.0;
import "./SafeMath.sol";
import "./Crowdsale.sol";
import "@nomiclabs/buidler/console.sol";
/**
* @title WhitelistedCrowdsale
* @dev Extension of Crowsdale with a whitelist of investors that
* can buy before the start block
*/
abstract contract WhitelistedCrowdsale is Crowdsale {
using SafeMath for uint256;
mapping (address => bool) public whitelist;
function addToWhitelist(address addr) public {
require(msg.sender != address(this));
whitelist[addr] = true;
}
// overriding Crowdsale#validPurchase to add extra whitelit logic
// @return true if investors can buy at the moment
function validPurchase() internal view override virtual returns (bool) {
console.log("WhitelistedCrowdsale.sol::validPurchase");
return super.validPurchase() || (whitelist[msg.sender] && !hasEnded());
}
}
|
overriding CrowdsalevalidPurchase to add extra whitelit logic return true if investors can buy at the moment
|
function validPurchase() internal view override virtual returns (bool) {
console.log("WhitelistedCrowdsale.sol::validPurchase");
return super.validPurchase() || (whitelist[msg.sender] && !hasEnded());
}
| 1,076,233 |
//Address: 0x0f6029ebde2ecd9ab4d60dd5d0a297e9e59bf77a
//Contract name: ADXExchange
//Balance: 0 Ether
//Verification Date: 11/16/2017
//Transacion Count: 34
// CODE STARTS HERE
pragma solidity ^0.4.15;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
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) onlyOwner {
if (newOwner != address(0)) {
owner = newOwner;
}
}
}
/**
* @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 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);
}
contract Drainable is Ownable {
function withdrawToken(address tokenaddr)
onlyOwner
{
ERC20 token = ERC20(tokenaddr);
uint bal = token.balanceOf(address(this));
token.transfer(msg.sender, bal);
}
function withdrawEther()
onlyOwner
{
require(msg.sender.send(this.balance));
}
}
contract ADXRegistry is Ownable, Drainable {
string public name = "AdEx Registry";
// Structure:
// AdUnit (advertiser) - a unit of a single advertisement
// AdSlot (publisher) - a particular property (slot) that can display an ad unit
// Campaign (advertiser) - group of ad units ; not vital
// Channel (publisher) - group of properties ; not vital
// Each Account is linked to all the items they own through the Account struct
mapping (address => Account) public accounts;
// XXX: mostly unused, because solidity does not allow mapping with enum as primary type.. :( we just use uint
enum ItemType { AdUnit, AdSlot, Campaign, Channel }
// uint here corresponds to the ItemType
mapping (uint => uint) public counts;
mapping (uint => mapping (uint => Item)) public items;
// Publisher or Advertiser (could be both)
struct Account {
address addr;
address wallet;
bytes32 ipfs; // ipfs addr for additional (larger) meta
bytes32 name; // name
bytes32 meta; // metadata, can be JSON, can be other format, depends on the high-level implementation
bytes32 signature; // signature in the off-blockchain state channel
// Items, by type, then in an array of numeric IDs
mapping (uint => uint[]) items;
}
// Sub-item, such as AdUnit, AdSlot, Campaign, Channel
struct Item {
uint id;
address owner;
ItemType itemType;
bytes32 ipfs; // ipfs addr for additional (larger) meta
bytes32 name; // name
bytes32 meta; // metadata, can be JSON, can be other format, depends on the high-level implementation
}
modifier onlyRegistered() {
var acc = accounts[msg.sender];
require(acc.addr != 0);
_;
}
// can be called over and over to update the data
// XXX consider entrance barrier, such as locking in some ADX
function register(bytes32 _name, address _wallet, bytes32 _ipfs, bytes32 _sig, bytes32 _meta)
external
{
require(_wallet != 0);
// XXX should we ensure _sig is not 0? if so, also add test
require(_name != 0);
var isNew = accounts[msg.sender].addr == 0;
var acc = accounts[msg.sender];
if (!isNew) require(acc.signature == _sig);
else acc.signature = _sig;
acc.addr = msg.sender;
acc.wallet = _wallet;
acc.ipfs = _ipfs;
acc.name = _name;
acc.meta = _meta;
if (isNew) LogAccountRegistered(acc.addr, acc.wallet, acc.ipfs, acc.name, acc.meta, acc.signature);
else LogAccountModified(acc.addr, acc.wallet, acc.ipfs, acc.name, acc.meta, acc.signature);
}
// use _id = 0 to create a new item, otherwise modify existing
function registerItem(uint _type, uint _id, bytes32 _ipfs, bytes32 _name, bytes32 _meta)
onlyRegistered
{
// XXX _type sanity check?
var item = items[_type][_id];
if (_id != 0)
require(item.owner == msg.sender);
else {
// XXX: what about overflow here?
var newId = ++counts[_type];
item = items[_type][newId];
item.id = newId;
item.itemType = ItemType(_type);
item.owner = msg.sender;
accounts[msg.sender].items[_type].push(item.id);
}
item.name = _name;
item.meta = _meta;
item.ipfs = _ipfs;
if (_id == 0) LogItemRegistered(
item.owner, uint(item.itemType), item.id, item.ipfs, item.name, item.meta
);
else LogItemModified(
item.owner, uint(item.itemType), item.id, item.ipfs, item.name, item.meta
);
}
// NOTE
// There's no real point of un-registering items
// Campaigns need to be kept anyway, as well as ad units
// END NOTE
//
// Constant functions
//
function isRegistered(address who)
public
constant
returns (bool)
{
var acc = accounts[who];
return acc.addr != 0;
}
// Functions exposed for web3 interface
// NOTE: this is sticking to the policy of keeping static-sized values at the left side of tuples
function getAccount(address _acc)
constant
public
returns (address, bytes32, bytes32, bytes32)
{
var acc = accounts[_acc];
require(acc.addr != 0);
return (acc.wallet, acc.ipfs, acc.name, acc.meta);
}
function getAccountItems(address _acc, uint _type)
constant
public
returns (uint[])
{
var acc = accounts[_acc];
require(acc.addr != 0);
return acc.items[_type];
}
function getItem(uint _type, uint _id)
constant
public
returns (address, bytes32, bytes32, bytes32)
{
var item = items[_type][_id];
require(item.id != 0);
return (item.owner, item.ipfs, item.name, item.meta);
}
function hasItem(uint _type, uint _id)
constant
public
returns (bool)
{
var item = items[_type][_id];
return item.id != 0;
}
// Events
event LogAccountRegistered(address addr, address wallet, bytes32 ipfs, bytes32 accountName, bytes32 meta, bytes32 signature);
event LogAccountModified(address addr, address wallet, bytes32 ipfs, bytes32 accountName, bytes32 meta, bytes32 signature);
event LogItemRegistered(address owner, uint itemType, uint id, bytes32 ipfs, bytes32 itemName, bytes32 meta);
event LogItemModified(address owner, uint itemType, uint id, bytes32 ipfs, bytes32 itemName, bytes32 meta);
}
contract ADXExchange is Ownable, Drainable {
string public name = "AdEx Exchange";
ERC20 public token;
ADXRegistry public registry;
uint public bidsCount;
mapping (uint => Bid) bidsById;
mapping (uint => uint[]) bidsByAdunit; // bids set out by ad unit
mapping (uint => uint[]) bidsByAdslot; // accepted by publisher, by ad slot
// TODO: some properties in the bid structure - achievedPoints/peers for example - are not used atm
// CONSIDER: the bid having a adunitType so that this can be filtered out
// WHY IT'S NOT IMPORTANT: you can get bids by ad units / ad slots, which is filter enough already considering we know their types
// CONSIDER: locking ad units / ad slots or certain properties from them so that bids cannot be ruined by editing them
// WHY IT'S NOT IMPORTANT: from a game theoretical point of view there's no incentive to do that
// corresponds to enum types in ADXRegistry
uint constant ADUNIT = 0;
uint constant ADSLOT = 1;
enum BidState {
Open,
Accepted, // in progress
// the following states MUST unlock the ADX amount (return to advertiser)
// fail states
Canceled,
Expired,
// success states
Completed,
Claimed
}
struct Bid {
uint id;
BidState state;
// ADX reward amount
uint amount;
// Links on advertiser side
address advertiser;
address advertiserWallet;
uint adUnit;
bytes32 adUnitIpfs;
bytes32 advertiserPeer;
// Links on publisher side
address publisher;
address publisherWallet;
uint adSlot;
bytes32 adSlotIpfs;
bytes32 publisherPeer;
uint acceptedTime; // when was it accepted by a publisher
// Requirements
//RequirementType type;
uint requiredPoints; // how many impressions/clicks/conversions have to be done
uint requiredExecTime; // essentially a timeout
// Results
bool confirmedByPublisher;
bool confirmedByAdvertiser;
// IPFS links to result reports
bytes32 publisherReportIpfs;
bytes32 advertiserReportIpfs;
}
//
// MODIFIERS
//
modifier onlyRegisteredAcc() {
require(registry.isRegistered(msg.sender));
_;
}
modifier onlyBidOwner(uint _bidId) {
require(msg.sender == bidsById[_bidId].advertiser);
_;
}
modifier onlyBidAceptee(uint _bidId) {
require(msg.sender == bidsById[_bidId].publisher);
_;
}
modifier onlyBidState(uint _bidId, BidState _state) {
require(bidsById[_bidId].id != 0);
require(bidsById[_bidId].state == _state);
_;
}
modifier onlyExistingBid(uint _bidId) {
require(bidsById[_bidId].id != 0);
_;
}
// Functions
function ADXExchange(address _token, address _registry)
{
token = ERC20(_token);
registry = ADXRegistry(_registry);
}
//
// Bid actions
//
// the bid is placed by the advertiser
function placeBid(uint _adunitId, uint _target, uint _rewardAmount, uint _timeout, bytes32 _peer)
onlyRegisteredAcc
{
bytes32 adIpfs;
address advertiser;
address advertiserWallet;
// NOTE: those will throw if the ad or respectively the account do not exist
(advertiser,adIpfs,,) = registry.getItem(ADUNIT, _adunitId);
(advertiserWallet,,,) = registry.getAccount(advertiser);
// XXX: maybe it could be a feature to allow advertisers bidding on other advertisers' ad units, but it will complicate things...
require(advertiser == msg.sender);
Bid memory bid;
bid.id = ++bidsCount; // start from 1, so that 0 is not a valid ID
bid.state = BidState.Open; // XXX redundant, but done for code clarity
bid.amount = _rewardAmount;
bid.advertiser = advertiser;
bid.advertiserWallet = advertiserWallet;
bid.adUnit = _adunitId;
bid.adUnitIpfs = adIpfs;
bid.requiredPoints = _target;
bid.requiredExecTime = _timeout;
bid.advertiserPeer = _peer;
bidsById[bid.id] = bid;
bidsByAdunit[_adunitId].push(bid.id);
require(token.transferFrom(advertiserWallet, address(this), _rewardAmount));
LogBidOpened(bid.id, advertiser, _adunitId, adIpfs, _target, _rewardAmount, _timeout, _peer);
}
// the bid is canceled by the advertiser
function cancelBid(uint _bidId)
onlyRegisteredAcc
onlyExistingBid(_bidId)
onlyBidOwner(_bidId)
onlyBidState(_bidId, BidState.Open)
{
Bid storage bid = bidsById[_bidId];
bid.state = BidState.Canceled;
require(token.transfer(bid.advertiserWallet, bid.amount));
LogBidCanceled(bid.id);
}
// a bid is accepted by a publisher for a given ad slot
function acceptBid(uint _bidId, uint _slotId, bytes32 _peer)
onlyRegisteredAcc
onlyExistingBid(_bidId)
onlyBidState(_bidId, BidState.Open)
{
address publisher;
address publisherWallet;
bytes32 adSlotIpfs;
// NOTE: those will throw if the ad slot or respectively the account do not exist
(publisher,adSlotIpfs,,) = registry.getItem(ADSLOT, _slotId);
(publisherWallet,,,) = registry.getAccount(publisher);
require(publisher == msg.sender);
Bid storage bid = bidsById[_bidId];
// should not happen when bid.state is BidState.Open, but just in case
require(bid.publisher == 0);
bid.state = BidState.Accepted;
bid.publisher = publisher;
bid.publisherWallet = publisherWallet;
bid.adSlot = _slotId;
bid.adSlotIpfs = adSlotIpfs;
bid.publisherPeer = _peer;
bid.acceptedTime = now;
bidsByAdslot[_slotId].push(_bidId);
LogBidAccepted(bid.id, publisher, _slotId, adSlotIpfs, bid.acceptedTime, bid.publisherPeer);
}
// the bid is given up by the publisher, therefore canceling it and returning the funds to the advertiser
// same logic as cancelBid(), but different permissions
function giveupBid(uint _bidId)
onlyRegisteredAcc
onlyExistingBid(_bidId)
onlyBidAceptee(_bidId)
onlyBidState(_bidId, BidState.Accepted)
{
var bid = bidsById[_bidId];
bid.state = BidState.Canceled;
require(token.transfer(bid.advertiserWallet, bid.amount));
LogBidCanceled(bid.id);
}
// both publisher and advertiser have to call this for a bid to be considered verified
function verifyBid(uint _bidId, bytes32 _report)
onlyRegisteredAcc
onlyExistingBid(_bidId)
onlyBidState(_bidId, BidState.Accepted)
{
Bid storage bid = bidsById[_bidId];
require(bid.publisher == msg.sender || bid.advertiser == msg.sender);
if (bid.publisher == msg.sender) {
bid.confirmedByPublisher = true;
bid.publisherReportIpfs = _report;
}
if (bid.advertiser == msg.sender) {
bid.confirmedByAdvertiser = true;
bid.advertiserReportIpfs = _report;
}
if (bid.confirmedByAdvertiser && bid.confirmedByPublisher) {
bid.state = BidState.Completed;
LogBidCompleted(bid.id, bid.advertiserReportIpfs, bid.publisherReportIpfs);
}
}
// now, claim the reward; callable by the publisher;
// claimBidReward is a separate function so as to define clearly who pays the gas for transfering the reward
function claimBidReward(uint _bidId)
onlyRegisteredAcc
onlyExistingBid(_bidId)
onlyBidAceptee(_bidId)
onlyBidState(_bidId, BidState.Completed)
{
Bid storage bid = bidsById[_bidId];
bid.state = BidState.Claimed;
require(token.transfer(bid.publisherWallet, bid.amount));
LogBidRewardClaimed(bid.id, bid.publisherWallet, bid.amount);
}
// This can be done if a bid is accepted, but expired
// This is essentially the protection from never settling on verification, or from publisher not executing the bid within a reasonable time
function refundBid(uint _bidId)
onlyRegisteredAcc
onlyExistingBid(_bidId)
onlyBidOwner(_bidId)
onlyBidState(_bidId, BidState.Accepted)
{
Bid storage bid = bidsById[_bidId];
require(bid.requiredExecTime > 0); // you can't refund if you haven't set a timeout
require(SafeMath.add(bid.acceptedTime, bid.requiredExecTime) < now);
bid.state = BidState.Expired;
require(token.transfer(bid.advertiserWallet, bid.amount));
LogBidExpired(bid.id);
}
//
// Public constant functions
//
function getBidsFromArr(uint[] arr, uint _state)
internal
returns (uint[] _all)
{
BidState state = BidState(_state);
// separate array is needed because of solidity stupidity (pun intended ))) )
uint[] memory all = new uint[](arr.length);
uint count = 0;
uint i;
for (i = 0; i < arr.length; i++) {
var id = arr[i];
var bid = bidsById[id];
if (bid.state == state) {
all[count] = id;
count += 1;
}
}
_all = new uint[](count);
for (i = 0; i < count; i++) _all[i] = all[i];
}
function getAllBidsByAdunit(uint _adunitId)
constant
external
returns (uint[])
{
return bidsByAdunit[_adunitId];
}
function getBidsByAdunit(uint _adunitId, uint _state)
constant
external
returns (uint[])
{
return getBidsFromArr(bidsByAdunit[_adunitId], _state);
}
function getAllBidsByAdslot(uint _adslotId)
constant
external
returns (uint[])
{
return bidsByAdslot[_adslotId];
}
function getBidsByAdslot(uint _adslotId, uint _state)
constant
external
returns (uint[])
{
return getBidsFromArr(bidsByAdslot[_adslotId], _state);
}
function getBid(uint _bidId)
onlyExistingBid(_bidId)
constant
external
returns (
uint, uint, uint, uint, uint,
// advertiser (ad unit, ipfs, peer)
uint, bytes32, bytes32,
// publisher (ad slot, ipfs, peer)
uint, bytes32, bytes32
)
{
var bid = bidsById[_bidId];
return (
uint(bid.state), bid.requiredPoints, bid.requiredExecTime, bid.amount, bid.acceptedTime,
bid.adUnit, bid.adUnitIpfs, bid.advertiserPeer,
bid.adSlot, bid.adSlotIpfs, bid.publisherPeer
);
}
function getBidReports(uint _bidId)
onlyExistingBid(_bidId)
constant
external
returns (
bytes32, // advertiser report
bytes32 // publisher report
)
{
var bid = bidsById[_bidId];
return (bid.advertiserReportIpfs, bid.publisherReportIpfs);
}
//
// Events
//
event LogBidOpened(uint bidId, address advertiser, uint adunitId, bytes32 adunitIpfs, uint target, uint rewardAmount, uint timeout, bytes32 advertiserPeer);
event LogBidAccepted(uint bidId, address publisher, uint adslotId, bytes32 adslotIpfs, uint acceptedTime, bytes32 publisherPeer);
event LogBidCanceled(uint bidId);
event LogBidExpired(uint bidId);
event LogBidCompleted(uint bidId, bytes32 advReport, bytes32 pubReport);
event LogBidRewardClaimed(uint _bidId, address _wallet, uint _amount);
}
|
now, claim the reward; callable by the publisher; claimBidReward is a separate function so as to define clearly who pays the gas for transfering the reward
|
function claimBidReward(uint _bidId)
onlyRegisteredAcc
onlyExistingBid(_bidId)
onlyBidAceptee(_bidId)
onlyBidState(_bidId, BidState.Completed)
{
Bid storage bid = bidsById[_bidId];
bid.state = BidState.Claimed;
require(token.transfer(bid.publisherWallet, bid.amount));
LogBidRewardClaimed(bid.id, bid.publisherWallet, bid.amount);
}
| 6,398,716 |
pragma solidity ^0.5.8;
import "./erc20.sol";
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract ERC20Burnable is ERC20 {
/**
* @dev Burns a specific amount of tokens.
* @param value The amount of token to be burned.
*/
function burn(uint256 value) external {
_burn(msg.sender, value);
}
/**
* @dev Burns a specific amount of tokens from the target address and decrements allowance.
* @param from address The account whose tokens will be burned.
* @param value uint256 The amount of token to be burned.
*/
function burnFrom(address from, uint256 value) external {
_burnFrom(from, value);
}
}
pragma solidity ^0.5.8;
import "./safemath.sol";
import "./ierc20.sol";
/**
* @title Standard ERC20 token
** @dev Implementation of the basic standard token.
* https://eips.ethereum.org/EIPS/eip-20
* Originally based on code by FirstBlood:
* https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
** This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for
* all accounts just by listening to said events. Note that this isn't required by the specification, and other
* compliant implementations may not do it.
*/
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() external view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return A uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) external 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) external view returns (uint256) {
return _allowed[owner][spender];
}
/**
* @dev Transfer token to a specified address.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) external returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value) public returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* Note that while this function emits an Approval event, this is not required as per the specification,
* and other compliant implementations may not emit the event.
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(address from, address to, uint256 value) external returns (bool) {
_transfer(from, to, value);
_approve(from, msg.sender, _allowed[from][msg.sender].sub(value));
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue) external returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue));
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue));
return true;
}
/**
* @dev Transfer token for a specified addresses.
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0), "ERC20: transfer to the zero address");
require(_balances[from]>=value, "ERC20 transfer: not enough tokens");
_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), "ERC20: mint to the zero address");
_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), "ERC20: burn from the zero address");
require(_balances[account] >= value, "Burn: not enough tokens");
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Approve an address to spend another addresses' tokens.
* @param owner The address that owns the tokens.
* @param spender The address that will spend the tokens.
* @param value The number of tokens that can be spent.
*/
function _approve(address owner, address spender, uint256 value) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowed[owner][spender] = value;
emit Approval(owner, spender, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* Emits an Approval event (reflecting the reduced allowance).
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
require(_allowed[account][msg.sender]>=value, "Burn: allowance too low");
_burn(account, value);
_approve(account, msg.sender, _allowed[account][msg.sender].sub(value));
}
}
pragma solidity ^0.5.8;
/**
* @title ERC20 interface
* @dev see https://eips.ethereum.org/EIPS/eip-20
*/
interface IERC20 {
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
pragma solidity ^0.5.8;
/**
* @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;
address public newOwner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public view returns (bool) {
return msg.sender == owner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
* @notice Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() external onlyOwner {
emit OwnershipTransferred(owner, address(0));
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) external onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() public{
require (newOwner == msg.sender, "Ownable: only new Owner can accept");
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
pragma solidity ^0.5.7;
/**
* @title SafeMath
* @dev Unsigned math operations with safety checks that revert on error.
*/
library SafeMath {
/**
* @dev Multiplies two unsigned integers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "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 Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
uint256 c = a - b;
return c;
}
/**
* @dev Adds two unsigned integers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
pragma solidity ^0.5.8;
import "./erc20.sol";
import "./ownable.sol";
contract Timelocks is ERC20, Ownable{
uint public lockedBalance;
struct Locker {
uint amount;
uint locktime;
}
mapping(address => Locker[]) timeLocks;
/**
* @dev function that lock tokens held by contract. Tokens can be unlocked and send to user after fime pass
* @param lockTimestamp timestamp after whih coins can be unlocked
* @param amount amount of tokens to lock
* @param user address of uset that cn unlock and posess tokens
*/
function lock(uint lockTimestamp, uint amount, address user) external onlyOwner {
_lock(lockTimestamp, amount, user);
}
function _lock(uint lockTimestamp, uint amount, address user) internal{
uint current = _balances[address(this)];
require(amount <= current.sub(lockedBalance), "Lock: Not enough tokens");
lockedBalance = lockedBalance.add(amount);
timeLocks[user].push(Locker(amount, lockTimestamp));
}
/**
* @dev Function to unlock timelocked tokens
* If block.timestap passed tokens are sent to owner and lock is removed from database
*/
function unlock() external
{
require(timeLocks[msg.sender].length > 0, "Unlock: No locks!");
Locker[] storage l = timeLocks[msg.sender];
for (uint i = 0; i < l.length; i++)
{
if (l[i].locktime < block.timestamp) {
uint amount = l[i].amount;
require(amount <= lockedBalance && amount <= _balances[address(this)], "Unlock: Not enough coins on contract!");
lockedBalance = lockedBalance.sub(amount);
_transfer(address(this), msg.sender, amount);
for (uint j = i; j < l.length - 1; j++)
{
l[j] = l[j + 1];
}
l.length--;
i--;
}
}
}
/**
* @dev Function to check how many locks are on caller account
* We need it because (for now) contract can not retrurn array of structs
* @return number of timelocked locks
*/
function locks() external view returns(uint)
{
return _locks(msg.sender);
}
/**
* @dev Function to check timelocks of any user
* @param user addres of user
* @return nuber of locks
*/
function locksOf(address user) external view returns(uint) {
return _locks(user);
}
function _locks(address user) internal view returns(uint){
return timeLocks[user].length;
}
/**
* @dev Function to check given timeLock
* @param num number of timeLock
* @return amount locked
* @return timestamp after whih coins can be unlocked
*/
function showLock(uint num) external view returns(uint, uint)
{
return _showLock(msg.sender, num);
}
/**
* @dev Function to show timeLock of any user
* @param user address of user
* @param num number of lock
* @return amount locked
* @return timestamp after whih can be unlocked
*/
function showLockOf(address user, uint num) external view returns(uint, uint) {
return _showLock(user, num);
}
function _showLock(address user, uint num) internal view returns(uint, uint) {
require(timeLocks[user].length > 0, "ShowLock: No locks!");
require(num < timeLocks[user].length, "ShowLock: Index over number of locks.");
Locker[] storage l = timeLocks[user];
return (l[num].amount, l[num].locktime);
}
}
pragma solidity ^0.5.8;
import "./ierc20.sol";
import "./safemath.sol";
import "./erc20.sol";
import "./burnable.sol";
import "./ownable.sol";
import "./timelocks.sol";
contract ContractFallbacks {
function receiveApproval(address from, uint256 _amount, address _token, bytes memory _data) public;
function onTokenTransfer(address from, uint256 amount, bytes memory data) public returns (bool success);
}
contract Wolfs is IERC20, ERC20, ERC20Burnable, Ownable, Timelocks {
using SafeMath for uint256;
string public name;
string public symbol;
uint8 public decimals;
/**
* @dev Token constructor
*/
constructor () public {
name = "Wolfs Group AG";
symbol = "WLF";
decimals = 0;
owner = 0x7fd429DBb710674614A35e967788Fa3e23A5c1C9;
emit OwnershipTransferred(address(0), owner);
_mint(0xc7eEef150818b5D3301cc93a965195F449603805, 15000000);
_mint(0x7fd429DBb710674614A35e967788Fa3e23A5c1C9, 135000000);
}
/**
* @dev function that allow to approve for transfer and call contract in one transaction
* @param _spender contract address
* @param _amount amount of tokens
* @param _extraData optional encoded data to send to contract
* @return True if function call was succesfull
*/
function approveAndCall(address _spender, uint256 _amount, bytes calldata _extraData) external returns (bool success)
{
require(approve(_spender, _amount), "ERC20: Approve unsuccesfull");
ContractFallbacks(_spender).receiveApproval(msg.sender, _amount, address(this), _extraData);
return true;
}
/**
* @dev function that transer tokens to diven address and call function on that address
* @param _to address to send tokens and call
* @param _value amount of tokens
* @param _data optional extra data to process in calling contract
* @return success True if all succedd
*/
function transferAndCall(address _to, uint _value, bytes calldata _data) external returns (bool success)
{
_transfer(msg.sender, _to, _value);
ContractFallbacks(_to).onTokenTransfer(msg.sender, _value, _data);
return true;
}
}
pragma solidity ^0.5.8;
import "./erc20.sol";
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract ERC20Burnable is ERC20 {
/**
* @dev Burns a specific amount of tokens.
* @param value The amount of token to be burned.
*/
function burn(uint256 value) external {
_burn(msg.sender, value);
}
/**
* @dev Burns a specific amount of tokens from the target address and decrements allowance.
* @param from address The account whose tokens will be burned.
* @param value uint256 The amount of token to be burned.
*/
function burnFrom(address from, uint256 value) external {
_burnFrom(from, value);
}
}
pragma solidity ^0.5.8;
import "./safemath.sol";
import "./ierc20.sol";
/**
* @title Standard ERC20 token
** @dev Implementation of the basic standard token.
* https://eips.ethereum.org/EIPS/eip-20
* Originally based on code by FirstBlood:
* https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
** This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for
* all accounts just by listening to said events. Note that this isn't required by the specification, and other
* compliant implementations may not do it.
*/
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() external view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return A uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) external 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) external view returns (uint256) {
return _allowed[owner][spender];
}
/**
* @dev Transfer token to a specified address.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) external returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value) public returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* Note that while this function emits an Approval event, this is not required as per the specification,
* and other compliant implementations may not emit the event.
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(address from, address to, uint256 value) external returns (bool) {
_transfer(from, to, value);
_approve(from, msg.sender, _allowed[from][msg.sender].sub(value));
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue) external returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue));
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue));
return true;
}
/**
* @dev Transfer token for a specified addresses.
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0), "ERC20: transfer to the zero address");
require(_balances[from]>=value, "ERC20 transfer: not enough tokens");
_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), "ERC20: mint to the zero address");
_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), "ERC20: burn from the zero address");
require(_balances[account] >= value, "Burn: not enough tokens");
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Approve an address to spend another addresses' tokens.
* @param owner The address that owns the tokens.
* @param spender The address that will spend the tokens.
* @param value The number of tokens that can be spent.
*/
function _approve(address owner, address spender, uint256 value) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowed[owner][spender] = value;
emit Approval(owner, spender, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* Emits an Approval event (reflecting the reduced allowance).
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
require(_allowed[account][msg.sender]>=value, "Burn: allowance too low");
_burn(account, value);
_approve(account, msg.sender, _allowed[account][msg.sender].sub(value));
}
}
pragma solidity ^0.5.8;
/**
* @title ERC20 interface
* @dev see https://eips.ethereum.org/EIPS/eip-20
*/
interface IERC20 {
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
pragma solidity ^0.5.8;
/**
* @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;
address public newOwner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public view returns (bool) {
return msg.sender == owner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
* @notice Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() external onlyOwner {
emit OwnershipTransferred(owner, address(0));
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) external onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() public{
require (newOwner == msg.sender, "Ownable: only new Owner can accept");
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
pragma solidity ^0.5.7;
/**
* @title SafeMath
* @dev Unsigned math operations with safety checks that revert on error.
*/
library SafeMath {
/**
* @dev Multiplies two unsigned integers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "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 Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
uint256 c = a - b;
return c;
}
/**
* @dev Adds two unsigned integers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
pragma solidity ^0.5.8;
import "./erc20.sol";
import "./ownable.sol";
contract Timelocks is ERC20, Ownable{
uint public lockedBalance;
struct Locker {
uint amount;
uint locktime;
}
mapping(address => Locker[]) timeLocks;
/**
* @dev function that lock tokens held by contract. Tokens can be unlocked and send to user after fime pass
* @param lockTimestamp timestamp after whih coins can be unlocked
* @param amount amount of tokens to lock
* @param user address of uset that cn unlock and posess tokens
*/
function lock(uint lockTimestamp, uint amount, address user) external onlyOwner {
_lock(lockTimestamp, amount, user);
}
function _lock(uint lockTimestamp, uint amount, address user) internal{
uint current = _balances[address(this)];
require(amount <= current.sub(lockedBalance), "Lock: Not enough tokens");
lockedBalance = lockedBalance.add(amount);
timeLocks[user].push(Locker(amount, lockTimestamp));
}
/**
* @dev Function to unlock timelocked tokens
* If block.timestap passed tokens are sent to owner and lock is removed from database
*/
function unlock() external
{
require(timeLocks[msg.sender].length > 0, "Unlock: No locks!");
Locker[] storage l = timeLocks[msg.sender];
for (uint i = 0; i < l.length; i++)
{
if (l[i].locktime < block.timestamp) {
uint amount = l[i].amount;
require(amount <= lockedBalance && amount <= _balances[address(this)], "Unlock: Not enough coins on contract!");
lockedBalance = lockedBalance.sub(amount);
_transfer(address(this), msg.sender, amount);
for (uint j = i; j < l.length - 1; j++)
{
l[j] = l[j + 1];
}
l.length--;
i--;
}
}
}
/**
* @dev Function to check how many locks are on caller account
* We need it because (for now) contract can not retrurn array of structs
* @return number of timelocked locks
*/
function locks() external view returns(uint)
{
return _locks(msg.sender);
}
/**
* @dev Function to check timelocks of any user
* @param user addres of user
* @return nuber of locks
*/
function locksOf(address user) external view returns(uint) {
return _locks(user);
}
function _locks(address user) internal view returns(uint){
return timeLocks[user].length;
}
/**
* @dev Function to check given timeLock
* @param num number of timeLock
* @return amount locked
* @return timestamp after whih coins can be unlocked
*/
function showLock(uint num) external view returns(uint, uint)
{
return _showLock(msg.sender, num);
}
/**
* @dev Function to show timeLock of any user
* @param user address of user
* @param num number of lock
* @return amount locked
* @return timestamp after whih can be unlocked
*/
function showLockOf(address user, uint num) external view returns(uint, uint) {
return _showLock(user, num);
}
function _showLock(address user, uint num) internal view returns(uint, uint) {
require(timeLocks[user].length > 0, "ShowLock: No locks!");
require(num < timeLocks[user].length, "ShowLock: Index over number of locks.");
Locker[] storage l = timeLocks[user];
return (l[num].amount, l[num].locktime);
}
}
pragma solidity ^0.5.8;
import "./ierc20.sol";
import "./safemath.sol";
import "./erc20.sol";
import "./burnable.sol";
import "./ownable.sol";
import "./timelocks.sol";
contract ContractFallbacks {
function receiveApproval(address from, uint256 _amount, address _token, bytes memory _data) public;
function onTokenTransfer(address from, uint256 amount, bytes memory data) public returns (bool success);
}
contract Wolfs is IERC20, ERC20, ERC20Burnable, Ownable, Timelocks {
using SafeMath for uint256;
string public name;
string public symbol;
uint8 public decimals;
/**
* @dev Token constructor
*/
constructor () public {
name = "Wolfs Group AG";
symbol = "WLF";
decimals = 0;
owner = 0x7fd429DBb710674614A35e967788Fa3e23A5c1C9;
emit OwnershipTransferred(address(0), owner);
_mint(0xc7eEef150818b5D3301cc93a965195F449603805, 15000000);
_mint(0x7fd429DBb710674614A35e967788Fa3e23A5c1C9, 135000000);
}
/**
* @dev function that allow to approve for transfer and call contract in one transaction
* @param _spender contract address
* @param _amount amount of tokens
* @param _extraData optional encoded data to send to contract
* @return True if function call was succesfull
*/
function approveAndCall(address _spender, uint256 _amount, bytes calldata _extraData) external returns (bool success)
{
require(approve(_spender, _amount), "ERC20: Approve unsuccesfull");
ContractFallbacks(_spender).receiveApproval(msg.sender, _amount, address(this), _extraData);
return true;
}
/**
* @dev function that transer tokens to diven address and call function on that address
* @param _to address to send tokens and call
* @param _value amount of tokens
* @param _data optional extra data to process in calling contract
* @return success True if all succedd
*/
function transferAndCall(address _to, uint _value, bytes calldata _data) external returns (bool success)
{
_transfer(msg.sender, _to, _value);
ContractFallbacks(_to).onTokenTransfer(msg.sender, _value, _data);
return true;
}
}
pragma solidity ^0.5.8;
import "./erc20.sol";
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract ERC20Burnable is ERC20 {
/**
* @dev Burns a specific amount of tokens.
* @param value The amount of token to be burned.
*/
function burn(uint256 value) external {
_burn(msg.sender, value);
}
/**
* @dev Burns a specific amount of tokens from the target address and decrements allowance.
* @param from address The account whose tokens will be burned.
* @param value uint256 The amount of token to be burned.
*/
function burnFrom(address from, uint256 value) external {
_burnFrom(from, value);
}
}
pragma solidity ^0.5.8;
import "./safemath.sol";
import "./ierc20.sol";
/**
* @title Standard ERC20 token
** @dev Implementation of the basic standard token.
* https://eips.ethereum.org/EIPS/eip-20
* Originally based on code by FirstBlood:
* https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
** This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for
* all accounts just by listening to said events. Note that this isn't required by the specification, and other
* compliant implementations may not do it.
*/
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() external view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return A uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) external 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) external view returns (uint256) {
return _allowed[owner][spender];
}
/**
* @dev Transfer token to a specified address.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) external returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value) public returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* Note that while this function emits an Approval event, this is not required as per the specification,
* and other compliant implementations may not emit the event.
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(address from, address to, uint256 value) external returns (bool) {
_transfer(from, to, value);
_approve(from, msg.sender, _allowed[from][msg.sender].sub(value));
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue) external returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue));
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue));
return true;
}
/**
* @dev Transfer token for a specified addresses.
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0), "ERC20: transfer to the zero address");
require(_balances[from]>=value, "ERC20 transfer: not enough tokens");
_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), "ERC20: mint to the zero address");
_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), "ERC20: burn from the zero address");
require(_balances[account] >= value, "Burn: not enough tokens");
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Approve an address to spend another addresses' tokens.
* @param owner The address that owns the tokens.
* @param spender The address that will spend the tokens.
* @param value The number of tokens that can be spent.
*/
function _approve(address owner, address spender, uint256 value) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowed[owner][spender] = value;
emit Approval(owner, spender, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* Emits an Approval event (reflecting the reduced allowance).
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
require(_allowed[account][msg.sender]>=value, "Burn: allowance too low");
_burn(account, value);
_approve(account, msg.sender, _allowed[account][msg.sender].sub(value));
}
}
pragma solidity ^0.5.8;
/**
* @title ERC20 interface
* @dev see https://eips.ethereum.org/EIPS/eip-20
*/
interface IERC20 {
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
pragma solidity ^0.5.8;
/**
* @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;
address public newOwner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public view returns (bool) {
return msg.sender == owner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
* @notice Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() external onlyOwner {
emit OwnershipTransferred(owner, address(0));
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) external onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() public{
require (newOwner == msg.sender, "Ownable: only new Owner can accept");
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
pragma solidity ^0.5.7;
/**
* @title SafeMath
* @dev Unsigned math operations with safety checks that revert on error.
*/
library SafeMath {
/**
* @dev Multiplies two unsigned integers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "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 Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
uint256 c = a - b;
return c;
}
/**
* @dev Adds two unsigned integers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
pragma solidity ^0.5.8;
import "./erc20.sol";
import "./ownable.sol";
contract Timelocks is ERC20, Ownable{
uint public lockedBalance;
struct Locker {
uint amount;
uint locktime;
}
mapping(address => Locker[]) timeLocks;
/**
* @dev function that lock tokens held by contract. Tokens can be unlocked and send to user after fime pass
* @param lockTimestamp timestamp after whih coins can be unlocked
* @param amount amount of tokens to lock
* @param user address of uset that cn unlock and posess tokens
*/
function lock(uint lockTimestamp, uint amount, address user) external onlyOwner {
_lock(lockTimestamp, amount, user);
}
function _lock(uint lockTimestamp, uint amount, address user) internal{
uint current = _balances[address(this)];
require(amount <= current.sub(lockedBalance), "Lock: Not enough tokens");
lockedBalance = lockedBalance.add(amount);
timeLocks[user].push(Locker(amount, lockTimestamp));
}
/**
* @dev Function to unlock timelocked tokens
* If block.timestap passed tokens are sent to owner and lock is removed from database
*/
function unlock() external
{
require(timeLocks[msg.sender].length > 0, "Unlock: No locks!");
Locker[] storage l = timeLocks[msg.sender];
for (uint i = 0; i < l.length; i++)
{
if (l[i].locktime < block.timestamp) {
uint amount = l[i].amount;
require(amount <= lockedBalance && amount <= _balances[address(this)], "Unlock: Not enough coins on contract!");
lockedBalance = lockedBalance.sub(amount);
_transfer(address(this), msg.sender, amount);
for (uint j = i; j < l.length - 1; j++)
{
l[j] = l[j + 1];
}
l.length--;
i--;
}
}
}
/**
* @dev Function to check how many locks are on caller account
* We need it because (for now) contract can not retrurn array of structs
* @return number of timelocked locks
*/
function locks() external view returns(uint)
{
return _locks(msg.sender);
}
/**
* @dev Function to check timelocks of any user
* @param user addres of user
* @return nuber of locks
*/
function locksOf(address user) external view returns(uint) {
return _locks(user);
}
function _locks(address user) internal view returns(uint){
return timeLocks[user].length;
}
/**
* @dev Function to check given timeLock
* @param num number of timeLock
* @return amount locked
* @return timestamp after whih coins can be unlocked
*/
function showLock(uint num) external view returns(uint, uint)
{
return _showLock(msg.sender, num);
}
/**
* @dev Function to show timeLock of any user
* @param user address of user
* @param num number of lock
* @return amount locked
* @return timestamp after whih can be unlocked
*/
function showLockOf(address user, uint num) external view returns(uint, uint) {
return _showLock(user, num);
}
function _showLock(address user, uint num) internal view returns(uint, uint) {
require(timeLocks[user].length > 0, "ShowLock: No locks!");
require(num < timeLocks[user].length, "ShowLock: Index over number of locks.");
Locker[] storage l = timeLocks[user];
return (l[num].amount, l[num].locktime);
}
}
pragma solidity ^0.5.8;
import "./ierc20.sol";
import "./safemath.sol";
import "./erc20.sol";
import "./burnable.sol";
import "./ownable.sol";
import "./timelocks.sol";
contract ContractFallbacks {
function receiveApproval(address from, uint256 _amount, address _token, bytes memory _data) public;
function onTokenTransfer(address from, uint256 amount, bytes memory data) public returns (bool success);
}
contract Wolfs is IERC20, ERC20, ERC20Burnable, Ownable, Timelocks {
using SafeMath for uint256;
string public name;
string public symbol;
uint8 public decimals;
/**
* @dev Token constructor
*/
constructor () public {
name = "Wolfs Group AG";
symbol = "WLF";
decimals = 0;
owner = 0x7fd429DBb710674614A35e967788Fa3e23A5c1C9;
emit OwnershipTransferred(address(0), owner);
_mint(0xc7eEef150818b5D3301cc93a965195F449603805, 15000000);
_mint(0x7fd429DBb710674614A35e967788Fa3e23A5c1C9, 135000000);
}
/**
* @dev function that allow to approve for transfer and call contract in one transaction
* @param _spender contract address
* @param _amount amount of tokens
* @param _extraData optional encoded data to send to contract
* @return True if function call was succesfull
*/
function approveAndCall(address _spender, uint256 _amount, bytes calldata _extraData) external returns (bool success)
{
require(approve(_spender, _amount), "ERC20: Approve unsuccesfull");
ContractFallbacks(_spender).receiveApproval(msg.sender, _amount, address(this), _extraData);
return true;
}
/**
* @dev function that transer tokens to diven address and call function on that address
* @param _to address to send tokens and call
* @param _value amount of tokens
* @param _data optional extra data to process in calling contract
* @return success True if all succedd
*/
function transferAndCall(address _to, uint _value, bytes calldata _data) external returns (bool success)
{
_transfer(msg.sender, _to, _value);
ContractFallbacks(_to).onTokenTransfer(msg.sender, _value, _data);
return true;
}
}
|
return true if `msg.sender` is the owner of the contract./
|
function isOwner() public view returns (bool) {
return msg.sender == owner;
}
| 906,659 |
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.7.6;
pragma abicoder v2;
import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import {IERC721Receiver} from "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import {ERC721} from "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import {Initializable} from "@openzeppelin/contracts/proxy/Initializable.sol";
import {EnumerableSet} from "@openzeppelin/contracts/utils/EnumerableSet.sol";
import {Address} from "@openzeppelin/contracts/utils/Address.sol";
import {TransferHelper} from "@uniswap/lib/contracts/libraries/TransferHelper.sol";
import {EIP712} from "./EIP712.sol";
import {ERC1271} from "./ERC1271.sol";
import {OwnableByERC721} from "./OwnableByERC721.sol";
import {IRageQuit} from "../staking/UniStakerV2.sol";
interface IUniversalVaultV2 {
/* user events */
event Locked(address delegate, address token, uint256 amount);
event Unlocked(address delegate, address token, uint256 amount);
event LockedERC721(address delegate, address token, uint256 tokenId);
event UnlockedERC721(address delegate, address token, uint256 tokenId);
event RageQuit(address delegate, address token, bool notified, string reason);
event ERC721Received(address operator, address from, uint256 tokenId, bytes data);
/* data types */
struct LockData {
address delegate;
address token;
uint256 balance;
}
/* initialize function */
function initialize() external;
/* user functions */
function lock(
address token,
uint256 amount,
bytes calldata permission
) external;
function unlock(
address token,
uint256 amount,
bytes calldata permission
) external;
function lockERC721(
address token,
uint256 tokenId,
bytes calldata permission
) external;
function unlockERC721(
address token,
uint256 tokenId,
bytes calldata permission
) external;
function rageQuit(address delegate, address token)
external
returns (bool notified, string memory error);
function transferERC20(
address token,
address to,
uint256 amount
) external;
function transferERC721(
address token,
address to,
uint256 tokenId
) external;
function transferETH(address to, uint256 amount) external payable;
/* pure functions */
function calculateLockID(address delegate, address token)
external
pure
returns (bytes32 lockID);
/* getter functions */
function getPermissionHash(
bytes32 eip712TypeHash,
address delegate,
address token,
uint256 amount,
uint256 nonce
) external view returns (bytes32 permissionHash);
function getPermissionHashERC721(
bytes32 eip712TypeHash,
address delegate,
address token,
uint256 tokenId,
uint256 nonce
) external view returns (bytes32 permissionHash);
function getNonce() external view returns (uint256 nonce);
function owner() external view returns (address ownerAddress);
function getLockSetCount() external view returns (uint256 count);
function getLockAt(uint256 index) external view returns (LockData memory lockData);
function getBalanceDelegated(address token, address delegate)
external
view
returns (uint256 balance);
function getBalanceLocked(address token) external view returns (uint256 balance);
function getNumERC721TypesLocked() external view returns (uint256 count);
function getERC721TypeLockedAt(uint index) external view returns (address token);
function getERC721LockedBalance(address token) external view returns (uint256 balance);
function getERC721LockedAt(address token, uint index) external view returns (uint256 tokenId);
function getNumERC721TypesInVault() external view returns (uint256 count);
function getERC721TypeInVaultAt(uint index) external view returns (address token);
function getERC721VaultBalance(address token) external view returns (uint256 balance);
function getERC721InVaultAt(address token, uint index) external view returns (uint256 tokenId);
function checkERC20Balances() external view returns (bool validity);
function checkERC721Balances() external view returns (bool validity);
}
/// @title MethodVault
/// @notice Vault for isolated storage of staking tokens
/// @dev Warning: not compatible with rebasing tokens
contract MethodVaultV2 is
IUniversalVaultV2,
EIP712("UniversalVault", "1.0.0"),
ERC1271,
OwnableByERC721,
Initializable,
IERC721Receiver
{
using SafeMath for uint256;
using Address for address;
using Address for address payable;
using EnumerableSet for EnumerableSet.Bytes32Set;
using EnumerableSet for EnumerableSet.UintSet;
using EnumerableSet for EnumerableSet.AddressSet;
/* constant */
// Hardcoding a gas limit for rageQuit() is required to prevent gas DOS attacks
// the gas requirement cannot be determined at runtime by querying the delegate
// as it could potentially be manipulated by a malicious delegate who could force
// the calls to revert.
// The gas limit could alternatively be set upon vault initialization or creation
// of a lock, but the gas consumption trade-offs are not favorable.
// Ultimately, to avoid a need for fixed gas limits, the EVM would need to provide
// an error code that allows for reliably catching out-of-gas errors on remote calls.
uint256 public constant RAGEQUIT_GAS = 500000;
bytes32 public constant LOCK_TYPEHASH =
keccak256("Lock(address delegate,address token,uint256 amount,uint256 nonce)");
bytes32 public constant UNLOCK_TYPEHASH =
keccak256("Unlock(address delegate,address token,uint256 amount,uint256 nonce)");
bytes32 public constant LOCK_ERC721_TYPEHASH =
keccak256("LockERC721(address delegate,address token,uint256 tokenId,uint256 nonce)");
bytes32 public constant UNLOCK_ERC721_TYPEHASH =
keccak256("UnlockERC721(address delegate,address token,uint256 tokenId,uint256 nonce)");
string public constant VERSION = "1.0.0";
/* storage */
uint256 private _nonce;
EnumerableSet.AddressSet private _vaultERC721Types;
// nft type to id mapping
mapping(address => EnumerableSet.UintSet) private _vaultERC721s;
EnumerableSet.AddressSet private _lockedERC721Types;
// nft type to id mapping
mapping(address => EnumerableSet.UintSet) private _lockedERC721s;
mapping(bytes32 => LockData) private _locks;
EnumerableSet.Bytes32Set private _lockSet;
/* initialization function */
function initializeLock() external initializer {}
function initialize() external override initializer {
OwnableByERC721._setNFT(msg.sender);
}
/* ether receive */
receive() external payable {}
/* internal overrides */
function _getOwner() internal view override(ERC1271) returns (address ownerAddress) {
return OwnableByERC721.owner();
}
/* overrides */
function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external override returns (bytes4) {
emit ERC721Received(operator, from, tokenId, data);
return IERC721Receiver(0).onERC721Received.selector;
}
/* pure functions */
function calculateLockID(address delegate, address token)
public
pure
override
returns (bytes32 lockID)
{
return keccak256(abi.encodePacked(delegate, token));
}
/* getter functions */
function getPermissionHash(
bytes32 eip712TypeHash,
address delegate,
address token,
uint256 amount,
uint256 nonce
) public view override returns (bytes32 permissionHash) {
return
EIP712._hashTypedDataV4(
keccak256(abi.encode(eip712TypeHash, delegate, token, amount, nonce))
);
}
function getPermissionHashERC721(
bytes32 eip712TypeHash,
address delegate,
address token,
uint256 tokenId,
uint256 nonce
) public view override returns (bytes32 permissionHash) {
return
EIP712._hashTypedDataV4(
keccak256(abi.encode(eip712TypeHash, delegate, token, tokenId, nonce))
);
}
function getNonce() external view override returns (uint256 nonce) {
return _nonce;
}
function owner()
public
view
override(IUniversalVaultV2, OwnableByERC721)
returns (address ownerAddress)
{
return OwnableByERC721.owner();
}
function getLockSetCount() external view override returns (uint256 count) {
return _lockSet.length();
}
function getLockAt(uint256 index) external view override returns (LockData memory lockData) {
return _locks[_lockSet.at(index)];
}
function getBalanceDelegated(address token, address delegate)
external
view
override
returns (uint256 balance)
{
return _locks[calculateLockID(delegate, token)].balance;
}
function getBalanceLocked(address token) public view override returns (uint256 balance) {
uint256 count = _lockSet.length();
for (uint256 index; index < count; index++) {
LockData storage _lockData = _locks[_lockSet.at(index)];
if (_lockData.token == token && _lockData.balance > balance)
balance = _lockData.balance;
}
return balance;
}
function getNumERC721TypesLocked() public view override returns (uint256 count) {
return _lockedERC721Types.length();
}
function getERC721TypeLockedAt(uint index) public view override returns (address token) {
return _lockedERC721Types.at(index);
}
function getERC721LockedBalance(address token) public view override returns (uint256 balance) {
return _lockedERC721s[token].length();
}
function getERC721LockedAt(address token, uint index) public view override returns (uint256 tokenId) {
return _lockedERC721s[token].at(index);
}
function getNumERC721TypesInVault() public view override returns (uint256 count) {
return _vaultERC721Types.length();
}
function getERC721TypeInVaultAt(uint index) public view override returns (address token) {
return _vaultERC721Types.at(index);
}
function getERC721VaultBalance(address token) public view override returns (uint256 balance) {
return _vaultERC721s[token].length();
}
function getERC721InVaultAt(address token, uint index) public view override returns (uint256 tokenId) {
return _vaultERC721s[token].at(index);
}
function checkERC20Balances() external view override returns (bool validity) {
// iterate over all token locks and validate sufficient balance
uint256 count = _lockSet.length();
for (uint256 index; index < count; index++) {
// fetch storage lock reference
LockData storage _lockData = _locks[_lockSet.at(index)];
// if insufficient balance return false
if (IERC20(_lockData.token).balanceOf(address(this)) < _lockData.balance) return false;
}
// if sufficient balance return true
return true;
}
function checkERC721Balances() external view override returns (bool validity) {
// iterate over all token locks and validate sufficient balance
uint256 count = _lockSet.length();
for (uint256 index; index < count; index++) {
// fetch storage lock reference
LockData storage _lockData = _locks[_lockSet.at(index)];
// if insufficient balance return false
if (IERC721(_lockData.token).balanceOf(address(this)) < _lockData.balance) return false;
}
// if sufficient balance return true
return true;
}
/* user functions */
/// @notice Lock ERC20 tokens in the vault
/// access control: called by delegate with signed permission from owner
/// state machine: anytime
/// state scope:
/// - insert or update _locks
/// - increase _nonce
/// token transfer: none
/// @param token Address of token being locked
/// @param amount Amount of tokens being locked
/// @param permission Permission signature payload
function lock(
address token,
uint256 amount,
bytes calldata permission
)
external
override
onlyValidSignature(
getPermissionHash(LOCK_TYPEHASH, msg.sender, token, amount, _nonce),
permission
)
{
// get lock id
bytes32 lockID = calculateLockID(msg.sender, token);
// add lock to storage
if (_lockSet.contains(lockID)) {
// if lock already exists, increase amount
_locks[lockID].balance = _locks[lockID].balance.add(amount);
} else {
// if does not exist, create new lock
// add lock to set
assert(_lockSet.add(lockID));
// add lock data to storage
_locks[lockID] = LockData(msg.sender, token, amount);
}
// validate sufficient balance
require(
IERC20(token).balanceOf(address(this)) >= _locks[lockID].balance,
"UniversalVaultV2: insufficient balance"
);
// increase nonce
_nonce += 1;
// emit event
emit Locked(msg.sender, token, amount);
}
function lockERC721(
address token,
uint256 tokenId,
bytes calldata permission
)
external
override
onlyValidSignature(
getPermissionHashERC721(LOCK_ERC721_TYPEHASH, msg.sender, token, tokenId, _nonce),
permission
)
{
// sanity check, can't lock self
require(
address(tokenId) != address(this),
"can't self lock"
);
// validate ownership
require(
IERC721(token).ownerOf(tokenId) == address(this),
"UniversalVaultV2: vault not owner of nft"
);
require(
!_lockedERC721s[token].contains(tokenId),
"NFT already locked"
);
_lockedERC721Types.add(token);
_lockedERC721s[token].add(tokenId);
// get lock id
bytes32 lockID = calculateLockID(msg.sender, token);
// add lock to storage
if (_lockSet.contains(lockID)) {
// if lock already exists, increase amount by 1
_locks[lockID].balance = _locks[lockID].balance.add(1);
} else {
// if does not exist, create new lock
// add lock to set
assert(_lockSet.add(lockID));
// add lock data to storage
_locks[lockID] = LockData(msg.sender, token, 1);
}
// increase nonce
_nonce += 1;
// emit event
emit LockedERC721(msg.sender, token, tokenId);
}
/// @notice Unlock ERC20 tokens in the vault
/// access control: called by delegate with signed permission from owner
/// state machine: after valid lock from delegate
/// state scope:
/// - remove or update _locks
/// - increase _nonce
/// token transfer: none
/// @param token Address of token being unlocked
/// @param amount Amount of tokens being unlocked
/// @param permission Permission signature payload
function unlock(
address token,
uint256 amount,
bytes calldata permission
)
external
override
onlyValidSignature(
getPermissionHash(UNLOCK_TYPEHASH, msg.sender, token, amount, _nonce),
permission
)
{
// get lock id
bytes32 lockID = calculateLockID(msg.sender, token);
// validate existing lock
require(_lockSet.contains(lockID), "UniversalVaultV2: missing lock");
// update lock data
if (_locks[lockID].balance > amount) {
// subtract amount from lock balance
_locks[lockID].balance = _locks[lockID].balance.sub(amount);
} else {
// delete lock data
delete _locks[lockID];
assert(_lockSet.remove(lockID));
}
// increase nonce
_nonce += 1;
// emit event
emit Unlocked(msg.sender, token, amount);
}
function unlockERC721(
address token,
uint256 tokenId,
bytes calldata permission
)
external
override
onlyValidSignature(
getPermissionHashERC721(UNLOCK_ERC721_TYPEHASH, msg.sender, token, tokenId, _nonce),
permission
)
{
// validate ownership
require(
IERC721(token).ownerOf(tokenId) == address(this),
"UniversalVaultV2: vault not owner of nft"
);
require(
_lockedERC721s[token].contains(tokenId),
"NFT not locked"
);
_lockedERC721s[token].remove(tokenId);
if (_lockedERC721s[token].length() == 0) {
_lockedERC721Types.remove(token);
}
_vaultERC721Types.add(token);
_vaultERC721s[token].add(tokenId);
// get lock id
bytes32 lockID = calculateLockID(msg.sender, token);
// validate existing lock
require(_lockSet.contains(lockID), "UniversalVaultV2: missing lock");
// update lock data
if (_locks[lockID].balance > 1) {
// subtract 1 from lock balance
_locks[lockID].balance = _locks[lockID].balance.sub(1);
} else {
// delete lock data
delete _locks[lockID];
assert(_lockSet.remove(lockID));
}
// increase nonce
_nonce += 1;
// emit event
emit UnlockedERC721(msg.sender, token, tokenId);
}
/// @notice Forcibly cancel delegate lock
/// @dev This function will attempt to notify the delegate of the rage quit using a fixed amount of gas.
/// access control: only owner
/// state machine: after valid lock from delegate
/// state scope:
/// - remove item from _locks
/// token transfer: none
/// @param delegate Address of delegate
/// @param token Address of token being unlocked
function rageQuit(address delegate, address token)
external
override
onlyOwner
returns (bool notified, string memory error)
{
// get lock id
bytes32 lockID = calculateLockID(delegate, token);
// validate existing lock
require(_lockSet.contains(lockID), "UniversalVaultV2: missing lock");
// attempt to notify delegate
if (delegate.isContract()) {
// check for sufficient gas
require(gasleft() >= RAGEQUIT_GAS, "UniversalVaultV2: insufficient gas");
// attempt rageQuit notification
try IRageQuit(delegate).rageQuit{gas: RAGEQUIT_GAS}() {
notified = true;
} catch Error(string memory res) {
notified = false;
error = res;
} catch (bytes memory) {
notified = false;
}
}
// update lock storage
assert(_lockSet.remove(lockID));
delete _locks[lockID];
// emit event
emit RageQuit(delegate, token, notified, error);
}
/// @notice Transfer ERC20 tokens out of vault
/// access control: only owner
/// state machine: when balance >= max(lock) + amount
/// state scope: none
/// token transfer: transfer any token
/// @param token Address of token being transferred
/// @param to Address of the recipient
/// @param amount Amount of tokens to transfer
function transferERC20(
address token,
address to,
uint256 amount
) external override onlyOwner {
// check for sufficient balance
require(
IERC20(token).balanceOf(address(this)) >= getBalanceLocked(token).add(amount),
"UniversalVaultV2: insufficient balance"
);
// perform transfer
TransferHelper.safeTransfer(token, to, amount);
}
function transferERC721(
address token,
address to,
uint256 tokenId
) external override onlyOwner {
// validate ownership
require(
IERC721(token).ownerOf(tokenId) == address(this),
"UniversalVaultV2: vault not owner of nft"
);
require(
!_lockedERC721s[token].contains(tokenId),
"NFT is locked. Unlock first."
);
_vaultERC721s[token].remove(tokenId);
if (_vaultERC721s[token].length() == 0) {
_vaultERC721Types.remove(token);
}
// perform transfer
IERC721(token).safeTransferFrom(address(this), to, tokenId);
}
/// @notice Transfer ERC20 tokens out of vault
/// access control: only owner
/// state machine: when balance >= amount
/// state scope: none
/// token transfer: transfer any token
/// @param to Address of the recipient
/// @param amount Amount of ETH to transfer
function transferETH(address to, uint256 amount) external payable override onlyOwner {
// perform transfer
TransferHelper.safeTransferETH(to, amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "../../introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @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 "../../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
// solhint-disable-next-line compiler-version
pragma solidity >=0.4.24 <0.8.0;
import "../utils/Address.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 !Address.isContract(address(this));
}
}
// 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.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: GPL-3.0-or-later
pragma solidity >=0.6.0;
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeApprove: approve failed'
);
}
function safeTransfer(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeTransfer: transfer failed'
);
}
function safeTransferFrom(
address token,
address from,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::transferFrom: transferFrom failed'
);
}
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, 'TransferHelper::safeTransferETH: ETH transfer failed');
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/* solhint-disable max-line-length */
/**
* @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 */
bytes32 private immutable _HASHED_NAME;
bytes32 private immutable _HASHED_VERSION;
bytes32 private constant _TYPE_HASH =
keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
);
/* solhint-enable var-name-mixedcase */
/**
* @dev Initializes the domain separator and parameter caches.
*
* The meaning of `name` and `version` is specified in
* https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
*
* - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
* - `version`: the current major version of the signing domain.
*
* NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
* contract upgrade].
*/
constructor(string memory name, string memory version) {
_HASHED_NAME = keccak256(bytes(name));
_HASHED_VERSION = keccak256(bytes(version));
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view returns (bytes32) {
return _buildDomainSeparator(_TYPE_HASH, _EIP712NameHash(), _EIP712VersionHash());
}
function _buildDomainSeparator(
bytes32 typeHash,
bytes32 name,
bytes32 version
) private view returns (bytes32) {
return keccak256(abi.encode(typeHash, name, version, _getChainId(), 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 keccak256(abi.encodePacked("\x19\x01", _domainSeparatorV4(), structHash));
}
function _getChainId() private view returns (uint256 chainId) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
// solhint-disable-next-line no-inline-assembly
assembly {
chainId := chainid()
}
}
/**
* @dev The hash of the name parameter for the EIP712 domain.
*
* NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs
* are a concern.
*/
function _EIP712NameHash() internal view virtual returns (bytes32) {
return _HASHED_NAME;
}
/**
* @dev The hash of the version parameter for the EIP712 domain.
*
* NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs
* are a concern.
*/
function _EIP712VersionHash() internal view virtual returns (bytes32) {
return _HASHED_VERSION;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.7.6;
import {ECDSA} from "@openzeppelin/contracts/cryptography/ECDSA.sol";
import {Address} from "@openzeppelin/contracts/utils/Address.sol";
interface IERC1271 {
function isValidSignature(bytes32 _messageHash, bytes memory _signature)
external
view
returns (bytes4 magicValue);
}
library SignatureChecker {
function isValidSignature(
address signer,
bytes32 hash,
bytes memory signature
) internal view returns (bool) {
if (Address.isContract(signer)) {
bytes4 selector = IERC1271.isValidSignature.selector;
(bool success, bytes memory returndata) =
signer.staticcall(abi.encodeWithSelector(selector, hash, signature));
return success && abi.decode(returndata, (bytes4)) == selector;
} else {
return ECDSA.recover(hash, signature) == signer;
}
}
}
/// @title ERC1271
/// @notice Module for ERC1271 compatibility
abstract contract ERC1271 is IERC1271 {
// Valid magic value bytes4(keccak256("isValidSignature(bytes32,bytes)")
bytes4 internal constant VALID_SIG = IERC1271.isValidSignature.selector;
// Invalid magic value
bytes4 internal constant INVALID_SIG = bytes4(0);
modifier onlyValidSignature(bytes32 permissionHash, bytes memory signature) {
require(
isValidSignature(permissionHash, signature) == VALID_SIG,
"ERC1271: Invalid signature"
);
_;
}
function _getOwner() internal view virtual returns (address owner);
function isValidSignature(bytes32 permissionHash, bytes memory signature)
public
view
override
returns (bytes4)
{
return
SignatureChecker.isValidSignature(_getOwner(), permissionHash, signature)
? VALID_SIG
: INVALID_SIG;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.7.6;
import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol";
/// @title OwnableByERC721
/// @notice Use ERC721 ownership for access control
contract OwnableByERC721 {
address private _nftAddress;
modifier onlyOwner() {
require(owner() == msg.sender, "OwnableByERC721: caller is not the owner");
_;
}
function _setNFT(address nftAddress) internal {
_nftAddress = nftAddress;
}
function nft() public view virtual returns (address nftAddress) {
return _nftAddress;
}
function owner() public view virtual returns (address ownerAddress) {
return IERC721(_nftAddress).ownerOf(uint256(address(this)));
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.7.6;
pragma abicoder v2;
import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol";
import {EnumerableSet} from "@openzeppelin/contracts/utils/EnumerableSet.sol";
import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import {TransferHelper} from "@uniswap/lib/contracts/libraries/TransferHelper.sol";
import {IFactory} from "../factory/IFactory.sol";
import {IInstanceRegistry} from "../factory/InstanceRegistry.sol";
import {IUniversalVaultV2} from "../methodNFT/MethodVaultV2.sol";
import {MethodNFTFactory} from "../methodNFT/MethodNFTFactory.sol";
import {IRewardPool} from "./RewardPool.sol";
import {Powered} from "./Powered.sol";
import {IERC2917} from "./IERC2917.sol";
import {ProxyFactory} from "../factory/ProxyFactory.sol";
interface IRageQuit {
function rageQuit() external;
}
interface IUniStakerV2 is IRageQuit {
/* admin events */
event UniStakerV2Created(address rewardPool, address powerSwitch);
event UniStakerV2Funded(address token, uint256 amount);
event BonusTokenRegistered(address token);
event BonusTokenRemoved(address token);
event VaultFactoryRegistered(address factory);
event VaultFactoryRemoved(address factory);
event AdminshipTransferred(address indexed previousAdmin, address indexed newAdmin);
/* user events */
event Staked(address vault, address token, uint256 tokenId);
event Unstaked(address vault, address token, uint256 tokenId);
event RageQuit(address vault);
event RewardClaimed(address vaultFactory, address recipient, address token, uint256 amount);
event VestedRewardClaimed(address recipient, address token, uint amount);
/* data types */
struct VaultData {
// token address to total token stake mapping
mapping(address => uint) tokenStake;
EnumerableSet.AddressSet tokens;
}
struct LMRewardData {
uint256 amount;
uint256 duration;
uint256 startedAt;
address rewardCalcInstance;
EnumerableSet.AddressSet bonusTokens;
mapping(address => uint) bonusTokenAmounts;
}
struct LMRewardVestingData {
uint amount;
uint startedAt;
}
/* getter functions */
function getBonusTokenSetLength() external view returns (uint256 length);
function getBonusTokenAtIndex(uint256 index) external view returns (address bonusToken);
function getVaultFactorySetLength() external view returns (uint256 length);
function getVaultFactoryAtIndex(uint256 index) external view returns (address factory);
function getNumVaults() external view returns (uint256 num);
function getVaultAt(uint256 index) external view returns (address vault);
function getNumTokensStaked() external view returns (uint256 num);
function getTokenStakedAt(uint256 index) external view returns (address token);
function getNumTokensStakedInVault(address vault) external view returns (uint256 num);
function getVaultTokenAtIndex(address vault, uint256 index) external view returns (address vaultToken);
function getVaultTokenStake(address vault, address token) external view returns (uint256 tokenStake);
function getLMRewardData(address token) external view returns (uint amount, uint duration, uint startedAt, address rewardCalcInstance);
function getLMRewardBonusTokensLength(address token) external view returns (uint length);
function getLMRewardBonusTokenAt(address token, uint index) external view returns (address bonusToken, uint bonusTokenAmount);
function getNumVestingLMTokenRewards(address user) external view returns (uint num);
function getVestingLMTokenAt(address user, uint index) external view returns (address token);
function getNumVests(address user, address token) external view returns (uint num);
function getNumRewardCalcTemplates() external view returns (uint num);
function getLMRewardVestingData(address user, address token, uint index) external view returns (uint amount, uint startedAt);
function isValidAddress(address target) external view returns (bool validity);
function isValidVault(address vault, address factory) external view returns (bool validity);
/* user functions */
function stakeERC721(
address vault,
address vaultFactory,
address token,
uint256 tokenId,
bytes calldata permission
) external;
function unstakeERC721AndClaimReward(
address vault,
address vaultFactory,
address recipient,
address token,
uint256 tokenId,
bool claimBonusReward,
bytes calldata permission
) external;
function claimVestedReward() external;
function claimVestedReward(address token) external;
}
/// @title UniStakerV2
/// @notice Reward distribution contract
/// Access Control
/// - Power controller:
/// Can power off / shutdown the UniStakerV2
/// Can withdraw rewards from reward pool once shutdown
/// - Owner:
/// Is unable to operate on user funds due to UniversalVault
/// Is unable to operate on reward pool funds when reward pool is offline / shutdown
/// - UniStakerV2 admin:
/// Can add funds to the UniStakerV2, register bonus tokens, and whitelist new vault factories
/// Is a subset of owner permissions
/// - User:
/// Can stake / unstake / ragequit / claim airdrop / claim vested rewards
/// UniStakerV2 State Machine
/// - Online:
/// UniStakerV2 is operating normally, all functions are enabled
/// - Offline:
/// UniStakerV2 is temporarely disabled for maintenance
/// User staking and unstaking is disabled, ragequit remains enabled
/// Users can delete their stake through rageQuit() but forego their pending reward
/// Should only be used when downtime required for an upgrade
/// - Shutdown:
/// UniStakerV2 is permanently disabled
/// All functions are disabled with the exception of ragequit
/// Users can delete their stake through rageQuit()
/// Power controller can withdraw from the reward pool
/// Should only be used if Owner role is compromised
contract UniStakerV2 is IUniStakerV2, Powered {
using SafeMath for uint256;
using EnumerableSet for EnumerableSet.AddressSet;
/* constants */
string public constant PLATINUM = "PLATINUM";
string public constant GOLD = "GOLD";
string public constant MINT = "MINT";
string public constant BLACK = "BLACK";
uint public PLATINUM_LM_REWARD_MULTIPLIER_NUM = 5;
uint public PLATINUM_LM_REWARD_MULTIPLIER_DENOM = 2;
uint public GOLD_LM_REWARD_MULTIPLIER_NUM = 2;
uint public GOLD_LM_REWARD_MULTIPLIER_DENOM = 1;
uint public MINT_LM_REWARD_MULTIPLIER_NUM = 3;
uint public MINT_LM_REWARD_MULTIPLIER_DENOM = 2;
uint public BLACK_LM_REWARD_MULTIPLIER_NUM = 1;
uint public BLACK_LM_REWARD_MULTIPLIER_DENOM = 1;
uint public LM_REWARD_VESTING_PERIOD = 7776000; // 3 months
uint public LM_REWARD_VESTING_PORTION_NUM = 1;
uint public LM_REWARD_VESTING_PORTION_DENOM = 2;
// An upper bound on the number of active tokens staked per vault is required to prevent
// calls to rageQuit() from reverting.
// With 30 tokens staked in a vault, ragequit costs 432811 gas which is conservatively lower
// than the hardcoded limit of 500k gas on the vault.
// This limit is configurable and could be increased in a future deployment.
// Ultimately, to avoid a need for fixed upper bounds, the EVM would need to provide
// an error code that allows for reliably catching out-of-gas errors on remote calls.
uint256 public MAX_TOKENS_STAKED_PER_VAULT = 30;
uint256 public MAX_BONUS_TOKENS = 50;
/* storage */
address public admin;
address public rewardToken;
address public rewardPool;
EnumerableSet.AddressSet private _vaultSet;
mapping(address => VaultData) private _vaults;
EnumerableSet.AddressSet private _bonusTokenSet;
EnumerableSet.AddressSet private _vaultFactorySet;
EnumerableSet.AddressSet private _allStakedTokens;
mapping(address => uint256) public stakedTokenTotal;
mapping(address => LMRewardData) private lmRewards;
// user to token to earned reward mapping
mapping(address => mapping(address => uint)) public earnedLMRewards;
// user to token to vesting data mapping
mapping(address => mapping(address => LMRewardVestingData[])) public vestingLMRewards;
// user to vesting lm token rewards set
mapping(address => EnumerableSet.AddressSet) private vestingLMTokenRewards;
// erc2917 template names
string[] public rewardCalcTemplateNames;
// erc2917 template names to erc 2917 templates
mapping(string => address) public rewardCalcTemplates;
string public activeRewardCalcTemplate;
event RewardCalcTemplateAdded(string indexed name, address indexed template);
event RewardCalcTemplateActive(string indexed name, address indexed template);
/* initializer */
/// @notice Initizalize UniStakerV2
/// access control: only proxy constructor
/// state machine: can only be called once
/// state scope: set initialization variables
/// token transfer: none
/// @param adminAddress address The admin address
/// @param rewardPoolFactory address The factory to use for deploying the RewardPool
/// @param powerSwitchFactory address The factory to use for deploying the PowerSwitch
/// @param rewardTokenAddress address The address of the reward token for this UniStakerV2
constructor(
address adminAddress,
address rewardPoolFactory,
address powerSwitchFactory,
address rewardTokenAddress
) {
// deploy power switch
address powerSwitch = IFactory(powerSwitchFactory).create(abi.encode(adminAddress));
// deploy reward pool
rewardPool = IFactory(rewardPoolFactory).create(abi.encode(powerSwitch));
// set internal config
admin = adminAddress;
rewardToken = rewardTokenAddress;
Powered._setPowerSwitch(powerSwitch);
// emit event
emit UniStakerV2Created(rewardPool, powerSwitch);
}
/* admin functions */
function _admin() private view {
require(msg.sender == admin, "not allowed");
}
/**
* @dev Leaves the contract without admin. It will not be possible to call
* `admin` functions anymore. Can only be called by the current admin.
*
* NOTE: Renouncing adminship will leave the contract without an admin,
* thereby removing any functionality that is only available to the admin.
*/
function renounceAdminship() public {
_admin();
emit AdminshipTransferred(admin, address(0));
admin = address(0);
}
/**
* @dev Transfers adminship of the contract to a new account (`newAdmin`).
* Can only be called by the current admin.
*/
function transferAdminship(address newAdmin) public {
_admin();
require(newAdmin != address(0), "new admin can't the zero address");
emit AdminshipTransferred(admin, newAdmin);
admin = newAdmin;
}
/// @notice Add funds to UniStakerV2
/// access control: only admin
/// state machine:
/// - can be called multiple times
/// - only online
/// state scope:
/// - none
/// token transfer: transfer staking tokens from msg.sender to reward pool
/// @param amount uint256 Amount of reward tokens to deposit
function fund(address token, uint256 amount) external {
_admin();
require(_bonusTokenSet.contains(token) || token == rewardToken, "cannot fund with unrecognized token");
// transfer reward tokens to reward pool
TransferHelper.safeTransferFrom(
token,
msg.sender,
rewardPool,
amount
);
// emit event
emit UniStakerV2Funded(token, amount);
}
/// @notice Rescue tokens from RewardPool
/// @dev use this function to rescue tokens from RewardPool contract without distributing to stakers or triggering emergency shutdown
/// access control: only admin
/// state machine:
/// - can be called multiple times
/// - not shutdown
/// state scope: none
/// token transfer: transfer requested token from RewardPool to recipient
/// @param token address The address of the token to rescue
/// @param recipient address The address of the recipient
/// @param amount uint256 The amount of tokens to rescue
function rescueTokensFromRewardPool(
address token,
address recipient,
uint256 amount
) external {
_admin();
// verify recipient
require(isValidAddress(recipient), "invalid recipient");
// transfer tokens to recipient
IRewardPool(rewardPool).sendERC20(token, recipient, amount);
}
/// @notice Add vault factory to whitelist
/// @dev use this function to enable stakes to vaults coming from the specified factory contract
/// access control: only admin
/// state machine:
/// - can be called multiple times
/// - not shutdown
/// state scope:
/// - append to _vaultFactorySet
/// token transfer: none
/// @param factory address The address of the vault factory
function registerVaultFactory(address factory) external {
_admin();
// add factory to set
require(_vaultFactorySet.add(factory), "UniStakerV2: vault factory already registered");
// emit event
emit VaultFactoryRegistered(factory);
}
/// @notice Remove vault factory from whitelist
/// @dev use this function to disable new stakes to vaults coming from the specified factory contract.
/// note: vaults with existing stakes from this factory are sill able to unstake
/// access control: only admin
/// state machine:
/// - can be called multiple times
/// - not shutdown
/// state scope:
/// - remove from _vaultFactorySet
/// token transfer: none
/// @param factory address The address of the vault factory
function removeVaultFactory(address factory) external {
_admin();
// remove factory from set
require(_vaultFactorySet.remove(factory), "UniStakerV2: vault factory not registered");
// emit event
emit VaultFactoryRemoved(factory);
}
/// @notice Register bonus token for distribution
/// @dev use this function to enable distribution of any ERC20 held by the RewardPool contract
/// access control: only admin
/// state machine:
/// - can be called multiple times
/// - only online
/// state scope:
/// - append to _bonusTokenSet
/// token transfer: none
/// @param bonusToken address The address of the bonus token
function registerBonusToken(address bonusToken) external {
_admin();
// verify valid bonus token
require(isValidAddress(bonusToken), "invalid bonus token address or is already present");
// verify bonus token count
require(_bonusTokenSet.length() < MAX_BONUS_TOKENS, "UniStakerV2: max bonus tokens reached ");
// add token to set
_bonusTokenSet.add(bonusToken);
// emit event
emit BonusTokenRegistered(bonusToken);
}
/// @notice Remove bonus token
/// @dev use this function to disable distribution of a token held by the RewardPool contract
/// access control: only admin
/// state machine:
/// - can be called multiple times
/// - not shutdown
/// state scope:
/// - remove from _bonusTokenSet
/// token transfer: none
/// @param bonusToken address The address of the bonus token
function removeBonusToken(address bonusToken) external {
_admin();
require(_bonusTokenSet.remove(bonusToken), "UniStakerV2: bonus token not present ");
// emit event
emit BonusTokenRemoved(bonusToken);
}
function addRewardCalcTemplate(string calldata name, address template) external {
_admin();
require(rewardCalcTemplates[name] == address(0), "Template already exists");
rewardCalcTemplates[name] = template;
if(rewardCalcTemplateNames.length == 0) {
activeRewardCalcTemplate = name;
emit RewardCalcTemplateActive(name, template);
}
rewardCalcTemplateNames.push(name);
emit RewardCalcTemplateAdded(name, template);
}
function setRewardCalcActiveTemplate(string calldata name) external {
_admin();
require(rewardCalcTemplates[name] != address(0), "Template does not exist");
activeRewardCalcTemplate = name;
emit RewardCalcTemplateActive(name, rewardCalcTemplates[name]);
}
function startLMRewards(address token, uint256 amount, uint256 duration) external {
startLMRewards(token, amount, duration, activeRewardCalcTemplate);
}
function startLMRewards(address token, uint256 amount, uint256 duration, string memory rewardCalcTemplateName) public {
_admin();
require(lmRewards[token].startedAt == 0, "A reward program already live for this token");
require(rewardCalcTemplates[rewardCalcTemplateName] != address(0), "Reward Calculator Template does not exist");
// create reward calc clone from template
address rewardCalcInstance = ProxyFactory._create(rewardCalcTemplates[rewardCalcTemplateName], abi.encodeWithSelector(IERC2917.initialize.selector));
LMRewardData storage lmrd = lmRewards[token];
lmrd.amount = amount;
lmrd.duration = duration;
lmrd.startedAt = block.timestamp;
lmrd.rewardCalcInstance = rewardCalcInstance;
}
function setImplementorForRewardsCalculator(address token, address newImplementor) public {
_admin();
require(lmRewards[token].startedAt != 0, "No reward program currently live for this token");
address rewardCalcInstance = lmRewards[token].rewardCalcInstance;
IERC2917(rewardCalcInstance).setImplementor(newImplementor);
}
function setLMRewardsPerBlock(address token, uint value) public onlyOnline {
_admin();
require(lmRewards[token].startedAt != 0, "No reward program currently live for this token");
address rewardCalcInstance = lmRewards[token].rewardCalcInstance;
IERC2917(rewardCalcInstance).changeInterestRatePerBlock(value);
}
function addBonusTokenToLMRewards(address lmToken, address bonusToken, uint256 bonusTokenAmount) public {
_admin();
require(lmRewards[lmToken].startedAt != 0, "No reward program currently live for this LM token");
require(_bonusTokenSet.contains(bonusToken), "Bonus token not registered");
lmRewards[lmToken].bonusTokens.add(bonusToken);
lmRewards[lmToken].bonusTokenAmounts[bonusToken] = lmRewards[lmToken].bonusTokenAmounts[bonusToken].add(bonusTokenAmount);
}
function endLMRewards(address token, bool removeBonusTokenData) public {
_admin();
lmRewards[token].amount = 0;
lmRewards[token].duration = 0;
lmRewards[token].startedAt = 0;
lmRewards[token].rewardCalcInstance = address(0);
if (removeBonusTokenData) {
for (uint index = 0; index < lmRewards[token].bonusTokens.length(); index++) {
address bonusToken = lmRewards[token].bonusTokens.at(index);
lmRewards[token].bonusTokens.remove(bonusToken);
delete lmRewards[token].bonusTokenAmounts[bonusToken];
}
}
}
function setMaxStakesPerVault(uint256 amount) external {
_admin();
MAX_TOKENS_STAKED_PER_VAULT = amount;
}
function setMaxBonusTokens(uint256 amount) external {
_admin();
MAX_BONUS_TOKENS = amount;
}
function setPlatinumLMRewardMultiplier(uint256 numerator, uint256 denominator) external {
_admin();
PLATINUM_LM_REWARD_MULTIPLIER_NUM = numerator;
PLATINUM_LM_REWARD_MULTIPLIER_DENOM = denominator;
}
function setGoldLMRewardMultiplier(uint256 numerator, uint256 denominator) external {
_admin();
GOLD_LM_REWARD_MULTIPLIER_NUM = numerator;
GOLD_LM_REWARD_MULTIPLIER_DENOM = denominator;
}
function setMintLMRewardMultiplier(uint256 numerator, uint256 denominator) external {
_admin();
MINT_LM_REWARD_MULTIPLIER_NUM = numerator;
MINT_LM_REWARD_MULTIPLIER_DENOM = denominator;
}
function setBlackLMRewardMultiplier(uint256 numerator, uint256 denominator) external {
_admin();
BLACK_LM_REWARD_MULTIPLIER_NUM = numerator;
BLACK_LM_REWARD_MULTIPLIER_DENOM = denominator;
}
function setLMRewardVestingPeriod(uint256 amount) external {
_admin();
LM_REWARD_VESTING_PERIOD = amount;
}
function setLMRewardVestingPortion(uint256 numerator, uint denominator) external {
_admin();
LM_REWARD_VESTING_PORTION_NUM = numerator;
LM_REWARD_VESTING_PORTION_DENOM = denominator;
}
/* getter functions */
function getBonusTokenSetLength() external view override returns (uint256 length) {
return _bonusTokenSet.length();
}
function getBonusTokenAtIndex(uint256 index)
external
view
override
returns (address bonusToken)
{
return _bonusTokenSet.at(index);
}
function getVaultFactorySetLength() external view override returns (uint256 length) {
return _vaultFactorySet.length();
}
function getVaultFactoryAtIndex(uint256 index)
external
view
override
returns (address factory)
{
return _vaultFactorySet.at(index);
}
function getNumVaults() external view override returns (uint256 num) {
return _vaultSet.length();
}
function getVaultAt(uint256 index) external view override returns (address vault) {
return _vaultSet.at(index);
}
function getNumTokensStaked() external view override returns (uint256 num) {
return _allStakedTokens.length();
}
function getTokenStakedAt(uint256 index) external view override returns (address token) {
return _allStakedTokens.at(index);
}
function getNumTokensStakedInVault(address vault)
external
view
override
returns (uint256 num)
{
return _vaults[vault].tokens.length();
}
function getVaultTokenAtIndex(address vault, uint256 index)
external
view
override
returns (address vaultToken)
{
return _vaults[vault].tokens.at(index);
}
function getVaultTokenStake(address vault, address token)
external
view
override
returns (uint256 tokenStake)
{
return _vaults[vault].tokenStake[token];
}
function getNftTier(uint256 nftId, address nftFactory) public view returns (string memory tier) {
uint256 serialNumber = MethodNFTFactory(nftFactory).tokenIdToSerialNumber(nftId);
if (serialNumber >= 1 && serialNumber <= 100) {
tier = PLATINUM;
} else if (serialNumber >= 101 && serialNumber <= 1000) {
tier = GOLD;
} else if (serialNumber >= 1001 && serialNumber <= 5000) {
tier = MINT;
} else if (serialNumber >= 5001) {
tier = BLACK;
}
}
function getLMRewardData(address token) external view override returns (uint amount, uint duration, uint startedAt, address rewardCalcInstance) {
return (lmRewards[token].amount, lmRewards[token].duration, lmRewards[token].startedAt, lmRewards[token].rewardCalcInstance);
}
function getLMRewardBonusTokensLength(address token) external view override returns (uint length) {
return lmRewards[token].bonusTokens.length();
}
function getLMRewardBonusTokenAt(address token, uint index) external view override returns (address bonusToken, uint bonusTokenAmount) {
return (lmRewards[token].bonusTokens.at(index), lmRewards[token].bonusTokenAmounts[lmRewards[token].bonusTokens.at(index)]);
}
function getNumVestingLMTokenRewards(address user) external view override returns (uint num) {
return vestingLMTokenRewards[user].length();
}
function getVestingLMTokenAt(address user, uint index) external view override returns (address token) {
return vestingLMTokenRewards[user].at(index);
}
function getNumVests(address user, address token) external view override returns (uint num) {
return vestingLMRewards[user][token].length;
}
function getLMRewardVestingData(address user, address token, uint index) external view override returns (uint amount, uint startedAt) {
return (vestingLMRewards[user][token][index].amount, vestingLMRewards[user][token][index].startedAt);
}
function getNumRewardCalcTemplates() external view override returns (uint num) {
return rewardCalcTemplateNames.length;
}
/* helper functions */
function isValidVault(address vault, address factory) public view override returns (bool validity) {
// validate vault is created from whitelisted vault factory and is an instance of that factory
return _vaultFactorySet.contains(factory) && IInstanceRegistry(factory).isInstance(vault);
}
function isValidAddress(address target) public view override returns (bool validity) {
// sanity check target for potential input errors
return
target != address(this) &&
target != address(0) &&
target != rewardToken &&
target != rewardPool &&
!_bonusTokenSet.contains(target);
}
/* convenience functions */
function _tierMultipliedReward(uint nftId, address nftFactory, uint reward) private view returns (uint multipliedReward) {
// get tier
string memory tier = getNftTier(nftId, nftFactory);
bytes32 tierHash = keccak256(abi.encodePacked(tier));
if (tierHash == keccak256(abi.encodePacked(PLATINUM))) {
multipliedReward = reward.mul(PLATINUM_LM_REWARD_MULTIPLIER_NUM).div(PLATINUM_LM_REWARD_MULTIPLIER_DENOM);
} else if (tierHash == keccak256(abi.encodePacked(GOLD))) {
multipliedReward = reward.mul(GOLD_LM_REWARD_MULTIPLIER_NUM).div(GOLD_LM_REWARD_MULTIPLIER_DENOM);
} else if (tierHash == keccak256(abi.encodePacked(MINT))) {
multipliedReward = reward.mul(MINT_LM_REWARD_MULTIPLIER_NUM).div(MINT_LM_REWARD_MULTIPLIER_DENOM);
} else if (tierHash == keccak256(abi.encodePacked(BLACK))) {
multipliedReward = reward.mul(BLACK_LM_REWARD_MULTIPLIER_NUM).div(BLACK_LM_REWARD_MULTIPLIER_DENOM);
}
}
/* user functions */
/// @notice Exit UniStakerV2 without claiming reward
/// @dev This function should never revert when correctly called by the vault.
/// A max number of tokens staked per vault is set with MAX_TOKENS_STAKED_PER_VAULT to
/// place an upper bound on the for loop.
/// access control: callable by anyone but fails if caller is not an approved vault
/// state machine:
/// - when vault exists on this UniStakerV2
/// - when active stake from this vault
/// - any power state
/// state scope:
/// - decrease stakedTokenTotal[token], delete if 0
/// - delete _vaults[vault].tokenStake[token]
/// - remove _vaults[vault].tokens.remove(token)
/// - delete _vaults[vault]
/// - remove vault from _vaultSet
/// - remove token from _allStakedTokens if required
/// token transfer: none
function rageQuit() external override {
require(_vaultSet.contains(msg.sender), "UniStakerV2: no vault");
//fetch vault storage reference
VaultData storage vaultData = _vaults[msg.sender];
// revert if no active tokens staked
EnumerableSet.AddressSet storage vaultTokens = vaultData.tokens;
require(vaultTokens.length() > 0, "UniStakerV2: no stake");
// update totals
for (uint256 index = 0; index < vaultTokens.length(); index++) {
address token = vaultTokens.at(index);
vaultTokens.remove(token);
uint256 amount = vaultData.tokenStake[token];
uint256 newTotal = stakedTokenTotal[token].sub(amount);
assert(newTotal >= 0);
if (newTotal == 0) {
_allStakedTokens.remove(token);
delete stakedTokenTotal[token];
} else {
stakedTokenTotal[token] = newTotal;
}
delete vaultData.tokenStake[token];
}
// delete vault data
_vaultSet.remove(msg.sender);
delete _vaults[msg.sender];
// emit event
emit RageQuit(msg.sender);
}
/// @notice Stake ERC721 tokens
/// @dev anyone can stake to any vault if they have valid permission
/// access control: anyone
/// state machine:
/// - can be called multiple times
/// - only online
/// - when vault exists on this UniStakerV2
/// state scope:
/// - add token to _vaults[vault].tokens if not already exists
/// - increase _vaults[vault].tokenStake[token]
/// - add vault to _vaultSet if not already exists
/// - add token to _allStakedTokens if not already exists
/// - increase stakedTokenTotal[token]
/// token transfer: transfer staking tokens from msg.sender to vault
/// @param vault address The address of the vault to stake to
/// @param vaultFactory address The address of the vault factory which created the vault
/// @param token address The address of the token being staked
/// @param tokenId uint256 The id of token to stake
function stakeERC721(
address vault,
address vaultFactory,
address token,
uint256 tokenId,
bytes calldata permission
) external override onlyOnline {
// verify vault is valid
require(isValidVault(vault, vaultFactory), "UniStakerV2: vault is not valid");
// add vault to set
_vaultSet.add(vault);
// fetch vault storage reference
VaultData storage vaultData = _vaults[vault];
// verify stakes boundary not reached
require(vaultData.tokens.length() < MAX_TOKENS_STAKED_PER_VAULT, "UniStakerV2: MAX_TOKENS_STAKED_PER_VAULT reached");
// add token to set and increase amount
vaultData.tokens.add(token);
vaultData.tokenStake[token] = vaultData.tokenStake[token].add(1);
// update total token staked
_allStakedTokens.add(token);
stakedTokenTotal[token] = stakedTokenTotal[token].add(1);
// perform transfer to vault
IERC721(token).safeTransferFrom(msg.sender, vault, tokenId);
// call lock on vault
IUniversalVaultV2(vault).lockERC721(token, tokenId, permission);
// check if there is a reward program currently running
if (lmRewards[token].startedAt != 0) {
address rewardCalcInstance = lmRewards[token].rewardCalcInstance;
(,uint rewardEarned,) = IERC2917(rewardCalcInstance).increaseProductivity(msg.sender, 1);
earnedLMRewards[msg.sender][token] = earnedLMRewards[msg.sender][token].add(rewardEarned);
}
// emit event
emit Staked(vault, token, tokenId);
}
/// @notice Unstake ERC721 tokens and claim reward
/// @dev LM rewards can only be claimed when unstaking
/// access control: anyone with permission
/// state machine:
/// - when vault exists on this UniStakerV2
/// - after stake from vault
/// - can be called multiple times while sufficient stake remains
/// - only online
/// state scope:
/// - decrease _vaults[vault].tokenStake[token]
/// - delete token from _vaults[vault].tokens if token stake is 0
/// - decrease stakedTokenTotal[token]
/// - delete token from _allStakedTokens if total token stake is 0
/// token transfer:
/// - transfer reward tokens from reward pool to recipient
/// - transfer bonus tokens from reward pool to recipient
/// @param vault address The vault to unstake from
/// @param vaultFactory address The vault factory that created this vault
/// @param recipient address The recipient to send reward to
/// @param token address The staking token
/// @param tokenId uint256 The id of the token to unstake
/// @param claimBonusReward bool flag to claim bonus rewards
function unstakeERC721AndClaimReward(
address vault,
address vaultFactory,
address recipient,
address token,
uint256 tokenId,
bool claimBonusReward,
bytes calldata permission
) external override onlyOnline {
require(_vaultSet.contains(vault), "UniStakerV2: no vault");
// fetch vault storage reference
VaultData storage vaultData = _vaults[vault];
// validate recipient
require(isValidAddress(recipient), "UniStakerV2: invalid recipient");
// check for sufficient vault stake amount
require(vaultData.tokens.contains(token), "UniStakerV2: no token in vault");
// check for sufficient vault stake amount
require(vaultData.tokenStake[token] >= 1, "UniStakerV2: insufficient vault token stake");
// check for sufficient total token stake amount
// if the above check succeeds and this check fails, there is a bug in stake accounting
require(stakedTokenTotal[token] >= 1, "stakedTokenTotal[token] is less than 1");
// check if there is a reward program currently running
uint rewardEarned = earnedLMRewards[msg.sender][token];
if (lmRewards[token].startedAt != 0) {
address rewardCalcInstance = lmRewards[token].rewardCalcInstance;
(,uint newReward,) = IERC2917(rewardCalcInstance).decreaseProductivity(msg.sender, 1);
rewardEarned = rewardEarned.add(newReward);
}
// decrease totalStake of token in this vault
vaultData.tokenStake[token] = vaultData.tokenStake[token].sub(1);
if (vaultData.tokenStake[token] == 0) {
vaultData.tokens.remove(token);
delete vaultData.tokenStake[token];
}
// decrease stakedTokenTotal across all vaults
stakedTokenTotal[token] = stakedTokenTotal[token].sub(1);
if (stakedTokenTotal[token] == 0) {
_allStakedTokens.remove(token);
delete stakedTokenTotal[token];
}
// unlock staking tokens from vault
IUniversalVaultV2(vault).unlockERC721(token, tokenId, permission);
// emit event
emit Unstaked(vault, token, tokenId);
// only perform on non-zero reward
if (rewardEarned > 0) {
// transfer bonus tokens from reward pool to recipient
// bonus tokens can only be claimed during an active rewards program
if (claimBonusReward && lmRewards[token].startedAt != 0) {
for (uint256 index = 0; index < lmRewards[token].bonusTokens.length(); index++) {
// fetch bonus token address reference
address bonusToken = lmRewards[token].bonusTokens.at(index);
// calculate bonus token amount
// bonusAmount = rewardEarned * allocatedBonusReward / allocatedMainReward
uint256 bonusAmount = rewardEarned.mul(lmRewards[token].bonusTokenAmounts[bonusToken]).div(lmRewards[token].amount);
// transfer bonus token
IRewardPool(rewardPool).sendERC20(bonusToken, recipient, bonusAmount);
// emit event
emit RewardClaimed(vault, recipient, bonusToken, bonusAmount);
}
}
// take care of multiplier
uint multipliedReward = _tierMultipliedReward(uint(vault), vaultFactory, rewardEarned);
// take care of vesting
uint vestingPortion = multipliedReward.mul(LM_REWARD_VESTING_PORTION_NUM).div(LM_REWARD_VESTING_PORTION_DENOM);
vestingLMRewards[msg.sender][token].push(LMRewardVestingData(vestingPortion, block.timestamp));
vestingLMTokenRewards[msg.sender].add(token);
// set earned reward to 0
earnedLMRewards[msg.sender][token] = 0;
// transfer reward tokens from reward pool to recipient
IRewardPool(rewardPool).sendERC20(rewardToken, recipient, multipliedReward.sub(vestingPortion));
// emit event
emit RewardClaimed(vault, recipient, rewardToken, rewardEarned);
}
}
function claimVestedReward() external override onlyOnline {
uint numTokens = vestingLMTokenRewards[msg.sender].length();
for (uint index = 0; index < numTokens; index++) {
address token = vestingLMTokenRewards[msg.sender].at(index);
claimVestedReward(token, vestingLMRewards[msg.sender][token].length);
}
}
function claimVestedReward(address token) external override onlyOnline {
claimVestedReward(token, vestingLMRewards[msg.sender][token].length);
}
function claimVestedReward(address token, uint numVests) public onlyOnline {
require(numVests <= vestingLMRewards[msg.sender][token].length, "num vests can't be greater than available vests");
LMRewardVestingData[] storage vests = vestingLMRewards[msg.sender][token];
uint vestedReward;
for (uint index = 0; index < numVests; index++) {
LMRewardVestingData storage vest = vests[index];
uint duration = block.timestamp.sub(vest.startedAt);
uint vested = vest.amount.mul(duration).div(LM_REWARD_VESTING_PERIOD);
if (vested >= vest.amount) {
// completely vested
vested = vest.amount;
// copy last element into this slot and pop last
vests[index] = vests[vests.length - 1];
vests.pop();
index--;
numVests--;
// if all vested remove from set
if (vests.length == 0) {
vestingLMTokenRewards[msg.sender].remove(token);
break;
}
} else {
vest.amount = vest.amount.sub(vested);
}
vestedReward = vestedReward.add(vested);
}
if (vestedReward > 0) {
// transfer reward tokens from reward pool to recipient
IRewardPool(rewardPool).sendERC20(rewardToken, msg.sender, vestedReward);
// emit event
emit VestedRewardClaimed(msg.sender, rewardToken, vestedReward);
}
}
}
// 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 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 "./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;
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 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 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.
*
* 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) {
revert("ECDSA: invalid signature length");
}
// 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)))
}
return recover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover-bytes32-bytes-} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) 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.
require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value");
require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value");
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
require(signer != address(0), "ECDSA: invalid signature");
return signer;
}
/**
* @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));
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.7.6;
interface IFactory {
function create(bytes calldata args) external returns (address instance);
function create2(bytes calldata args, bytes32 salt) external returns (address instance);
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.7.6;
import {EnumerableSet} from "@openzeppelin/contracts/utils/EnumerableSet.sol";
interface IInstanceRegistry {
/* events */
event InstanceAdded(address instance);
event InstanceRemoved(address instance);
/* view functions */
function isInstance(address instance) external view returns (bool validity);
function instanceCount() external view returns (uint256 count);
function instanceAt(uint256 index) external view returns (address instance);
}
/// @title InstanceRegistry
contract InstanceRegistry is IInstanceRegistry {
using EnumerableSet for EnumerableSet.AddressSet;
/* storage */
EnumerableSet.AddressSet private _instanceSet;
/* view functions */
function isInstance(address instance) external view override returns (bool validity) {
return _instanceSet.contains(instance);
}
function instanceCount() external view override returns (uint256 count) {
return _instanceSet.length();
}
function instanceAt(uint256 index) external view override returns (address instance) {
return _instanceSet.at(index);
}
/* admin functions */
function _register(address instance) internal {
require(_instanceSet.add(instance), "InstanceRegistry: already registered");
emit InstanceAdded(instance);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.7.6;
import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol";
import {ERC721} from "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {IFactory} from "../factory/IFactory.sol";
import {IInstanceRegistry} from "../factory/InstanceRegistry.sol";
import {ProxyFactory} from "../factory/ProxyFactory.sol";
import {IUniversalVault} from "./MethodVault.sol";
/// @title MethodNFTFactory
contract MethodNFTFactory is Ownable, IFactory, IInstanceRegistry, ERC721 {
using SafeMath for uint256;
bytes32[] public names;
mapping(bytes32=>address) public templates;
bytes32 public activeTemplate;
uint256 public tokenSerialNumber;
mapping(uint256=>uint256) public serialNumberToTokenId;
mapping(uint256=>uint256) public tokenIdToSerialNumber;
mapping(address=>address[]) private ownerToVaultsMap;
event TemplateAdded(bytes32 indexed name, address indexed template);
event TemplateActive(bytes32 indexed name, address indexed template);
constructor() ERC721("MethodNFT", "MTHDNFT") {
ERC721._setBaseURI("https://api.methodfi.co/nft/");
}
function addTemplate(bytes32 name, address template) public onlyOwner {
require(templates[name] == address(0), "Template already exists");
templates[name] = template;
if(names.length == 0) {
activeTemplate = name;
emit TemplateActive(name, template);
}
names.push(name);
emit TemplateAdded(name, template);
}
function setActive(bytes32 name) public onlyOwner {
require(templates[name] != address(0), "Template does not exist");
activeTemplate = name;
emit TemplateActive(name, templates[name]);
}
/* registry functions */
function isInstance(address instance) external view override returns (bool validity) {
return ERC721._exists(uint256(instance));
}
function instanceCount() external view override returns (uint256 count) {
return ERC721.totalSupply();
}
function instanceAt(uint256 index) external view override returns (address instance) {
return address(ERC721.tokenByIndex(index));
}
/* factory functions */
function create(bytes calldata) external override returns (address vault) {
return createSelected(activeTemplate);
}
function create2(bytes calldata, bytes32 salt) external override returns (address vault) {
return createSelected2(activeTemplate, salt);
}
function create() public returns (address vault) {
return createSelected(activeTemplate);
}
function create2(bytes32 salt) public returns (address vault) {
return createSelected2(activeTemplate, salt);
}
function createSelected(bytes32 name) public returns (address vault) {
// create clone and initialize
vault = ProxyFactory._create(
templates[name],
abi.encodeWithSelector(IUniversalVault.initialize.selector)
);
// mint nft to caller
uint256 tokenId = uint256(vault);
ERC721._safeMint(msg.sender, tokenId);
// push vault to owner's map
ownerToVaultsMap[msg.sender].push(vault);
// update serial number
tokenSerialNumber = tokenSerialNumber.add(1);
serialNumberToTokenId[tokenSerialNumber] = tokenId;
tokenIdToSerialNumber[tokenId] = tokenSerialNumber;
// emit event
emit InstanceAdded(vault);
// explicit return
return vault;
}
function createSelected2(bytes32 name, bytes32 salt) public returns (address vault) {
// create clone and initialize
vault = ProxyFactory._create2(
templates[name],
abi.encodeWithSelector(IUniversalVault.initialize.selector),
salt
);
// mint nft to caller
uint256 tokenId = uint256(vault);
ERC721._safeMint(msg.sender, tokenId);
// push vault to owner's map
ownerToVaultsMap[msg.sender].push(vault);
// update serial number
tokenSerialNumber = tokenSerialNumber.add(1);
serialNumberToTokenId[tokenSerialNumber] = tokenId;
tokenIdToSerialNumber[tokenId] = tokenSerialNumber;
// emit event
emit InstanceAdded(vault);
// explicit return
return vault;
}
/* getter functions */
function nameCount() public view returns(uint256) {
return names.length;
}
function vaultCount(address owner) public view returns(uint256) {
return ownerToVaultsMap[owner].length;
}
function getVault(address owner, uint256 index) public view returns (address) {
return ownerToVaultsMap[owner][index];
}
function getAllVaults(address owner) public view returns (address [] memory) {
return ownerToVaultsMap[owner];
}
function getTemplate() external view returns (address) {
return templates[activeTemplate];
}
function getVaultOfNFT(uint256 nftId) public pure returns (address) {
return address(nftId);
}
function getNFTOfVault(address vault) public pure returns (uint256) {
return uint256(vault);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.7.6;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {TransferHelper} from "@uniswap/lib/contracts/libraries/TransferHelper.sol";
import {Powered} from "./Powered.sol";
interface IRewardPool {
function sendERC20(
address token,
address to,
uint256 value
) external;
function rescueERC20(address[] calldata tokens, address recipient) external;
}
/// @title Reward Pool
/// @notice Vault for isolated storage of reward tokens
contract RewardPool is IRewardPool, Powered, Ownable {
/* initializer */
constructor(address powerSwitch) {
Powered._setPowerSwitch(powerSwitch);
}
/* user functions */
/// @notice Send an ERC20 token
/// access control: only owner
/// state machine:
/// - can be called multiple times
/// - only online
/// state scope: none
/// token transfer: transfer tokens from self to recipient
/// @param token address The token to send
/// @param to address The recipient to send to
/// @param value uint256 Amount of tokens to send
function sendERC20(
address token,
address to,
uint256 value
) external override onlyOwner onlyOnline {
TransferHelper.safeTransfer(token, to, value);
}
/* emergency functions */
/// @notice Rescue multiple ERC20 tokens
/// access control: only power controller
/// state machine:
/// - can be called multiple times
/// - only shutdown
/// state scope: none
/// token transfer: transfer tokens from self to recipient
/// @param tokens address[] The tokens to rescue
/// @param recipient address The recipient to rescue to
function rescueERC20(address[] calldata tokens, address recipient)
external
override
onlyShutdown
{
// only callable by controller
require(
msg.sender == Powered.getPowerController(),
"RewardPool: only controller can withdraw after shutdown"
);
// assert recipient is defined
require(recipient != address(0), "RewardPool: recipient not defined");
// transfer tokens
for (uint256 index = 0; index < tokens.length; index++) {
// get token
address token = tokens[index];
// get balance
uint256 balance = IERC20(token).balanceOf(address(this));
// transfer token
TransferHelper.safeTransfer(token, recipient, balance);
}
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.7.6;
import {IPowerSwitch} from "./PowerSwitch.sol";
interface IPowered {
function isOnline() external view returns (bool status);
function isOffline() external view returns (bool status);
function isShutdown() external view returns (bool status);
function getPowerSwitch() external view returns (address powerSwitch);
function getPowerController() external view returns (address controller);
}
/// @title Powered
/// @notice Helper for calling external PowerSwitch
contract Powered is IPowered {
/* storage */
address private _powerSwitch;
/* modifiers */
modifier onlyOnline() {
require(isOnline(), "Powered: is not online");
_;
}
modifier onlyOffline() {
require(isOffline(), "Powered: is not offline");
_;
}
modifier notShutdown() {
require(!isShutdown(), "Powered: is shutdown");
_;
}
modifier onlyShutdown() {
require(isShutdown(), "Powered: is not shutdown");
_;
}
/* initializer */
function _setPowerSwitch(address powerSwitch) internal {
_powerSwitch = powerSwitch;
}
/* getter functions */
function isOnline() public view override returns (bool status) {
return IPowerSwitch(_powerSwitch).isOnline();
}
function isOffline() public view override returns (bool status) {
return IPowerSwitch(_powerSwitch).isOffline();
}
function isShutdown() public view override returns (bool status) {
return IPowerSwitch(_powerSwitch).isShutdown();
}
function getPowerSwitch() public view override returns (address powerSwitch) {
return _powerSwitch;
}
function getPowerController() public view override returns (address controller) {
return IPowerSwitch(_powerSwitch).getPowerController();
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.7.6;
interface IERC2917 {
/// @dev This emits when interests amount per block is changed by the owner of the contract.
/// It emits with the old interests amount and the new interests amount.
event InterestRatePerBlockChanged (uint oldValue, uint newValue);
/// @dev This emits when a users' productivity has changed
/// It emits with the user's address and the the value after the change.
event ProductivityIncreased (address indexed user, uint value);
/// @dev This emits when a users' productivity has changed
/// It emits with the user's address and the the value after the change.
event ProductivityDecreased (address indexed user, uint value);
function initialize() external;
/// @dev Note best practice will be to restrict the caller to staking contract address.
function setImplementor(address newImplementor) external;
/// @dev Return the current contract's interest rate per block.
/// @return The amount of interests currently producing per each block.
function interestsPerBlock() external view returns (uint);
/// @notice Change the current contract's interest rate.
/// @dev Note best practice will be to restrict the caller to staking contract address.
/// @return The true/fase to notice that the value has successfully changed or not, when it succeeds, it will emit the InterestRatePerBlockChanged event.
function changeInterestRatePerBlock(uint value) external returns (bool);
/// @notice It will get the productivity of a given user.
/// @dev it will return 0 if user has no productivity in the contract.
/// @return user's productivity and overall productivity.
function getProductivity(address user) external view returns (uint, uint);
/// @notice increase a user's productivity.
/// @dev Note best practice will be to restrict the caller to staking contract address.
/// @return productivity added status as well as interest earned prior period and total productivity
function increaseProductivity(address user, uint value) external returns (bool, uint, uint);
/// @notice decrease a user's productivity.
/// @dev Note best practice will be to restrict the caller to staking contract address.
/// @return productivity removed status as well as interest earned prior period and total productivity
function decreaseProductivity(address user, uint value) external returns (bool, uint, uint);
/// @notice take() will return the interest that callee will get at current block height.
/// @dev it will always be calculated by block.number, so it will change when block height changes.
/// @return amount of the interest that user is able to mint() at current block height.
function take() external view returns (uint);
/// @notice similar to take(), but with the block height joined to calculate return.
/// @dev for instance, it returns (_amount, _block), which means at block height _block, the callee has accumulated _amount of interest.
/// @return amount of interest and the block height.
function takeWithBlock() external view returns (uint, uint);
/// @notice mint the avaiable interests to callee.
/// @dev once it mints, the amount of interests will transfer to callee's address.
/// @return the amount of interest minted.
function mint() external returns (uint);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
import {Clones} from "@openzeppelin/contracts/proxy/Clones.sol";
library ProxyFactory {
/* functions */
function _create(address logic, bytes memory data) internal returns (address proxy) {
// deploy clone
proxy = Clones.clone(logic);
// attempt initialization
if (data.length > 0) {
(bool success, bytes memory err) = proxy.call(data);
require(success, string(err));
}
// explicit return
return proxy;
}
function _create2(
address logic,
bytes memory data,
bytes32 salt
) internal returns (address proxy) {
// deploy clone
proxy = Clones.cloneDeterministic(logic, salt);
// attempt initialization
if (data.length > 0) {
(bool success, bytes memory err) = proxy.call(data);
require(success, string(err));
}
// explicit return
return proxy;
}
}
// 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: GPL-3.0-only
pragma solidity 0.7.6;
pragma abicoder v2;
import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {ERC721} from "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import {Initializable} from "@openzeppelin/contracts/proxy/Initializable.sol";
import {EnumerableSet} from "@openzeppelin/contracts/utils/EnumerableSet.sol";
import {Address} from "@openzeppelin/contracts/utils/Address.sol";
import {TransferHelper} from "@uniswap/lib/contracts/libraries/TransferHelper.sol";
import {EIP712} from "./EIP712.sol";
import {ERC1271} from "./ERC1271.sol";
import {OwnableByERC721} from "./OwnableByERC721.sol";
import {IRageQuit} from "../staking/UniStaker.sol";
interface IUniversalVault {
/* user events */
event Locked(address delegate, address token, uint256 amount);
event Unlocked(address delegate, address token, uint256 amount);
event RageQuit(address delegate, address token, bool notified, string reason);
/* data types */
struct LockData {
address delegate;
address token;
uint256 balance;
}
/* initialize function */
function initialize() external;
/* user functions */
function lock(
address token,
uint256 amount,
bytes calldata permission
) external;
function unlock(
address token,
uint256 amount,
bytes calldata permission
) external;
function rageQuit(address delegate, address token)
external
returns (bool notified, string memory error);
function transferERC20(
address token,
address to,
uint256 amount
) external;
function transferETH(address to, uint256 amount) external payable;
/* pure functions */
function calculateLockID(address delegate, address token)
external
pure
returns (bytes32 lockID);
/* getter functions */
function getPermissionHash(
bytes32 eip712TypeHash,
address delegate,
address token,
uint256 amount,
uint256 nonce
) external view returns (bytes32 permissionHash);
function getNonce() external view returns (uint256 nonce);
function owner() external view returns (address ownerAddress);
function getLockSetCount() external view returns (uint256 count);
function getLockAt(uint256 index) external view returns (LockData memory lockData);
function getBalanceDelegated(address token, address delegate)
external
view
returns (uint256 balance);
function getBalanceLocked(address token) external view returns (uint256 balance);
function checkBalances() external view returns (bool validity);
}
/// @title MethodVault
/// @notice Vault for isolated storage of staking tokens
/// @dev Warning: not compatible with rebasing tokens
contract MethodVault is
IUniversalVault,
EIP712("UniversalVault", "1.0.0"),
ERC1271,
OwnableByERC721,
Initializable
{
using SafeMath for uint256;
using Address for address;
using Address for address payable;
using EnumerableSet for EnumerableSet.Bytes32Set;
/* constant */
// Hardcoding a gas limit for rageQuit() is required to prevent gas DOS attacks
// the gas requirement cannot be determined at runtime by querying the delegate
// as it could potentially be manipulated by a malicious delegate who could force
// the calls to revert.
// The gas limit could alternatively be set upon vault initialization or creation
// of a lock, but the gas consumption trade-offs are not favorable.
// Ultimately, to avoid a need for fixed gas limits, the EVM would need to provide
// an error code that allows for reliably catching out-of-gas errors on remote calls.
uint256 public constant RAGEQUIT_GAS = 500000;
bytes32 public constant LOCK_TYPEHASH =
keccak256("Lock(address delegate,address token,uint256 amount,uint256 nonce)");
bytes32 public constant UNLOCK_TYPEHASH =
keccak256("Unlock(address delegate,address token,uint256 amount,uint256 nonce)");
string public constant VERSION = "1.0.0";
/* storage */
uint256 private _nonce;
mapping(bytes32 => LockData) private _locks;
EnumerableSet.Bytes32Set private _lockSet;
/* initialization function */
function initializeLock() external initializer {}
function initialize() external override initializer {
OwnableByERC721._setNFT(msg.sender);
}
/* ether receive */
receive() external payable {}
/* internal overrides */
function _getOwner() internal view override(ERC1271) returns (address ownerAddress) {
return OwnableByERC721.owner();
}
/* pure functions */
function calculateLockID(address delegate, address token)
public
pure
override
returns (bytes32 lockID)
{
return keccak256(abi.encodePacked(delegate, token));
}
/* getter functions */
function getPermissionHash(
bytes32 eip712TypeHash,
address delegate,
address token,
uint256 amount,
uint256 nonce
) public view override returns (bytes32 permissionHash) {
return
EIP712._hashTypedDataV4(
keccak256(abi.encode(eip712TypeHash, delegate, token, amount, nonce))
);
}
function getNonce() external view override returns (uint256 nonce) {
return _nonce;
}
function owner()
public
view
override(IUniversalVault, OwnableByERC721)
returns (address ownerAddress)
{
return OwnableByERC721.owner();
}
function getLockSetCount() external view override returns (uint256 count) {
return _lockSet.length();
}
function getLockAt(uint256 index) external view override returns (LockData memory lockData) {
return _locks[_lockSet.at(index)];
}
function getBalanceDelegated(address token, address delegate)
external
view
override
returns (uint256 balance)
{
return _locks[calculateLockID(delegate, token)].balance;
}
function getBalanceLocked(address token) public view override returns (uint256 balance) {
uint256 count = _lockSet.length();
for (uint256 index; index < count; index++) {
LockData storage _lockData = _locks[_lockSet.at(index)];
if (_lockData.token == token && _lockData.balance > balance)
balance = _lockData.balance;
}
return balance;
}
function checkBalances() external view override returns (bool validity) {
// iterate over all token locks and validate sufficient balance
uint256 count = _lockSet.length();
for (uint256 index; index < count; index++) {
// fetch storage lock reference
LockData storage _lockData = _locks[_lockSet.at(index)];
// if insufficient balance and not shutdown, return false
if (IERC20(_lockData.token).balanceOf(address(this)) < _lockData.balance) return false;
}
// if sufficient balance or shutdown, return true
return true;
}
/* user functions */
/// @notice Lock ERC20 tokens in the vault
/// access control: called by delegate with signed permission from owner
/// state machine: anytime
/// state scope:
/// - insert or update _locks
/// - increase _nonce
/// token transfer: none
/// @param token Address of token being locked
/// @param amount Amount of tokens being locked
/// @param permission Permission signature payload
function lock(
address token,
uint256 amount,
bytes calldata permission
)
external
override
onlyValidSignature(
getPermissionHash(LOCK_TYPEHASH, msg.sender, token, amount, _nonce),
permission
)
{
// get lock id
bytes32 lockID = calculateLockID(msg.sender, token);
// add lock to storage
if (_lockSet.contains(lockID)) {
// if lock already exists, increase amount
_locks[lockID].balance = _locks[lockID].balance.add(amount);
} else {
// if does not exist, create new lock
// add lock to set
assert(_lockSet.add(lockID));
// add lock data to storage
_locks[lockID] = LockData(msg.sender, token, amount);
}
// validate sufficient balance
require(
IERC20(token).balanceOf(address(this)) >= _locks[lockID].balance,
"UniversalVault: insufficient balance"
);
// increase nonce
_nonce += 1;
// emit event
emit Locked(msg.sender, token, amount);
}
/// @notice Unlock ERC20 tokens in the vault
/// access control: called by delegate with signed permission from owner
/// state machine: after valid lock from delegate
/// state scope:
/// - remove or update _locks
/// - increase _nonce
/// token transfer: none
/// @param token Address of token being unlocked
/// @param amount Amount of tokens being unlocked
/// @param permission Permission signature payload
function unlock(
address token,
uint256 amount,
bytes calldata permission
)
external
override
onlyValidSignature(
getPermissionHash(UNLOCK_TYPEHASH, msg.sender, token, amount, _nonce),
permission
)
{
// get lock id
bytes32 lockID = calculateLockID(msg.sender, token);
// validate existing lock
require(_lockSet.contains(lockID), "UniversalVault: missing lock");
// update lock data
if (_locks[lockID].balance > amount) {
// substract amount from lock balance
_locks[lockID].balance = _locks[lockID].balance.sub(amount);
} else {
// delete lock data
delete _locks[lockID];
assert(_lockSet.remove(lockID));
}
// increase nonce
_nonce += 1;
// emit event
emit Unlocked(msg.sender, token, amount);
}
/// @notice Forcibly cancel delegate lock
/// @dev This function will attempt to notify the delegate of the rage quit using a fixed amount of gas.
/// access control: only owner
/// state machine: after valid lock from delegate
/// state scope:
/// - remove item from _locks
/// token transfer: none
/// @param delegate Address of delegate
/// @param token Address of token being unlocked
function rageQuit(address delegate, address token)
external
override
onlyOwner
returns (bool notified, string memory error)
{
// get lock id
bytes32 lockID = calculateLockID(delegate, token);
// validate existing lock
require(_lockSet.contains(lockID), "UniversalVault: missing lock");
// attempt to notify delegate
if (delegate.isContract()) {
// check for sufficient gas
require(gasleft() >= RAGEQUIT_GAS, "UniversalVault: insufficient gas");
// attempt rageQuit notification
try IRageQuit(delegate).rageQuit{gas: RAGEQUIT_GAS}() {
notified = true;
} catch Error(string memory res) {
notified = false;
error = res;
} catch (bytes memory) {
notified = false;
}
}
// update lock storage
assert(_lockSet.remove(lockID));
delete _locks[lockID];
// emit event
emit RageQuit(delegate, token, notified, error);
}
/// @notice Transfer ERC20 tokens out of vault
/// access control: only owner
/// state machine: when balance >= max(lock) + amount
/// state scope: none
/// token transfer: transfer any token
/// @param token Address of token being transferred
/// @param to Address of the recipient
/// @param amount Amount of tokens to transfer
function transferERC20(
address token,
address to,
uint256 amount
) external override onlyOwner {
// check for sufficient balance
require(
IERC20(token).balanceOf(address(this)) >= getBalanceLocked(token).add(amount),
"UniversalVault: insufficient balance"
);
// perform transfer
TransferHelper.safeTransfer(token, to, amount);
}
/// @notice Transfer ERC20 tokens out of vault
/// access control: only owner
/// state machine: when balance >= amount
/// state scope: none
/// token transfer: transfer any token
/// @param to Address of the recipient
/// @param amount Amount of ETH to transfer
function transferETH(address to, uint256 amount) external payable override onlyOwner {
// perform transfer
TransferHelper.safeTransferETH(to, amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <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 `master`.
*
* This function uses the create opcode, which should never revert.
*/
function clone(address master) 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, master))
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 `master`.
*
* This function uses the create2 opcode and a `salt` to deterministically deploy
* the clone. Using the same `master` and `salt` multiple time will revert, since
* the clones cannot be deployed twice at the same address.
*/
function cloneDeterministic(address master, 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, master))
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 master, 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, master))
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 master, bytes32 salt) internal view returns (address predicted) {
return predictDeterministicAddress(master, salt, address(this));
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.7.6;
pragma abicoder v2;
import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol";
import {EnumerableSet} from "@openzeppelin/contracts/utils/EnumerableSet.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {TransferHelper} from "@uniswap/lib/contracts/libraries/TransferHelper.sol";
import {IFactory} from "../factory/IFactory.sol";
import {IInstanceRegistry} from "../factory/InstanceRegistry.sol";
import {IUniversalVault} from "../methodNFT/MethodVault.sol";
import {MethodNFTFactory} from "../methodNFT/MethodNFTFactory.sol";
import {IRewardPool} from "./RewardPool.sol";
import {Powered} from "./Powered.sol";
import {IERC2917} from "./IERC2917.sol";
import {ProxyFactory} from "../factory/ProxyFactory.sol";
interface IRageQuit {
function rageQuit() external;
}
interface IUniStaker is IRageQuit {
/* admin events */
event UniStakerCreated(address rewardPool, address powerSwitch);
event UniStakerFunded(address token, uint256 amount);
event BonusTokenRegistered(address token);
event BonusTokenRemoved(address token);
event VaultFactoryRegistered(address factory);
event VaultFactoryRemoved(address factory);
event AdminshipTransferred(address indexed previousAdmin, address indexed newAdmin);
/* user events */
event Staked(address vault, uint256 amount);
event Unstaked(address vault, uint256 amount);
event RageQuit(address vault);
event RewardClaimed(address vaultFactory, address recipient, address token, uint256 amount);
event VestedRewardClaimed(address recipient, address token, uint amount);
/* data types */
struct VaultData {
// token address to total token stake mapping
mapping(address => uint) tokenStake;
EnumerableSet.AddressSet tokens;
}
struct LMRewardData {
uint256 amount;
uint256 duration;
uint256 startedAt;
address rewardCalcInstance;
EnumerableSet.AddressSet bonusTokens;
mapping(address => uint) bonusTokenAmounts;
}
struct LMRewardVestingData {
uint amount;
uint startedAt;
}
/* getter functions */
function getBonusTokenSetLength() external view returns (uint256 length);
function getBonusTokenAtIndex(uint256 index) external view returns (address bonusToken);
function getVaultFactorySetLength() external view returns (uint256 length);
function getVaultFactoryAtIndex(uint256 index) external view returns (address factory);
function getNumVaults() external view returns (uint256 num);
function getVaultAt(uint256 index) external view returns (address vault);
function getNumTokensStaked() external view returns (uint256 num);
function getTokenStakedAt(uint256 index) external view returns (address token);
function getNumTokensStakedInVault(address vault) external view returns (uint256 num);
function getVaultTokenAtIndex(address vault, uint256 index) external view returns (address vaultToken);
function getVaultTokenStake(address vault, address token) external view returns (uint256 tokenStake);
function getLMRewardData(address token) external view returns (uint amount, uint duration, uint startedAt, address rewardCalcInstance);
function getLMRewardBonusTokensLength(address token) external view returns (uint length);
function getLMRewardBonusTokenAt(address token, uint index) external view returns (address bonusToken, uint bonusTokenAmount);
function getNumVestingLMTokenRewards(address user) external view returns (uint num);
function getVestingLMTokenAt(address user, uint index) external view returns (address token);
function getNumVests(address user, address token) external view returns (uint num);
function getNumRewardCalcTemplates() external view returns (uint num);
function getLMRewardVestingData(address user, address token, uint index) external view returns (uint amount, uint startedAt);
function isValidAddress(address target) external view returns (bool validity);
function isValidVault(address vault, address factory) external view returns (bool validity);
/* user functions */
function stake(
address vault,
address vaultFactory,
address token,
uint256 amount,
bytes calldata permission
) external;
function unstakeAndClaim(
address vault,
address vaultFactory,
address recipient,
address token,
uint256 amount,
bool claimBonusReward,
bytes calldata permission
) external;
function claimAirdropReward(address nftFactory) external;
function claimAirdropReward(address nftFactory, uint256[] calldata tokenIds) external;
function claimVestedReward() external;
function claimVestedReward(address token) external;
}
/// @title UniStaker
/// @notice Reward distribution contract
/// Access Control
/// - Power controller:
/// Can power off / shutdown the UniStaker
/// Can withdraw rewards from reward pool once shutdown
/// - Owner:
/// Is unable to operate on user funds due to UniversalVault
/// Is unable to operate on reward pool funds when reward pool is offline / shutdown
/// - UniStaker admin:
/// Can add funds to the UniStaker, register bonus tokens, and whitelist new vault factories
/// Is a subset of owner permissions
/// - User:
/// Can stake / unstake / ragequit / claim airdrop / claim vested rewards
/// UniStaker State Machine
/// - Online:
/// UniStaker is operating normally, all functions are enabled
/// - Offline:
/// UniStaker is temporarely disabled for maintenance
/// User staking and unstaking is disabled, ragequit remains enabled
/// Users can delete their stake through rageQuit() but forego their pending reward
/// Should only be used when downtime required for an upgrade
/// - Shutdown:
/// UniStaker is permanently disabled
/// All functions are disabled with the exception of ragequit
/// Users can delete their stake through rageQuit()
/// Power controller can withdraw from the reward pool
/// Should only be used if Owner role is compromised
contract UniStaker is IUniStaker, Powered {
using SafeMath for uint256;
using EnumerableSet for EnumerableSet.AddressSet;
/* constants */
string public constant PLATINUM = "PLATINUM";
string public constant GOLD = "GOLD";
string public constant MINT = "MINT";
string public constant BLACK = "BLACK";
uint public PLATINUM_LM_REWARD_MULTIPLIER_NUM = 5;
uint public PLATINUM_LM_REWARD_MULTIPLIER_DENOM = 2;
uint public GOLD_LM_REWARD_MULTIPLIER_NUM = 2;
uint public GOLD_LM_REWARD_MULTIPLIER_DENOM = 1;
uint public MINT_LM_REWARD_MULTIPLIER_NUM = 3;
uint public MINT_LM_REWARD_MULTIPLIER_DENOM = 2;
uint public BLACK_LM_REWARD_MULTIPLIER_NUM = 1;
uint public BLACK_LM_REWARD_MULTIPLIER_DENOM = 1;
uint public LM_REWARD_VESTING_PERIOD = 7776000; // 3 months
uint public LM_REWARD_VESTING_PORTION_NUM = 1;
uint public LM_REWARD_VESTING_PORTION_DENOM = 2;
// An upper bound on the number of active tokens staked per vault is required to prevent
// calls to rageQuit() from reverting.
// With 30 tokens staked in a vault, ragequit costs 432811 gas which is conservatively lower
// than the hardcoded limit of 500k gas on the vault.
// This limit is configurable and could be increased in a future deployment.
// Ultimately, to avoid a need for fixed upper bounds, the EVM would need to provide
// an error code that allows for reliably catching out-of-gas errors on remote calls.
uint256 public MAX_TOKENS_STAKED_PER_VAULT = 30;
uint256 public MAX_BONUS_TOKENS = 50;
uint256 public MIN_AIRDROP_REWARD_CLAIM_FREQUENCY = 604800; // week in seconds
/* storage */
address public admin;
address public rewardToken;
address public rewardPool;
EnumerableSet.AddressSet private _vaultSet;
mapping(address => VaultData) private _vaults;
EnumerableSet.AddressSet private _bonusTokenSet;
EnumerableSet.AddressSet private _vaultFactorySet;
EnumerableSet.AddressSet private _allStakedTokens;
mapping(address => uint256) public stakedTokenTotal;
mapping(address => LMRewardData) private lmRewards;
// user to token to earned reward mapping
mapping(address => mapping(address => uint)) public earnedLMRewards;
// user to token to vesting data mapping
mapping(address => mapping(address => LMRewardVestingData[])) public vestingLMRewards;
// user to vesting lm token rewards set
mapping(address => EnumerableSet.AddressSet) private vestingLMTokenRewards;
// nft tier to amount
mapping(string => uint256) public weeklyAirdropAmounts;
mapping(string => uint256) public balancesRequiredToClaim;
// nft id to timestamp
mapping(uint256 => uint256) public nftLastClaimedRewardAt;
// erc2917 template names
string[] public rewardCalcTemplateNames;
// erc2917 template names to erc 2917 templates
mapping(string => address) public rewardCalcTemplates;
string public activeRewardCalcTemplate;
event RewardCalcTemplateAdded(string indexed name, address indexed template);
event RewardCalcTemplateActive(string indexed name, address indexed template);
/* initializer */
/// @notice Initizalize UniStaker
/// access control: only proxy constructor
/// state machine: can only be called once
/// state scope: set initialization variables
/// token transfer: none
/// @param adminAddress address The admin address
/// @param rewardPoolFactory address The factory to use for deploying the RewardPool
/// @param powerSwitchFactory address The factory to use for deploying the PowerSwitch
/// @param rewardTokenAddress address The address of the reward token for this UniStaker
constructor(
address adminAddress,
address rewardPoolFactory,
address powerSwitchFactory,
address rewardTokenAddress
) {
// deploy power switch
address powerSwitch = IFactory(powerSwitchFactory).create(abi.encode(adminAddress));
// deploy reward pool
rewardPool = IFactory(rewardPoolFactory).create(abi.encode(powerSwitch));
// set internal config
admin = adminAddress;
rewardToken = rewardTokenAddress;
Powered._setPowerSwitch(powerSwitch);
weeklyAirdropAmounts[PLATINUM] = uint256(166).mul(1e18);
weeklyAirdropAmounts[GOLD] = uint256(18).mul(1e18);
weeklyAirdropAmounts[MINT] = uint256(4).mul(1e18);
balancesRequiredToClaim[PLATINUM] = uint256(166).mul(1e18);
balancesRequiredToClaim[GOLD] = uint256(18).mul(1e18);
balancesRequiredToClaim[MINT] = uint256(4).mul(1e18);
// emit event
emit UniStakerCreated(rewardPool, powerSwitch);
}
/* admin functions */
function _admin() private view {
require(msg.sender == admin, "not allowed");
}
/**
* @dev Leaves the contract without admin. It will not be possible to call
* `admin` functions anymore. Can only be called by the current admin.
*
* NOTE: Renouncing adminship will leave the contract without an admin,
* thereby removing any functionality that is only available to the admin.
*/
function renounceAdminship() public {
_admin();
emit AdminshipTransferred(admin, address(0));
admin = address(0);
}
/**
* @dev Transfers adminship of the contract to a new account (`newAdmin`).
* Can only be called by the current admin.
*/
function transferAdminship(address newAdmin) public {
_admin();
require(newAdmin != address(0), "new admin can't the zero address");
emit AdminshipTransferred(admin, newAdmin);
admin = newAdmin;
}
/// @notice Add funds to UniStaker
/// access control: only admin
/// state machine:
/// - can be called multiple times
/// - only online
/// state scope:
/// - none
/// token transfer: transfer staking tokens from msg.sender to reward pool
/// @param amount uint256 Amount of reward tokens to deposit
function fund(address token, uint256 amount) external {
_admin();
require(_bonusTokenSet.contains(token) || token == rewardToken, "cannot fund with unrecognized token");
// transfer reward tokens to reward pool
TransferHelper.safeTransferFrom(
token,
msg.sender,
rewardPool,
amount
);
// emit event
emit UniStakerFunded(token, amount);
}
/// @notice Rescue tokens from RewardPool
/// @dev use this function to rescue tokens from RewardPool contract without distributing to stakers or triggering emergency shutdown
/// access control: only admin
/// state machine:
/// - can be called multiple times
/// - not shutdown
/// state scope: none
/// token transfer: transfer requested token from RewardPool to recipient
/// @param token address The address of the token to rescue
/// @param recipient address The address of the recipient
/// @param amount uint256 The amount of tokens to rescue
function rescueTokensFromRewardPool(
address token,
address recipient,
uint256 amount
) external {
_admin();
// verify recipient
require(isValidAddress(recipient), "invalid recipient");
// transfer tokens to recipient
IRewardPool(rewardPool).sendERC20(token, recipient, amount);
}
/// @notice Add vault factory to whitelist
/// @dev use this function to enable stakes to vaults coming from the specified factory contract
/// access control: only admin
/// state machine:
/// - can be called multiple times
/// - not shutdown
/// state scope:
/// - append to _vaultFactorySet
/// token transfer: none
/// @param factory address The address of the vault factory
function registerVaultFactory(address factory) external {
_admin();
// add factory to set
require(_vaultFactorySet.add(factory), "UniStaker: vault factory already registered");
// emit event
emit VaultFactoryRegistered(factory);
}
/// @notice Remove vault factory from whitelist
/// @dev use this function to disable new stakes to vaults coming from the specified factory contract.
/// note: vaults with existing stakes from this factory are sill able to unstake
/// access control: only admin
/// state machine:
/// - can be called multiple times
/// - not shutdown
/// state scope:
/// - remove from _vaultFactorySet
/// token transfer: none
/// @param factory address The address of the vault factory
function removeVaultFactory(address factory) external {
_admin();
// remove factory from set
require(_vaultFactorySet.remove(factory), "UniStaker: vault factory not registered");
// emit event
emit VaultFactoryRemoved(factory);
}
/// @notice Register bonus token for distribution
/// @dev use this function to enable distribution of any ERC20 held by the RewardPool contract
/// access control: only admin
/// state machine:
/// - can be called multiple times
/// - only online
/// state scope:
/// - append to _bonusTokenSet
/// token transfer: none
/// @param bonusToken address The address of the bonus token
function registerBonusToken(address bonusToken) external {
_admin();
// verify valid bonus token
require(isValidAddress(bonusToken), "invalid bonus token address or is already present");
// verify bonus token count
require(_bonusTokenSet.length() < MAX_BONUS_TOKENS, "UniStaker: max bonus tokens reached ");
// add token to set
_bonusTokenSet.add(bonusToken);
// emit event
emit BonusTokenRegistered(bonusToken);
}
/// @notice Remove bonus token
/// @dev use this function to disable distribution of a token held by the RewardPool contract
/// access control: only admin
/// state machine:
/// - can be called multiple times
/// - not shutdown
/// state scope:
/// - remove from _bonusTokenSet
/// token transfer: none
/// @param bonusToken address The address of the bonus token
function removeBonusToken(address bonusToken) external {
_admin();
require(_bonusTokenSet.remove(bonusToken), "UniStaker: bonus token not present ");
// emit event
emit BonusTokenRemoved(bonusToken);
}
function addRewardCalcTemplate(string calldata name, address template) external {
_admin();
require(rewardCalcTemplates[name] == address(0), "Template already exists");
rewardCalcTemplates[name] = template;
if(rewardCalcTemplateNames.length == 0) {
activeRewardCalcTemplate = name;
emit RewardCalcTemplateActive(name, template);
}
rewardCalcTemplateNames.push(name);
emit RewardCalcTemplateAdded(name, template);
}
function setRewardCalcActiveTemplate(string calldata name) external {
_admin();
require(rewardCalcTemplates[name] != address(0), "Template does not exist");
activeRewardCalcTemplate = name;
emit RewardCalcTemplateActive(name, rewardCalcTemplates[name]);
}
function startLMRewards(address token, uint256 amount, uint256 duration) external {
startLMRewards(token, amount, duration, activeRewardCalcTemplate);
}
function startLMRewards(address token, uint256 amount, uint256 duration, string memory rewardCalcTemplateName) public {
_admin();
require(lmRewards[token].startedAt == 0, "A reward program already live for this token");
require(rewardCalcTemplates[rewardCalcTemplateName] != address(0), "Reward Calculator Template does not exist");
// create reward calc clone from template
address rewardCalcInstance = ProxyFactory._create(rewardCalcTemplates[rewardCalcTemplateName], abi.encodeWithSelector(IERC2917.initialize.selector));
LMRewardData storage lmrd = lmRewards[token];
lmrd.amount = amount;
lmrd.duration = duration;
lmrd.startedAt = block.timestamp;
lmrd.rewardCalcInstance = rewardCalcInstance;
}
function setImplementorForRewardsCalculator(address token, address newImplementor) public {
_admin();
require(lmRewards[token].startedAt != 0, "No reward program currently live for this token");
address rewardCalcInstance = lmRewards[token].rewardCalcInstance;
IERC2917(rewardCalcInstance).setImplementor(newImplementor);
}
function setLMRewardsPerBlock(address token, uint value) public onlyOnline {
_admin();
require(lmRewards[token].startedAt != 0, "No reward program currently live for this token");
address rewardCalcInstance = lmRewards[token].rewardCalcInstance;
IERC2917(rewardCalcInstance).changeInterestRatePerBlock(value);
}
function addBonusTokenToLMRewards(address lmToken, address bonusToken, uint256 bonusTokenAmount) public {
_admin();
require(lmRewards[lmToken].startedAt != 0, "No reward program currently live for this LM token");
require(_bonusTokenSet.contains(bonusToken), "Bonus token not registered");
lmRewards[lmToken].bonusTokens.add(bonusToken);
lmRewards[lmToken].bonusTokenAmounts[bonusToken] = lmRewards[lmToken].bonusTokenAmounts[bonusToken].add(bonusTokenAmount);
}
function endLMRewards(address token, bool removeBonusTokenData) public {
_admin();
lmRewards[token].amount = 0;
lmRewards[token].duration = 0;
lmRewards[token].startedAt = 0;
lmRewards[token].rewardCalcInstance = address(0);
if (removeBonusTokenData) {
for (uint index = 0; index < lmRewards[token].bonusTokens.length(); index++) {
address bonusToken = lmRewards[token].bonusTokens.at(index);
lmRewards[token].bonusTokens.remove(bonusToken);
delete lmRewards[token].bonusTokenAmounts[bonusToken];
}
}
}
function setWeeklyAirdropAmount(string calldata tier, uint256 amount) external {
_admin();
weeklyAirdropAmounts[tier] = amount;
}
function setBalanceRequiredToClaim(string calldata tier, uint256 amount) external {
_admin();
balancesRequiredToClaim[tier] = amount;
}
function setMaxStakesPerVault(uint256 amount) external {
_admin();
MAX_TOKENS_STAKED_PER_VAULT = amount;
}
function setMaxBonusTokens(uint256 amount) external {
_admin();
MAX_BONUS_TOKENS = amount;
}
function setMinRewardClaimFrequency(uint256 amount) external {
_admin();
MIN_AIRDROP_REWARD_CLAIM_FREQUENCY = amount;
}
function setPlatinumLMRewardMultiplier(uint256 numerator, uint256 denominator) external {
_admin();
PLATINUM_LM_REWARD_MULTIPLIER_NUM = numerator;
PLATINUM_LM_REWARD_MULTIPLIER_DENOM = denominator;
}
function setGoldLMRewardMultiplier(uint256 numerator, uint256 denominator) external {
_admin();
GOLD_LM_REWARD_MULTIPLIER_NUM = numerator;
GOLD_LM_REWARD_MULTIPLIER_DENOM = denominator;
}
function setMintLMRewardMultiplier(uint256 numerator, uint256 denominator) external {
_admin();
MINT_LM_REWARD_MULTIPLIER_NUM = numerator;
MINT_LM_REWARD_MULTIPLIER_DENOM = denominator;
}
function setBlackLMRewardMultiplier(uint256 numerator, uint256 denominator) external {
_admin();
BLACK_LM_REWARD_MULTIPLIER_NUM = numerator;
BLACK_LM_REWARD_MULTIPLIER_DENOM = denominator;
}
function setLMRewardVestingPeriod(uint256 amount) external {
_admin();
LM_REWARD_VESTING_PERIOD = amount;
}
function setLMRewardVestingPortion(uint256 numerator, uint denominator) external {
_admin();
LM_REWARD_VESTING_PORTION_NUM = numerator;
LM_REWARD_VESTING_PORTION_DENOM = denominator;
}
/* getter functions */
function getBonusTokenSetLength() external view override returns (uint256 length) {
return _bonusTokenSet.length();
}
function getBonusTokenAtIndex(uint256 index)
external
view
override
returns (address bonusToken)
{
return _bonusTokenSet.at(index);
}
function getVaultFactorySetLength() external view override returns (uint256 length) {
return _vaultFactorySet.length();
}
function getVaultFactoryAtIndex(uint256 index)
external
view
override
returns (address factory)
{
return _vaultFactorySet.at(index);
}
function getNumVaults() external view override returns (uint256 num) {
return _vaultSet.length();
}
function getVaultAt(uint256 index) external view override returns (address vault) {
return _vaultSet.at(index);
}
function getNumTokensStaked() external view override returns (uint256 num) {
return _allStakedTokens.length();
}
function getTokenStakedAt(uint256 index) external view override returns (address token) {
return _allStakedTokens.at(index);
}
function getNumTokensStakedInVault(address vault)
external
view
override
returns (uint256 num)
{
return _vaults[vault].tokens.length();
}
function getVaultTokenAtIndex(address vault, uint256 index)
external
view
override
returns (address vaultToken)
{
return _vaults[vault].tokens.at(index);
}
function getVaultTokenStake(address vault, address token)
external
view
override
returns (uint256 tokenStake)
{
return _vaults[vault].tokenStake[token];
}
function getNftTier(uint256 nftId, address nftFactory) public view returns (string memory tier) {
uint256 serialNumber = MethodNFTFactory(nftFactory).tokenIdToSerialNumber(nftId);
if (serialNumber >= 1 && serialNumber <= 100) {
tier = PLATINUM;
} else if (serialNumber >= 101 && serialNumber <= 1000) {
tier = GOLD;
} else if (serialNumber >= 1001 && serialNumber <= 5000) {
tier = MINT;
} else if (serialNumber >= 5001) {
tier = BLACK;
}
}
function getNftsOfOwner(address owner, address nftFactory) public view returns (uint256[] memory nftIds) {
uint256 balance = MethodNFTFactory(nftFactory).balanceOf(owner);
nftIds = new uint256[](balance);
for (uint256 index = 0; index < balance; index++) {
uint256 nftId = MethodNFTFactory(nftFactory).tokenOfOwnerByIndex(owner, index);
nftIds[index] = nftId;
}
}
function getLMRewardData(address token) external view override returns (uint amount, uint duration, uint startedAt, address rewardCalcInstance) {
return (lmRewards[token].amount, lmRewards[token].duration, lmRewards[token].startedAt, lmRewards[token].rewardCalcInstance);
}
function getLMRewardBonusTokensLength(address token) external view override returns (uint length) {
return lmRewards[token].bonusTokens.length();
}
function getLMRewardBonusTokenAt(address token, uint index) external view override returns (address bonusToken, uint bonusTokenAmount) {
return (lmRewards[token].bonusTokens.at(index), lmRewards[token].bonusTokenAmounts[lmRewards[token].bonusTokens.at(index)]);
}
function getNumVestingLMTokenRewards(address user) external view override returns (uint num) {
return vestingLMTokenRewards[user].length();
}
function getVestingLMTokenAt(address user, uint index) external view override returns (address token) {
return vestingLMTokenRewards[user].at(index);
}
function getNumVests(address user, address token) external view override returns (uint num) {
return vestingLMRewards[user][token].length;
}
function getLMRewardVestingData(address user, address token, uint index) external view override returns (uint amount, uint startedAt) {
return (vestingLMRewards[user][token][index].amount, vestingLMRewards[user][token][index].startedAt);
}
function getNumRewardCalcTemplates() external view override returns (uint num) {
return rewardCalcTemplateNames.length;
}
/* helper functions */
function isValidVault(address vault, address factory) public view override returns (bool validity) {
// validate vault is created from whitelisted vault factory and is an instance of that factory
return _vaultFactorySet.contains(factory) && IInstanceRegistry(factory).isInstance(vault);
}
function isValidAddress(address target) public view override returns (bool validity) {
// sanity check target for potential input errors
return
target != address(this) &&
target != address(0) &&
target != rewardToken &&
target != rewardPool &&
!_bonusTokenSet.contains(target);
}
function calculateAirdropReward(address owner, address nftFactory) public returns (uint256 amount, uint256 balanceRequiredToClaim, uint256 balanceLocked) {
uint256[] memory nftIds = getNftsOfOwner(owner, nftFactory);
return calculateAirdropReward(nftFactory, nftIds);
}
function calculateAirdropReward(address nftFactory, uint256[] memory nftIds) public returns (uint256 amount, uint256 balanceRequiredToClaim, uint256 balanceLocked) {
for (uint256 index = 0; index < nftIds.length; index++) {
uint256 nftId = nftIds[index];
(uint256 amnt, uint256 balRequired, uint256 balLocked) = calculateAirdropReward(nftFactory, nftId);
amount = amount.add(amnt);
balanceRequiredToClaim = balanceRequiredToClaim.add(balRequired);
balanceLocked = balanceLocked.add(balLocked);
}
}
function calculateAirdropReward(address nftFactory, uint256 nftId) public returns (uint256 amount, uint256 balanceRequiredToClaim, uint256 balanceLocked) {
address vaultAddress = address(nftId);
require(isValidVault(vaultAddress, nftFactory), "UniStaker: vault is not valid");
// first ever claim
if (nftLastClaimedRewardAt[nftId] == 0) {
nftLastClaimedRewardAt[nftId] = block.timestamp;
return (0,0,0);
}
uint256 secondsSinceLastClaim = block.timestamp.sub(nftLastClaimedRewardAt[nftId]);
require(secondsSinceLastClaim > MIN_AIRDROP_REWARD_CLAIM_FREQUENCY, "Claimed reward recently");
// get tier
string memory tier = getNftTier(nftId, nftFactory);
// get balance locked of reward token (MTHD)
uint256 balanceLockedInVault = IUniversalVault(vaultAddress).getBalanceLocked(rewardToken);
balanceLocked = balanceLocked.add(balanceLockedInVault);
// get number of epochs since last claim
uint256 epochsSinceLastClaim = secondsSinceLastClaim.div(MIN_AIRDROP_REWARD_CLAIM_FREQUENCY);
uint256 accruedReward;
bytes32 tierHash = keccak256(abi.encodePacked(tier));
if (tierHash == keccak256(abi.encodePacked(PLATINUM))) {
accruedReward = weeklyAirdropAmounts[PLATINUM].mul(epochsSinceLastClaim);
amount = amount.add(accruedReward);
balanceRequiredToClaim = balanceRequiredToClaim.add(balancesRequiredToClaim[PLATINUM]);
} else if (tierHash == keccak256(abi.encodePacked(GOLD))) {
accruedReward = weeklyAirdropAmounts[GOLD].mul(epochsSinceLastClaim);
amount = amount.add(accruedReward);
balanceRequiredToClaim = balanceRequiredToClaim.add(balancesRequiredToClaim[GOLD]);
} else if (tierHash == keccak256(abi.encodePacked(MINT))) {
accruedReward = weeklyAirdropAmounts[MINT].mul(epochsSinceLastClaim);
amount = amount.add(accruedReward);
balanceRequiredToClaim = balanceRequiredToClaim.add(balancesRequiredToClaim[MINT]);
} else if (tierHash == keccak256(abi.encodePacked(BLACK))) {
accruedReward = weeklyAirdropAmounts[BLACK].mul(epochsSinceLastClaim);
amount = amount.add(accruedReward);
balanceRequiredToClaim = balanceRequiredToClaim.add(balancesRequiredToClaim[BLACK]);
}
}
/* convenience functions */
function _processAirdropRewardClaim(address nftFactory, uint256[] memory nftIds) private {
(uint256 amount, uint256 balanceRequiredToClaim, uint256 balanceLocked) = calculateAirdropReward(nftFactory, nftIds);
require(balanceLocked > balanceRequiredToClaim, "Insufficient MTHD tokens staked for claiming airdrop reward");
// update claim times
_updateClaimTimes(nftIds);
// send out
IRewardPool(rewardPool).sendERC20(rewardToken, msg.sender, amount);
emit RewardClaimed(nftFactory, msg.sender, rewardToken, amount);
}
function _updateClaimTimes(uint256[] memory nftIds) private {
for (uint256 index = 0; index < nftIds.length; index++) {
uint256 nftId = nftIds[index];
nftLastClaimedRewardAt[nftId] = block.timestamp;
}
}
function _tierMultipliedReward(uint nftId, address nftFactory, uint reward) private view returns (uint multipliedReward) {
// get tier
string memory tier = getNftTier(nftId, nftFactory);
bytes32 tierHash = keccak256(abi.encodePacked(tier));
if (tierHash == keccak256(abi.encodePacked(PLATINUM))) {
multipliedReward = reward.mul(PLATINUM_LM_REWARD_MULTIPLIER_NUM).div(PLATINUM_LM_REWARD_MULTIPLIER_DENOM);
} else if (tierHash == keccak256(abi.encodePacked(GOLD))) {
multipliedReward = reward.mul(GOLD_LM_REWARD_MULTIPLIER_NUM).div(GOLD_LM_REWARD_MULTIPLIER_DENOM);
} else if (tierHash == keccak256(abi.encodePacked(MINT))) {
multipliedReward = reward.mul(MINT_LM_REWARD_MULTIPLIER_NUM).div(MINT_LM_REWARD_MULTIPLIER_DENOM);
} else if (tierHash == keccak256(abi.encodePacked(BLACK))) {
multipliedReward = reward.mul(BLACK_LM_REWARD_MULTIPLIER_NUM).div(BLACK_LM_REWARD_MULTIPLIER_DENOM);
}
}
/* user functions */
/// @notice Exit UniStaker without claiming reward
/// @dev This function should never revert when correctly called by the vault.
/// A max number of tokens staked per vault is set with MAX_TOKENS_STAKED_PER_VAULT to
/// place an upper bound on the for loop.
/// access control: callable by anyone but fails if caller is not an approved vault
/// state machine:
/// - when vault exists on this UniStaker
/// - when active stake from this vault
/// - any power state
/// state scope:
/// - decrease stakedTokenTotal[token], delete if 0
/// - delete _vaults[vault].tokenStake[token]
/// - remove _vaults[vault].tokens.remove(token)
/// - delete _vaults[vault]
/// - remove vault from _vaultSet
/// - remove token from _allStakedTokens if required
/// token transfer: none
function rageQuit() external override {
require(_vaultSet.contains(msg.sender), "UniStaker: no vault");
//fetch vault storage reference
VaultData storage vaultData = _vaults[msg.sender];
// revert if no active tokens staked
EnumerableSet.AddressSet storage vaultTokens = vaultData.tokens;
require(vaultTokens.length() > 0, "UniStaker: no stake");
// update totals
for (uint256 index = 0; index < vaultTokens.length(); index++) {
address token = vaultTokens.at(index);
vaultTokens.remove(token);
uint256 amount = vaultData.tokenStake[token];
uint256 newTotal = stakedTokenTotal[token].sub(amount);
assert(newTotal >= 0);
if (newTotal == 0) {
_allStakedTokens.remove(token);
delete stakedTokenTotal[token];
} else {
stakedTokenTotal[token] = newTotal;
}
delete vaultData.tokenStake[token];
}
// delete vault data
_vaultSet.remove(msg.sender);
delete _vaults[msg.sender];
// emit event
emit RageQuit(msg.sender);
}
/// @notice Stake tokens
/// @dev anyone can stake to any vault if they have valid permission
/// access control: anyone
/// state machine:
/// - can be called multiple times
/// - only online
/// - when vault exists on this UniStaker
/// state scope:
/// - add token to _vaults[vault].tokens if not already exists
/// - increase _vaults[vault].tokenStake[token]
/// - add vault to _vaultSet if not already exists
/// - add token to _allStakedTokens if not already exists
/// - increase stakedTokenTotal[token]
/// token transfer: transfer staking tokens from msg.sender to vault
/// @param vault address The address of the vault to stake to
/// @param vaultFactory address The address of the vault factory which created the vault
/// @param token address The address of the token being staked
/// @param amount uint256 The amount of tokens to stake
function stake(
address vault,
address vaultFactory,
address token,
uint256 amount,
bytes calldata permission
) external override onlyOnline {
// verify vault is valid
require(isValidVault(vault, vaultFactory), "UniStaker: vault is not valid");
// verify non-zero amount
require(amount != 0, "UniStaker: no amount staked");
// check sender balance
require(IERC20(token).balanceOf(msg.sender) >= amount, "insufficient token balance");
// add vault to set
_vaultSet.add(vault);
// fetch vault storage reference
VaultData storage vaultData = _vaults[vault];
// verify stakes boundary not reached
require(vaultData.tokens.length() < MAX_TOKENS_STAKED_PER_VAULT, "UniStaker: MAX_TOKENS_STAKED_PER_VAULT reached");
// add token to set and increase amount
vaultData.tokens.add(token);
vaultData.tokenStake[token] = vaultData.tokenStake[token].add(amount);
// update total token staked
_allStakedTokens.add(token);
stakedTokenTotal[token] = stakedTokenTotal[token].add(amount);
// perform transfer
TransferHelper.safeTransferFrom(token, msg.sender, vault, amount);
// call lock on vault
IUniversalVault(vault).lock(token, amount, permission);
// check if there is a reward program currently running
if (lmRewards[token].startedAt != 0) {
address rewardCalcInstance = lmRewards[token].rewardCalcInstance;
(,uint rewardEarned,) = IERC2917(rewardCalcInstance).increaseProductivity(msg.sender, amount);
earnedLMRewards[msg.sender][token] = earnedLMRewards[msg.sender][token].add(rewardEarned);
}
// emit event
emit Staked(vault, amount);
}
/// @notice Unstake tokens and claim reward
/// @dev LM rewards can only be claimed when unstaking
/// access control: anyone with permission
/// state machine:
/// - when vault exists on this UniStaker
/// - after stake from vault
/// - can be called multiple times while sufficient stake remains
/// - only online
/// state scope:
/// - decrease _vaults[vault].tokenStake[token]
/// - delete token from _vaults[vault].tokens if token stake is 0
/// - decrease stakedTokenTotal[token]
/// - delete token from _allStakedTokens if total token stake is 0
/// token transfer:
/// - transfer reward tokens from reward pool to recipient
/// - transfer bonus tokens from reward pool to recipient
/// @param vault address The vault to unstake from
/// @param vaultFactory address The vault factory that created this vault
/// @param recipient address The recipient to send reward to
/// @param token address The staking token
/// @param amount uint256 The amount of staking tokens to unstake
/// @param claimBonusReward bool flag to claim bonus rewards
function unstakeAndClaim(
address vault,
address vaultFactory,
address recipient,
address token,
uint256 amount,
bool claimBonusReward,
bytes calldata permission
) external override onlyOnline {
require(_vaultSet.contains(vault), "UniStaker: no vault");
// fetch vault storage reference
VaultData storage vaultData = _vaults[vault];
// verify non-zero amount
require(amount != 0, "UniStaker: no amount unstaked");
// validate recipient
require(isValidAddress(recipient), "UniStaker: invalid recipient");
// check for sufficient vault stake amount
require(vaultData.tokens.contains(token), "UniStaker: no token in vault");
// check for sufficient vault stake amount
require(vaultData.tokenStake[token] >= amount, "UniStaker: insufficient vault token stake");
// check for sufficient total token stake amount
// if the above check succeeds and this check fails, there is a bug in stake accounting
require(stakedTokenTotal[token] >= amount, "stakedTokenTotal[token] is less than amount being unstaked");
// check if there is a reward program currently running
uint rewardEarned = earnedLMRewards[msg.sender][token];
if (lmRewards[token].startedAt != 0) {
address rewardCalcInstance = lmRewards[token].rewardCalcInstance;
(,uint newReward,) = IERC2917(rewardCalcInstance).decreaseProductivity(msg.sender, amount);
rewardEarned = rewardEarned.add(newReward);
}
// decrease totalStake of token in this vault
vaultData.tokenStake[token] = vaultData.tokenStake[token].sub(amount);
if (vaultData.tokenStake[token] == 0) {
vaultData.tokens.remove(token);
delete vaultData.tokenStake[token];
}
// decrease stakedTokenTotal across all vaults
stakedTokenTotal[token] = stakedTokenTotal[token].sub(amount);
if (stakedTokenTotal[token] == 0) {
_allStakedTokens.remove(token);
delete stakedTokenTotal[token];
}
// unlock staking tokens from vault
IUniversalVault(vault).unlock(token, amount, permission);
// emit event
emit Unstaked(vault, amount);
// only perform on non-zero reward
if (rewardEarned > 0) {
// transfer bonus tokens from reward pool to recipient
// bonus tokens can only be claimed during an active rewards program
if (claimBonusReward && lmRewards[token].startedAt != 0) {
for (uint256 index = 0; index < lmRewards[token].bonusTokens.length(); index++) {
// fetch bonus token address reference
address bonusToken = lmRewards[token].bonusTokens.at(index);
// calculate bonus token amount
// bonusAmount = rewardEarned * allocatedBonusReward / allocatedMainReward
uint256 bonusAmount = rewardEarned.mul(lmRewards[token].bonusTokenAmounts[bonusToken]).div(lmRewards[token].amount);
// transfer bonus token
IRewardPool(rewardPool).sendERC20(bonusToken, recipient, bonusAmount);
// emit event
emit RewardClaimed(vault, recipient, bonusToken, bonusAmount);
}
}
// take care of multiplier
uint multipliedReward = _tierMultipliedReward(uint(vault), vaultFactory, rewardEarned);
// take care of vesting
uint vestingPortion = multipliedReward.mul(LM_REWARD_VESTING_PORTION_NUM).div(LM_REWARD_VESTING_PORTION_DENOM);
vestingLMRewards[msg.sender][token].push(LMRewardVestingData(vestingPortion, block.timestamp));
vestingLMTokenRewards[msg.sender].add(token);
// set earned reward to 0
earnedLMRewards[msg.sender][token] = 0;
// transfer reward tokens from reward pool to recipient
IRewardPool(rewardPool).sendERC20(rewardToken, recipient, multipliedReward.sub(vestingPortion));
// emit event
emit RewardClaimed(vault, recipient, rewardToken, rewardEarned);
}
}
function claimAirdropReward(address nftFactory) external override onlyOnline {
uint256[] memory nftIds = getNftsOfOwner(msg.sender, nftFactory);
_processAirdropRewardClaim(nftFactory, nftIds);
}
function claimAirdropReward(address nftFactory, uint256[] calldata nftIds) external override onlyOnline {
_processAirdropRewardClaim(nftFactory, nftIds);
}
function claimVestedReward() external override onlyOnline {
uint numTokens = vestingLMTokenRewards[msg.sender].length();
for (uint index = 0; index < numTokens; index++) {
address token = vestingLMTokenRewards[msg.sender].at(index);
claimVestedReward(token, vestingLMRewards[msg.sender][token].length);
}
}
function claimVestedReward(address token) external override onlyOnline {
claimVestedReward(token, vestingLMRewards[msg.sender][token].length);
}
function claimVestedReward(address token, uint numVests) public onlyOnline {
require(numVests <= vestingLMRewards[msg.sender][token].length, "num vests can't be greater than available vests");
LMRewardVestingData[] storage vests = vestingLMRewards[msg.sender][token];
uint vestedReward;
for (uint index = 0; index < numVests; index++) {
LMRewardVestingData storage vest = vests[index];
uint duration = block.timestamp.sub(vest.startedAt);
uint vested = vest.amount.mul(duration).div(LM_REWARD_VESTING_PERIOD);
if (vested >= vest.amount) {
// completely vested
vested = vest.amount;
// copy last element into this slot and pop last
vests[index] = vests[vests.length - 1];
vests.pop();
index--;
numVests--;
// if all vested remove from set
if (vests.length == 0) {
vestingLMTokenRewards[msg.sender].remove(token);
break;
}
} else {
vest.amount = vest.amount.sub(vested);
}
vestedReward = vestedReward.add(vested);
}
if (vestedReward > 0) {
// transfer reward tokens from reward pool to recipient
IRewardPool(rewardPool).sendERC20(rewardToken, msg.sender, vestedReward);
// emit event
emit VestedRewardClaimed(msg.sender, rewardToken, vestedReward);
}
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.7.6;
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
interface IPowerSwitch {
/* admin events */
event PowerOn();
event PowerOff();
event EmergencyShutdown();
/* data types */
enum State {Online, Offline, Shutdown}
/* admin functions */
function powerOn() external;
function powerOff() external;
function emergencyShutdown() external;
/* view functions */
function isOnline() external view returns (bool status);
function isOffline() external view returns (bool status);
function isShutdown() external view returns (bool status);
function getStatus() external view returns (State status);
function getPowerController() external view returns (address controller);
}
/// @title PowerSwitch
/// @notice Standalone pausing and emergency stop functionality
contract PowerSwitch is IPowerSwitch, Ownable {
/* storage */
IPowerSwitch.State private _status;
/* initializer */
constructor(address owner) {
// sanity check owner
require(owner != address(0), "PowerSwitch: invalid owner");
// transfer ownership
Ownable.transferOwnership(owner);
}
/* admin functions */
/// @notice Turn Power On
/// access control: only owner
/// state machine: only when offline
/// state scope: only modify _status
/// token transfer: none
function powerOn() external override onlyOwner {
require(_status == IPowerSwitch.State.Offline, "PowerSwitch: cannot power on");
_status = IPowerSwitch.State.Online;
emit PowerOn();
}
/// @notice Turn Power Off
/// access control: only owner
/// state machine: only when online
/// state scope: only modify _status
/// token transfer: none
function powerOff() external override onlyOwner {
require(_status == IPowerSwitch.State.Online, "PowerSwitch: cannot power off");
_status = IPowerSwitch.State.Offline;
emit PowerOff();
}
/// @notice Shutdown Permanently
/// access control: only owner
/// state machine:
/// - when online or offline
/// - can only be called once
/// state scope: only modify _status
/// token transfer: none
function emergencyShutdown() external override onlyOwner {
require(_status != IPowerSwitch.State.Shutdown, "PowerSwitch: cannot shutdown");
_status = IPowerSwitch.State.Shutdown;
emit EmergencyShutdown();
}
/* getter functions */
function isOnline() external view override returns (bool status) {
return _status == IPowerSwitch.State.Online;
}
function isOffline() external view override returns (bool status) {
return _status == IPowerSwitch.State.Offline;
}
function isShutdown() external view override returns (bool status) {
return _status == IPowerSwitch.State.Shutdown;
}
function getStatus() external view override returns (IPowerSwitch.State status) {
return _status;
}
function getPowerController() external view override returns (address controller) {
return Ownable.owner();
}
}
|
Unstake tokens and claim reward LM rewards can only be claimed when unstaking access control: anyone with permission state machine: - when vault exists on this UniStaker - after stake from vault - can be called multiple times while sufficient stake remains - only online state scope: - decrease _vaults[vault].tokenStake[token] - delete token from _vaults[vault].tokens if token stake is 0 - decrease stakedTokenTotal[token] - delete token from _allStakedTokens if total token stake is 0 token transfer: - transfer reward tokens from reward pool to recipient - transfer bonus tokens from reward pool to recipient vault address The vault to unstake from vaultFactory address The vault factory that created this vault recipient address The recipient to send reward to token address The staking token amount uint256 The amount of staking tokens to unstake claimBonusReward bool flag to claim bonus rewards fetch vault storage reference verify non-zero amount validate recipient check for sufficient vault stake amount check for sufficient vault stake amount check for sufficient total token stake amount if the above check succeeds and this check fails, there is a bug in stake accounting check if there is a reward program currently running only perform on non-zero reward transfer bonus tokens from reward pool to recipient bonus tokens can only be claimed during an active rewards program fetch bonus token address reference calculate bonus token amount bonusAmount = rewardEarned allocatedBonusReward / allocatedMainReward transfer bonus token emit event
|
function unstakeAndClaim(
address vault,
address vaultFactory,
address recipient,
address token,
uint256 amount,
bool claimBonusReward,
bytes calldata permission
) external override onlyOnline {
require(_vaultSet.contains(vault), "UniStaker: no vault");
VaultData storage vaultData = _vaults[vault];
require(amount != 0, "UniStaker: no amount unstaked");
require(isValidAddress(recipient), "UniStaker: invalid recipient");
require(vaultData.tokens.contains(token), "UniStaker: no token in vault");
require(vaultData.tokenStake[token] >= amount, "UniStaker: insufficient vault token stake");
require(stakedTokenTotal[token] >= amount, "stakedTokenTotal[token] is less than amount being unstaked");
uint rewardEarned = earnedLMRewards[msg.sender][token];
if (lmRewards[token].startedAt != 0) {
address rewardCalcInstance = lmRewards[token].rewardCalcInstance;
(,uint newReward,) = IERC2917(rewardCalcInstance).decreaseProductivity(msg.sender, amount);
rewardEarned = rewardEarned.add(newReward);
}
if (vaultData.tokenStake[token] == 0) {
vaultData.tokens.remove(token);
delete vaultData.tokenStake[token];
}
if (stakedTokenTotal[token] == 0) {
_allStakedTokens.remove(token);
delete stakedTokenTotal[token];
}
if (rewardEarned > 0) {
if (claimBonusReward && lmRewards[token].startedAt != 0) {
for (uint256 index = 0; index < lmRewards[token].bonusTokens.length(); index++) {
address bonusToken = lmRewards[token].bonusTokens.at(index);
uint256 bonusAmount = rewardEarned.mul(lmRewards[token].bonusTokenAmounts[bonusToken]).div(lmRewards[token].amount);
IRewardPool(rewardPool).sendERC20(bonusToken, recipient, bonusAmount);
emit RewardClaimed(vault, recipient, bonusToken, bonusAmount);
}
}
vestingLMRewards[msg.sender][token].push(LMRewardVestingData(vestingPortion, block.timestamp));
vestingLMTokenRewards[msg.sender].add(token);
}
}
| 166,149 |
// SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./AloePool.sol";
contract AloePoolCapped is AloePool {
using SafeERC20 for IERC20;
address public immutable MULTISIG;
uint256 public maxTotalSupply;
constructor(address predictions, address multisig) AloePool(predictions) {
MULTISIG = multisig;
}
function deposit(
uint256 amount0Max,
uint256 amount1Max,
uint256 amount0Min,
uint256 amount1Min
)
public
override
lock
returns (
uint256 shares,
uint256 amount0,
uint256 amount1
)
{
(shares, amount0, amount1) = super.deposit(amount0Max, amount1Max, amount0Min, amount1Min);
require(totalSupply() <= maxTotalSupply, "Aloe: Pool already full");
}
/**
* @notice Removes tokens accidentally sent to this vault.
*/
function sweep(
IERC20 token,
uint256 amount,
address to
) external {
require(msg.sender == MULTISIG, "Not authorized");
require(token != TOKEN0 && token != TOKEN1, "Not sweepable");
token.safeTransfer(to, amount);
}
/**
* @notice Used to change deposit cap for a guarded launch or to ensure
* vault doesn't grow too large relative to the UNI_POOL. Cap is on total
* supply rather than amounts of TOKEN0 and TOKEN1 as those amounts
* fluctuate naturally over time.
*/
function setMaxTotalSupply(uint256 _maxTotalSupply) external {
require(msg.sender == MULTISIG, "Not authorized");
maxTotalSupply = _maxTotalSupply;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// 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: Unlicense
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol";
import "./libraries/FullMath.sol";
import "./libraries/LiquidityAmounts.sol";
import "./libraries/Math.sol";
import "./libraries/TickMath.sol";
import "./interfaces/IAloePredictions.sol";
import "./interfaces/IAloePredictionsImmutables.sol";
import "./structs/Bounds.sol";
import "./AloePoolERC20.sol";
import "./UniswapMinter.sol";
contract AloePool is AloePoolERC20, UniswapMinter {
using SafeERC20 for IERC20;
event Deposit(address indexed sender, uint256 shares, uint256 amount0, uint256 amount1);
event Withdraw(address indexed sender, uint256 shares, uint256 amount0, uint256 amount1);
event Snapshot(int24 tick, uint256 totalAmount0, uint256 totalAmount1, uint256 totalSupply);
/// @dev The maximum number of ticks a lower||upper bound can shift down per rebalance
int24 public constant MAX_SHIFT_DOWN = -726; // -7%
/// @dev The maximum number of ticks a lower||upper bound can shift up per rebalance
int24 public constant MAX_SHIFT_UP = 677; // +7%
/// @dev The predictions market that provides this pool with next-price distribution data
IAloePredictions public immutable PREDICTIONS;
/// @dev The most recent predictions market epoch during which this pool was rebalanced
uint24 public epoch;
/// @dev The tick corresponding to the lower price bound of our mean +/- 2 stddev position
int24 public lower2STD;
/// @dev The tick corresponding to the upper price bound of our mean +/- 2 stddev position
int24 public upper2STD;
/// @dev The tick corresponding to the lower price bound of our just-in-time position
int24 public lowerJIT;
/// @dev The tick corresponding to the upper price bound of our just-in-time position
int24 public upperJIT;
/// @dev For reentrancy check
bool private locked;
modifier lock() {
require(!locked, "Aloe: Locked");
locked = true;
_;
locked = false;
}
constructor(address predictions)
AloePoolERC20()
UniswapMinter(IUniswapV3Pool(IAloePredictionsImmutables(predictions).UNI_POOL()))
{
PREDICTIONS = IAloePredictions(predictions);
(Bounds memory bounds, bool areInverted) = IAloePredictions(predictions).current();
(lower2STD, upper2STD) = _getNextTicks(bounds, areInverted);
}
/**
* @notice Calculates the vault's total holdings of TOKEN0 and TOKEN1 - in
* other words, how much of each token the vault would hold if it withdrew
* all its liquidity from Uniswap.
*/
function getReserves() public view returns (uint256 reserve0, uint256 reserve1) {
(uint256 amount2STD0, uint256 amount2STD1) = _collectableAmountsAsOfLastPoke(lower2STD, upper2STD);
(uint256 amountJIT0, uint256 amountJIT1) = _collectableAmountsAsOfLastPoke(lowerJIT, upperJIT);
reserve0 = TOKEN0.balanceOf(address(this)) + amount2STD0 + amountJIT0;
reserve1 = TOKEN1.balanceOf(address(this)) + amount2STD1 + amountJIT1;
}
function getNextTicks() public view returns (int24 lower, int24 upper) {
(Bounds memory bounds, bool areInverted) = PREDICTIONS.current();
return _getNextTicks(bounds, areInverted);
}
function _getNextTicks(Bounds memory bounds, bool areInverted) private pure returns (int24 lower, int24 upper) {
uint160 sqrtPriceX96;
if (areInverted) {
sqrtPriceX96 = uint160(uint256(type(uint128).max) / Math.sqrt(bounds.lower << 80));
lower = TickMath.getTickAtSqrtRatio(sqrtPriceX96);
sqrtPriceX96 = uint160(uint256(type(uint128).max) / Math.sqrt(bounds.upper << 80));
upper = TickMath.getTickAtSqrtRatio(sqrtPriceX96);
} else {
sqrtPriceX96 = uint160(Math.sqrt(bounds.lower << 80) << 32);
lower = TickMath.getTickAtSqrtRatio(sqrtPriceX96);
sqrtPriceX96 = uint160(Math.sqrt(bounds.upper << 80) << 32);
upper = TickMath.getTickAtSqrtRatio(sqrtPriceX96);
}
}
/**
* @notice Deposits tokens in proportion to the vault's current holdings.
* @dev These tokens sit in the vault and are not used for liquidity on
* Uniswap until the next rebalance. Also note it's not necessary to check
* if user manipulated price to deposit cheaper, as the value of range
* orders can only by manipulated higher.
* @dev LOCK MODIFIER IS APPLIED IN AloePoolCapped!!!
* @param amount0Max Max amount of TOKEN0 to deposit
* @param amount1Max Max amount of TOKEN1 to deposit
* @param amount0Min Ensure `amount0` is greater than this
* @param amount1Min Ensure `amount1` is greater than this
* @return shares Number of shares minted
* @return amount0 Amount of TOKEN0 deposited
* @return amount1 Amount of TOKEN1 deposited
*/
function deposit(
uint256 amount0Max,
uint256 amount1Max,
uint256 amount0Min,
uint256 amount1Min
)
public
virtual
returns (
uint256 shares,
uint256 amount0,
uint256 amount1
)
{
require(amount0Max != 0 || amount1Max != 0, "Aloe: 0 deposit");
_uniswapPoke(lower2STD, upper2STD);
_uniswapPoke(lowerJIT, upperJIT);
(shares, amount0, amount1) = _computeLPShares(amount0Max, amount1Max);
require(shares != 0, "Aloe: 0 shares");
require(amount0 > amount0Min, "Aloe: amount0 too low");
require(amount1 > amount1Min, "Aloe: amount1 too low");
// Pull in tokens from sender
if (amount0 != 0) TOKEN0.safeTransferFrom(msg.sender, address(this), amount0);
if (amount1 != 0) TOKEN1.safeTransferFrom(msg.sender, address(this), amount1);
// Mint shares
_mint(msg.sender, shares);
emit Deposit(msg.sender, shares, amount0, amount1);
}
/// @dev Calculates the largest possible `amount0` and `amount1` such that
/// they're in the same proportion as total amounts, but not greater than
/// `amount0Max` and `amount1Max` respectively.
function _computeLPShares(uint256 amount0Max, uint256 amount1Max)
internal
view
returns (
uint256 shares,
uint256 amount0,
uint256 amount1
)
{
uint256 totalSupply = totalSupply();
(uint256 reserve0, uint256 reserve1) = getReserves();
// If total supply > 0, pool can't be empty
assert(totalSupply == 0 || reserve0 != 0 || reserve1 != 0);
if (totalSupply == 0) {
// For first deposit, just use the amounts desired
amount0 = amount0Max;
amount1 = amount1Max;
shares = amount0 > amount1 ? amount0 : amount1; // max
} else if (reserve0 == 0) {
amount1 = amount1Max;
shares = FullMath.mulDiv(amount1, totalSupply, reserve1);
} else if (reserve1 == 0) {
amount0 = amount0Max;
shares = FullMath.mulDiv(amount0, totalSupply, reserve0);
} else {
amount0 = FullMath.mulDiv(amount1Max, reserve0, reserve1);
if (amount0 < amount0Max) {
amount1 = amount1Max;
shares = FullMath.mulDiv(amount1, totalSupply, reserve1);
} else {
amount0 = amount0Max;
amount1 = FullMath.mulDiv(amount0, reserve1, reserve0);
shares = FullMath.mulDiv(amount0, totalSupply, reserve0);
}
}
}
/**
* @notice Withdraws tokens in proportion to the vault's holdings.
* @param shares Shares burned by sender
* @param amount0Min Revert if resulting `amount0` is smaller than this
* @param amount1Min Revert if resulting `amount1` is smaller than this
* @return amount0 Amount of TOKEN0 sent to recipient
* @return amount1 Amount of TOKEN1 sent to recipient
*/
function withdraw(
uint256 shares,
uint256 amount0Min,
uint256 amount1Min
) external lock returns (uint256 amount0, uint256 amount1) {
require(shares != 0, "Aloe: 0 shares");
uint256 totalSupply = totalSupply() + 1;
// Calculate token amounts proportional to unused balances
amount0 = FullMath.mulDiv(TOKEN0.balanceOf(address(this)), shares, totalSupply);
amount1 = FullMath.mulDiv(TOKEN1.balanceOf(address(this)), shares, totalSupply);
// Withdraw proportion of liquidity from Uniswap pool
uint256 temp0;
uint256 temp1;
(temp0, temp1) = _uniswapExitFraction(shares, totalSupply, lower2STD, upper2STD);
amount0 += temp0;
amount1 += temp1;
(temp0, temp1) = _uniswapExitFraction(shares, totalSupply, lowerJIT, upperJIT);
amount0 += temp0;
amount1 += temp1;
// Check constraints
require(amount0 >= amount0Min, "Aloe: amount0 too low");
require(amount1 >= amount1Min, "Aloe: amount1 too low");
// Transfer tokens
if (amount0 != 0) TOKEN0.safeTransfer(msg.sender, amount0);
if (amount1 != 0) TOKEN1.safeTransfer(msg.sender, amount1);
// Burn shares
_burn(msg.sender, shares);
emit Withdraw(msg.sender, shares, amount0, amount1);
}
/// @dev Withdraws share of liquidity in a range from Uniswap pool. All fee earnings
/// will be collected and left unused afterwards
function _uniswapExitFraction(
uint256 numerator,
uint256 denominator,
int24 tickLower,
int24 tickUpper
) internal returns (uint256 amount0, uint256 amount1) {
assert(numerator < denominator);
(uint128 liquidity, , , , ) = _position(tickLower, tickUpper);
liquidity = uint128(FullMath.mulDiv(liquidity, numerator, denominator));
uint256 earned0;
uint256 earned1;
(amount0, amount1, earned0, earned1) = _uniswapExit(tickLower, tickUpper, liquidity);
// Add share of fees
amount0 += FullMath.mulDiv(earned0, numerator, denominator);
amount1 += FullMath.mulDiv(earned1, numerator, denominator);
}
/**
* @notice Updates vault's positions. Can only be called by the strategy.
* @dev Two orders are placed - a base order and a limit order. The base
* order is placed first with as much liquidity as possible. This order
* should use up all of one token, leaving only the other one. This excess
* amount is then placed as a single-sided bid or ask order.
*/
function rebalance() external lock {
uint24 _epoch = PREDICTIONS.epoch();
require(_epoch > epoch, "Aloe: Too early");
epoch = _epoch;
int24 lower2STDOld = lower2STD;
int24 upper2STDOld = upper2STD;
// Extract target lower & upper ticks from predictions market
(int24 lower2STDNew, int24 upper2STDNew) = getNextTicks();
lower2STDNew = _constrainTickShift(lower2STDOld, lower2STDNew);
upper2STDNew = _constrainTickShift(upper2STDOld, upper2STDNew);
(lower2STDNew, upper2STDNew) = _coerceTicksToSpacing(lower2STDNew, upper2STDNew);
// Only perform rebalance if lower||upper tick has changed
if (lower2STDNew != lower2STDOld || upper2STDNew != upper2STDOld) {
(uint160 sqrtPriceX96, int24 tick, , , , , ) = UNI_POOL.slot0();
// Exit all current Uniswap positions
{
(uint128 liquidity2STD, , , , ) = _position(lower2STDOld, upper2STDOld);
(uint128 liquidityJIT, , , , ) = _position(lowerJIT, upperJIT);
_uniswapExit(lower2STDOld, upper2STDOld, liquidity2STD);
_uniswapExit(lowerJIT, upperJIT, liquidityJIT);
}
// Emit snapshot to record balances and supply
uint256 balance0 = TOKEN0.balanceOf(address(this));
uint256 balance1 = TOKEN1.balanceOf(address(this));
emit Snapshot(tick, balance0, balance1, totalSupply());
// Place base order on Uniswap
uint128 liquidity = _liquidityForAmounts(lower2STDNew, upper2STDNew, sqrtPriceX96, balance0, balance1);
_uniswapEnter(lower2STDNew, upper2STDNew, liquidity);
(lower2STD, upper2STD) = (lower2STDNew, upper2STDNew);
// Place naive JIT order on Uniswap
_snipe(sqrtPriceX96, tick);
}
}
function snipe() external lock {
// Exit current JIT position
(uint128 liquidityJIT, , , , ) = _position(lowerJIT, upperJIT);
(, , uint256 earned0, uint256 earned1) = _uniswapExit(lowerJIT, upperJIT, liquidityJIT);
// Reward caller
if (earned0 != 0) TOKEN0.safeTransfer(address(this), earned0);
if (earned1 != 0) TOKEN1.safeTransfer(address(this), earned1);
// Fetch necessary state info
(uint160 sqrtPriceX96, int24 tick, , , , , ) = UNI_POOL.slot0();
uint256 balance0 = TOKEN0.balanceOf(address(this));
uint256 balance1 = TOKEN1.balanceOf(address(this));
// Add to base order on Uniswap
// TODO To maximize resource usage, one would fix one bound and one balance, as opposed
// to fixing two bounds and computing both balances as is done here
uint128 liquidity = _liquidityForAmounts(lower2STD, upper2STD, sqrtPriceX96, balance0, balance1);
_uniswapEnter(lower2STD, upper2STD, liquidity);
// Place updated JIT order on Uniswap
_snipe(sqrtPriceX96, tick);
}
/// @dev Allocates entire balance of _either_ TOKEN0 or TOKEN1 to as tight a position as possible,
/// with one edge on the current tick.
function _snipe(uint160 sqrtPriceX96, int24 tick) private {
int24 tickSpacing = TICK_SPACING;
uint256 balance0 = TOKEN0.balanceOf(address(this));
uint256 balance1 = TOKEN1.balanceOf(address(this));
(int24 upperL, int24 lowerR) = _coerceTicksToSpacing(tick, tick);
// TODO Won't have to compute both liquidity amounts if _all_ of one token gets used
// in main position (as would be the case when fixing one bound and one balance)
uint128 liquidityL = _liquidityForAmounts(upperL - tickSpacing, upperL, sqrtPriceX96, balance0, balance1);
uint128 liquidityR = _liquidityForAmounts(lowerR, lowerR + tickSpacing, sqrtPriceX96, balance0, balance1);
if (liquidityL > liquidityR) {
_uniswapEnter(upperL - tickSpacing, upperL, liquidityL);
(lowerJIT, upperJIT) = (upperL - tickSpacing, upperL);
} else {
_uniswapEnter(lowerR, lowerR + tickSpacing, liquidityR);
(lowerJIT, upperJIT) = (lowerR, lowerR + tickSpacing);
}
}
function _constrainTickShift(int24 tickOld, int24 tickNew) private pure returns (int24) {
if (tickNew < tickOld + MAX_SHIFT_DOWN) {
return tickOld + MAX_SHIFT_DOWN;
} else if (tickNew > tickOld + MAX_SHIFT_UP) {
return tickOld + MAX_SHIFT_UP;
}
return tickNew;
}
function _coerceTicksToSpacing(int24 tickLower, int24 tickUpper)
private
view
returns (int24 tickLowerCoerced, int24 tickUpperCoerced)
{
tickLowerCoerced =
tickLower -
(tickLower < 0 ? TICK_SPACING + (tickLower % TICK_SPACING) : tickLower % TICK_SPACING);
tickUpperCoerced =
tickUpper +
(tickUpper < 0 ? -tickUpper % TICK_SPACING : TICK_SPACING - (tickUpper % TICK_SPACING));
assert(tickLowerCoerced <= tickLower);
assert(tickUpperCoerced >= tickUpper);
}
}
// 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: GPL-2.0-or-later
pragma solidity >=0.5.0;
import './pool/IUniswapV3PoolImmutables.sol';
import './pool/IUniswapV3PoolState.sol';
import './pool/IUniswapV3PoolDerivedState.sol';
import './pool/IUniswapV3PoolActions.sol';
import './pool/IUniswapV3PoolOwnerActions.sol';
import './pool/IUniswapV3PoolEvents.sol';
/// @title The interface for a Uniswap V3 Pool
/// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform
/// to the ERC20 specification
/// @dev The pool interface is broken up into many smaller pieces
interface IUniswapV3Pool is
IUniswapV3PoolImmutables,
IUniswapV3PoolState,
IUniswapV3PoolDerivedState,
IUniswapV3PoolActions,
IUniswapV3PoolOwnerActions,
IUniswapV3PoolEvents
{
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.0;
/// @title Contains 512-bit math functions
/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision
/// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits
library FullMath {
/// @notice Calculates floor(aΓbΓ·denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
/// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
function mulDiv(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = a * b
// Compute the product mod 2**256 and mod 2**256 - 1
// then use the Chinese Remainder Theorem to reconstruct
// the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2**256 + prod0
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(a, b, not(0))
prod0 := mul(a, b)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division
if (prod1 == 0) {
require(denominator > 0);
assembly {
result := div(prod0, denominator)
}
return result;
}
// Make sure the result is less than 2**256.
// Also prevents denominator == 0
require(denominator > prod1);
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0]
// Compute remainder using mulmod
uint256 remainder;
assembly {
remainder := mulmod(a, b, denominator)
}
// Subtract 256 bit number from 512 bit number
assembly {
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator
// Compute largest power of two divisor of denominator.
// Always >= 1.
// https://ethereum.stackexchange.com/a/96646
uint256 twos = denominator & (~denominator + 1);
// Divide denominator by power of two
assembly {
denominator := div(denominator, twos)
}
// Divide [prod1 prod0] by the factors of two
assembly {
prod0 := div(prod0, twos)
}
// Shift in bits from prod1 into prod0. For this we need
// to flip `twos` such that it is 2**256 / twos.
// If twos is zero, then it becomes one
assembly {
twos := add(div(sub(0, twos), twos), 1)
}
prod0 |= prod1 * twos;
// Invert denominator mod 2**256
// Now that denominator is an odd number, it has an inverse
// modulo 2**256 such that denominator * inv = 1 mod 2**256.
// Compute the inverse by starting with a seed that is correct
// correct for four bits. That is, denominator * inv = 1 mod 2**4
uint256 inv = (3 * denominator) ^ 2;
// Now use Newton-Raphson iteration to improve the precision.
// Thanks to Hensel's lifting lemma, this also works in modular
// arithmetic, doubling the correct bits in each step.
inv *= 2 - denominator * inv; // inverse mod 2**8
inv *= 2 - denominator * inv; // inverse mod 2**16
inv *= 2 - denominator * inv; // inverse mod 2**32
inv *= 2 - denominator * inv; // inverse mod 2**64
inv *= 2 - denominator * inv; // inverse mod 2**128
inv *= 2 - denominator * inv; // inverse mod 2**256
// Because the division is now exact we can divide by multiplying
// with the modular inverse of denominator. This will give us the
// correct result modulo 2**256. Since the precoditions guarantee
// that the outcome is less than 2**256, this is the final result.
// We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inv;
return result;
}
}
/// @notice Calculates ceil(aΓbΓ·denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
function mulDivRoundingUp(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
result = mulDiv(a, b, denominator);
if (mulmod(a, b, denominator) > 0) {
require(result < type(uint256).max);
result++;
}
}
/// @dev https://medium.com/wicketh/mathemagic-full-multiply-27650fec525d
function mul512(uint256 a, uint256 b) internal pure returns (uint256 r0, uint256 r1) {
assembly {
let mm := mulmod(a, b, not(0))
r0 := mul(a, b)
r1 := sub(sub(mm, r0), lt(mm, r0))
}
}
/// @dev Like `mul512`, but multiply a number by itself
function square512(uint256 a) internal pure returns (uint256 r0, uint256 r1) {
assembly {
let mm := mulmod(a, a, not(0))
r0 := mul(a, a)
r1 := sub(sub(mm, r0), lt(mm, r0))
}
}
/// @dev https://github.com/hifi-finance/prb-math/blob/main/contracts/PRBMathCommon.sol
function log2floor(uint256 x) internal pure returns (uint256 msb) {
unchecked {
if (x >= 2**128) {
x >>= 128;
msb += 128;
}
if (x >= 2**64) {
x >>= 64;
msb += 64;
}
if (x >= 2**32) {
x >>= 32;
msb += 32;
}
if (x >= 2**16) {
x >>= 16;
msb += 16;
}
if (x >= 2**8) {
x >>= 8;
msb += 8;
}
if (x >= 2**4) {
x >>= 4;
msb += 4;
}
if (x >= 2**2) {
x >>= 2;
msb += 2;
}
if (x >= 2**1) {
// No need to shift x any more.
msb += 1;
}
}
}
/// @dev https://graphics.stanford.edu/~seander/bithacks.html#IntegerLogDeBruijn
function log2ceil(uint256 x) internal pure returns (uint256 y) {
assembly {
let arg := x
x := sub(x, 1)
x := or(x, div(x, 0x02))
x := or(x, div(x, 0x04))
x := or(x, div(x, 0x10))
x := or(x, div(x, 0x100))
x := or(x, div(x, 0x10000))
x := or(x, div(x, 0x100000000))
x := or(x, div(x, 0x10000000000000000))
x := or(x, div(x, 0x100000000000000000000000000000000))
x := add(x, 1)
let m := mload(0x40)
mstore(m, 0xf8f9cbfae6cc78fbefe7cdc3a1793dfcf4f0e8bbd8cec470b6a28a7a5a3e1efd)
mstore(add(m, 0x20), 0xf5ecf1b3e9debc68e1d9cfabc5997135bfb7a7a3938b7b606b5b4b3f2f1f0ffe)
mstore(add(m, 0x40), 0xf6e4ed9ff2d6b458eadcdf97bd91692de2d4da8fd2d0ac50c6ae9a8272523616)
mstore(add(m, 0x60), 0xc8c0b887b0a8a4489c948c7f847c6125746c645c544c444038302820181008ff)
mstore(add(m, 0x80), 0xf7cae577eec2a03cf3bad76fb589591debb2dd67e0aa9834bea6925f6a4a2e0e)
mstore(add(m, 0xa0), 0xe39ed557db96902cd38ed14fad815115c786af479b7e83247363534337271707)
mstore(add(m, 0xc0), 0xc976c13bb96e881cb166a933a55e490d9d56952b8d4e801485467d2362422606)
mstore(add(m, 0xe0), 0x753a6d1b65325d0c552a4d1345224105391a310b29122104190a110309020100)
mstore(0x40, add(m, 0x100))
let magic := 0x818283848586878898a8b8c8d8e8f929395969799a9b9d9e9faaeb6bedeeff
let shift := 0x100000000000000000000000000000000000000000000000000000000000000
let a := div(mul(x, magic), shift)
y := div(mload(add(m, sub(255, a))), shift)
y := add(y, mul(256, gt(arg, 0x8000000000000000000000000000000000000000000000000000000000000000)))
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
import "./FixedPoint96.sol";
import "./FullMath.sol";
/// @title Liquidity amount functions
/// @notice Provides functions for computing liquidity amounts from token amounts and prices
library LiquidityAmounts {
/// @notice Downcasts uint256 to uint128
/// @param x The uint258 to be downcasted
/// @return y The passed value, downcasted to uint128
function toUint128(uint256 x) private pure returns (uint128 y) {
require((y = uint128(x)) == x);
}
/// @notice Computes the amount of liquidity received for a given amount of token0 and price range
/// @dev Calculates amount0 * (sqrt(upper) * sqrt(lower)) / (sqrt(upper) - sqrt(lower))
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param amount0 The amount0 being sent in
/// @return liquidity The amount of returned liquidity
function getLiquidityForAmount0(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount0
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
uint256 intermediate = FullMath.mulDiv(sqrtRatioAX96, sqrtRatioBX96, FixedPoint96.Q96);
return toUint128(FullMath.mulDiv(amount0, intermediate, sqrtRatioBX96 - sqrtRatioAX96));
}
/// @notice Computes the amount of liquidity received for a given amount of token1 and price range
/// @dev Calculates amount1 / (sqrt(upper) - sqrt(lower)).
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param amount1 The amount1 being sent in
/// @return liquidity The amount of returned liquidity
function getLiquidityForAmount1(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount1
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return toUint128(FullMath.mulDiv(amount1, FixedPoint96.Q96, sqrtRatioBX96 - sqrtRatioAX96));
}
/// @notice Computes the maximum amount of liquidity received for a given amount of token0, token1, the current
/// pool prices and the prices at the tick boundaries
/// @param sqrtRatioX96 A sqrt price representing the current pool prices
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param amount0 The amount of token0 being sent in
/// @param amount1 The amount of token1 being sent in
/// @return liquidity The maximum amount of liquidity received
function getLiquidityForAmounts(
uint160 sqrtRatioX96,
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount0,
uint256 amount1
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
if (sqrtRatioX96 <= sqrtRatioAX96) {
liquidity = getLiquidityForAmount0(sqrtRatioAX96, sqrtRatioBX96, amount0);
} else if (sqrtRatioX96 < sqrtRatioBX96) {
uint128 liquidity0 = getLiquidityForAmount0(sqrtRatioX96, sqrtRatioBX96, amount0);
uint128 liquidity1 = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioX96, amount1);
liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1;
} else {
liquidity = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1);
}
}
/// @notice Computes the amount of token0 for a given amount of liquidity and a price range
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param liquidity The liquidity being valued
/// @return amount0 The amount of token0
function getAmount0ForLiquidity(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount0) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return
FullMath.mulDiv(
uint256(liquidity) << FixedPoint96.RESOLUTION,
sqrtRatioBX96 - sqrtRatioAX96,
sqrtRatioBX96
) / sqrtRatioAX96;
}
/// @notice Computes the amount of token1 for a given amount of liquidity and a price range
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param liquidity The liquidity being valued
/// @return amount1 The amount of token1
function getAmount1ForLiquidity(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount1) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96);
}
/// @notice Computes the token0 and token1 value for a given amount of liquidity, the current
/// pool prices and the prices at the tick boundaries
/// @param sqrtRatioX96 A sqrt price representing the current pool prices
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param liquidity The liquidity being valued
/// @return amount0 The amount of token0
/// @return amount1 The amount of token1
function getAmountsForLiquidity(
uint160 sqrtRatioX96,
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount0, uint256 amount1) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
if (sqrtRatioX96 <= sqrtRatioAX96) {
amount0 = getAmount0ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);
} else if (sqrtRatioX96 < sqrtRatioBX96) {
amount0 = getAmount0ForLiquidity(sqrtRatioX96, sqrtRatioBX96, liquidity);
amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioX96, liquidity);
} else {
amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
library Math {
// babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
function sqrt(uint256 y) internal pure returns (uint256 z) {
unchecked {
if (y > 3) {
z = y;
uint256 x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Math library for computing sqrt prices from ticks and vice versa
/// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports
/// prices between 2**-128 and 2**128
library TickMath {
/// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128
int24 internal constant MIN_TICK = -887272;
/// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128
int24 internal constant MAX_TICK = -MIN_TICK;
/// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK)
uint160 internal constant MIN_SQRT_RATIO = 4295128739;
/// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK)
uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;
/// @notice Calculates sqrt(1.0001^tick) * 2^96
/// @dev Throws if |tick| > max tick
/// @param tick The input tick for the above formula
/// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0)
/// at the given tick
function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) {
uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick));
require(absTick <= uint256(uint24(MAX_TICK)), "T");
uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000;
if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128;
if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;
if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;
if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128;
if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128;
if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128;
if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;
if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;
if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128;
if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;
if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;
if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;
if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;
if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;
if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128;
if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;
if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128;
if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128;
if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128;
if (tick > 0) ratio = type(uint256).max / ratio;
// this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.
// we then downcast because we know the result always fits within 160 bits due to our tick input constraint
// we round up in the division so getTickAtSqrtRatio of the output price is always consistent
sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1));
}
/// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio
/// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may
/// ever return.
/// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96
/// @return tick The greatest tick for which the ratio is less than or equal to the input ratio
function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) {
// second inequality must be < because the price can never reach the price at the max tick
require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, "R");
uint256 ratio = uint256(sqrtPriceX96) << 32;
uint256 r = ratio;
uint256 msb = 0;
assembly {
let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(5, gt(r, 0xFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(4, gt(r, 0xFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(3, gt(r, 0xFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(2, gt(r, 0xF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(1, gt(r, 0x3))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := gt(r, 0x1)
msb := or(msb, f)
}
if (msb >= 128) r = ratio >> (msb - 127);
else r = ratio << (127 - msb);
int256 log_2 = (int256(msb) - 128) << 64;
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(63, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(62, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(61, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(60, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(59, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(58, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(57, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(56, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(55, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(54, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(53, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(52, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(51, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(50, f))
}
int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number
int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128);
int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128);
tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IAloePredictionsActions.sol";
import "./IAloePredictionsDerivedState.sol";
import "./IAloePredictionsEvents.sol";
import "./IAloePredictionsState.sol";
/// @title Aloe predictions market interface
/// @dev The interface is broken up into many smaller pieces
interface IAloePredictions is
IAloePredictionsActions,
IAloePredictionsDerivedState,
IAloePredictionsEvents,
IAloePredictionsState
{
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IAloePredictionsImmutables {
/// @dev The maximum number of proposals that should be aggregated
function NUM_PROPOSALS_TO_AGGREGATE() external view returns (uint8);
/// @dev The number of standard deviations to +/- from the mean when computing ground truth bounds
function GROUND_TRUTH_STDDEV_SCALE() external view returns (uint256);
/// @dev The minimum length of an epoch, in seconds. Epochs may be longer if no one calls `advance`
function EPOCH_LENGTH_SECONDS() external view returns (uint32);
/// @dev The ALOE token used for staking
function ALOE() external view returns (address);
/// @dev The Uniswap pair for which predictions should be made
function UNI_POOL() external view returns (address);
/// @dev The incentive vault to use for staking extras and `advance()` reward
function INCENTIVE_VAULT() external view returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
struct Bounds {
// Q128.48 price at tickLower of a Uniswap position
uint176 lower;
// Q128.48 price at tickUpper of a Uniswap position
uint176 upper;
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/extensions/draft-ERC20Permit.sol";
contract AloePoolERC20 is ERC20Permit {
constructor() ERC20Permit("Aloe V1") ERC20("Aloe V1", "ALOE-V1") {}
}
// SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3MintCallback.sol";
import "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol";
import "./libraries/LiquidityAmounts.sol";
import "./libraries/TickMath.sol";
contract UniswapMinter is IUniswapV3MintCallback {
using SafeERC20 for IERC20;
IUniswapV3Pool public immutable UNI_POOL;
int24 public immutable TICK_SPACING;
IERC20 public immutable TOKEN0;
IERC20 public immutable TOKEN1;
constructor(IUniswapV3Pool uniPool) {
UNI_POOL = uniPool;
TICK_SPACING = uniPool.tickSpacing();
TOKEN0 = IERC20(uniPool.token0());
TOKEN1 = IERC20(uniPool.token1());
}
/// @dev Do zero-burns to poke the Uniswap pools so earned fees are updated
function _uniswapPoke(int24 tickLower, int24 tickUpper) internal {
(uint128 liquidity, , , , ) = _position(tickLower, tickUpper);
if (liquidity == 0) return;
UNI_POOL.burn(tickLower, tickUpper, 0);
}
/// @dev Deposits liquidity in a range on the Uniswap pool.
function _uniswapEnter(
int24 tickLower,
int24 tickUpper,
uint128 liquidity
) internal {
if (liquidity == 0) return;
UNI_POOL.mint(address(this), tickLower, tickUpper, liquidity, "");
}
/// @dev Withdraws liquidity from a range and collects all fees in the process.
function _uniswapExit(
int24 tickLower,
int24 tickUpper,
uint128 liquidity
)
internal
returns (
uint256 burned0,
uint256 burned1,
uint256 earned0,
uint256 earned1
)
{
if (liquidity != 0) {
(burned0, burned1) = UNI_POOL.burn(tickLower, tickUpper, liquidity);
}
// Collect all owed tokens including earned fees
(uint256 collected0, uint256 collected1) =
UNI_POOL.collect(address(this), tickLower, tickUpper, type(uint128).max, type(uint128).max);
earned0 = collected0 - burned0;
earned1 = collected1 - burned1;
}
/**
* @notice Amounts of TOKEN0 and TOKEN1 held in vault's position. Includes
* owed fees, except those accrued since last poke.
*/
function _collectableAmountsAsOfLastPoke(int24 tickLower, int24 tickUpper)
public
view
returns (uint256, uint256)
{
(uint128 liquidity, , , uint128 earnable0, uint128 earnable1) = _position(tickLower, tickUpper);
(uint256 burnable0, uint256 burnable1) = _amountsForLiquidity(tickLower, tickUpper, liquidity);
return (burnable0 + earnable0, burnable1 + earnable1);
}
/// @dev Wrapper around `IUniswapV3Pool.positions()`.
function _position(int24 tickLower, int24 tickUpper)
internal
view
returns (
uint128, // liquidity
uint256, // feeGrowthInside0LastX128
uint256, // feeGrowthInside1LastX128
uint128, // tokensOwed0
uint128 // tokensOwed1
)
{
return UNI_POOL.positions(keccak256(abi.encodePacked(address(this), tickLower, tickUpper)));
}
/// @dev Wrapper around `LiquidityAmounts.getAmountsForLiquidity()`.
function _amountsForLiquidity(
int24 tickLower,
int24 tickUpper,
uint128 liquidity
) internal view returns (uint256, uint256) {
(uint160 sqrtPriceX96, , , , , , ) = UNI_POOL.slot0();
return
LiquidityAmounts.getAmountsForLiquidity(
sqrtPriceX96,
TickMath.getSqrtRatioAtTick(tickLower),
TickMath.getSqrtRatioAtTick(tickUpper),
liquidity
);
}
/// @dev Wrapper around `LiquidityAmounts.getLiquidityForAmounts()`.
function _liquidityForAmounts(
int24 tickLower,
int24 tickUpper,
uint160 sqrtPriceX96,
uint256 amount0,
uint256 amount1
) internal pure returns (uint128) {
return
LiquidityAmounts.getLiquidityForAmounts(
sqrtPriceX96,
TickMath.getSqrtRatioAtTick(tickLower),
TickMath.getSqrtRatioAtTick(tickUpper),
amount0,
amount1
);
}
/// @dev Callback for Uniswap V3 pool.
function uniswapV3MintCallback(
uint256 amount0,
uint256 amount1,
bytes calldata data
) external override {
require(msg.sender == address(UNI_POOL), "Fake callback");
if (amount0 != 0) TOKEN0.safeTransfer(msg.sender, amount0);
if (amount1 != 0) TOKEN1.safeTransfer(msg.sender, amount1);
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that never changes
/// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values
interface IUniswapV3PoolImmutables {
/// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface
/// @return The contract address
function factory() external view returns (address);
/// @notice The first of the two tokens of the pool, sorted by address
/// @return The token contract address
function token0() external view returns (address);
/// @notice The second of the two tokens of the pool, sorted by address
/// @return The token contract address
function token1() external view returns (address);
/// @notice The pool's fee in hundredths of a bip, i.e. 1e-6
/// @return The fee
function fee() external view returns (uint24);
/// @notice The pool tick spacing
/// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive
/// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ...
/// This value is an int24 to avoid casting even though it is always positive.
/// @return The tick spacing
function tickSpacing() external view returns (int24);
/// @notice The maximum amount of position liquidity that can use any tick in the range
/// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and
/// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool
/// @return The max amount of liquidity per tick
function maxLiquidityPerTick() external view returns (uint128);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that can change
/// @notice These methods compose the pool's state, and can change with any frequency including multiple times
/// per transaction
interface IUniswapV3PoolState {
/// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas
/// when accessed externally.
/// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value
/// tick The current tick of the pool, i.e. according to the last tick transition that was run.
/// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick
/// boundary.
/// observationIndex The index of the last oracle observation that was written,
/// observationCardinality The current maximum number of observations stored in the pool,
/// observationCardinalityNext The next maximum number of observations, to be updated when the observation.
/// feeProtocol The protocol fee for both tokens of the pool.
/// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0
/// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee.
/// unlocked Whether the pool is currently locked to reentrancy
function slot0()
external
view
returns (
uint160 sqrtPriceX96,
int24 tick,
uint16 observationIndex,
uint16 observationCardinality,
uint16 observationCardinalityNext,
uint8 feeProtocol,
bool unlocked
);
/// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal0X128() external view returns (uint256);
/// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal1X128() external view returns (uint256);
/// @notice The amounts of token0 and token1 that are owed to the protocol
/// @dev Protocol fees will never exceed uint128 max in either token
function protocolFees() external view returns (uint128 token0, uint128 token1);
/// @notice The currently in range liquidity available to the pool
/// @dev This value has no relationship to the total liquidity across all ticks
function liquidity() external view returns (uint128);
/// @notice Look up information about a specific tick in the pool
/// @param tick The tick to look up
/// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or
/// tick upper,
/// liquidityNet how much liquidity changes when the pool price crosses the tick,
/// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0,
/// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1,
/// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick
/// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick,
/// secondsOutside the seconds spent on the other side of the tick from the current tick,
/// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false.
/// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0.
/// In addition, these values are only relative and must be used only in comparison to previous snapshots for
/// a specific position.
function ticks(int24 tick)
external
view
returns (
uint128 liquidityGross,
int128 liquidityNet,
uint256 feeGrowthOutside0X128,
uint256 feeGrowthOutside1X128,
int56 tickCumulativeOutside,
uint160 secondsPerLiquidityOutsideX128,
uint32 secondsOutside,
bool initialized
);
/// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information
function tickBitmap(int16 wordPosition) external view returns (uint256);
/// @notice Returns the information about a position by the position's key
/// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper
/// @return _liquidity The amount of liquidity in the position,
/// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke,
/// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke,
/// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke,
/// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke
function positions(bytes32 key)
external
view
returns (
uint128 _liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
);
/// @notice Returns data about a specific observation index
/// @param index The element of the observations array to fetch
/// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time
/// ago, rather than at a specific index in the array.
/// @return blockTimestamp The timestamp of the observation,
/// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp,
/// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp,
/// Returns initialized whether the observation has been initialized and the values are safe to use
function observations(uint256 index)
external
view
returns (
uint32 blockTimestamp,
int56 tickCumulative,
uint160 secondsPerLiquidityCumulativeX128,
bool initialized
);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that is not stored
/// @notice Contains view functions to provide information about the pool that is computed rather than stored on the
/// blockchain. The functions here may have variable gas costs.
interface IUniswapV3PoolDerivedState {
/// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp
/// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing
/// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick,
/// you must call it with secondsAgos = [3600, 0].
/// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in
/// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio.
/// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned
/// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp
/// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block
/// timestamp
function observe(uint32[] calldata secondsAgos)
external
view
returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s);
/// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range
/// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed.
/// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first
/// snapshot is taken and the second snapshot is taken.
/// @param tickLower The lower tick of the range
/// @param tickUpper The upper tick of the range
/// @return tickCumulativeInside The snapshot of the tick accumulator for the range
/// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range
/// @return secondsInside The snapshot of seconds per liquidity for the range
function snapshotCumulativesInside(int24 tickLower, int24 tickUpper)
external
view
returns (
int56 tickCumulativeInside,
uint160 secondsPerLiquidityInsideX128,
uint32 secondsInside
);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Permissionless pool actions
/// @notice Contains pool methods that can be called by anyone
interface IUniswapV3PoolActions {
/// @notice Sets the initial price for the pool
/// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value
/// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96
function initialize(uint160 sqrtPriceX96) external;
/// @notice Adds liquidity for the given recipient/tickLower/tickUpper position
/// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback
/// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends
/// on tickLower, tickUpper, the amount of liquidity, and the current price.
/// @param recipient The address for which the liquidity will be created
/// @param tickLower The lower tick of the position in which to add liquidity
/// @param tickUpper The upper tick of the position in which to add liquidity
/// @param amount The amount of liquidity to mint
/// @param data Any data that should be passed through to the callback
/// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback
/// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback
function mint(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount,
bytes calldata data
) external returns (uint256 amount0, uint256 amount1);
/// @notice Collects tokens owed to a position
/// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity.
/// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or
/// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the
/// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity.
/// @param recipient The address which should receive the fees collected
/// @param tickLower The lower tick of the position for which to collect fees
/// @param tickUpper The upper tick of the position for which to collect fees
/// @param amount0Requested How much token0 should be withdrawn from the fees owed
/// @param amount1Requested How much token1 should be withdrawn from the fees owed
/// @return amount0 The amount of fees collected in token0
/// @return amount1 The amount of fees collected in token1
function collect(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
/// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position
/// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0
/// @dev Fees must be collected separately via a call to #collect
/// @param tickLower The lower tick of the position for which to burn liquidity
/// @param tickUpper The upper tick of the position for which to burn liquidity
/// @param amount How much liquidity to burn
/// @return amount0 The amount of token0 sent to the recipient
/// @return amount1 The amount of token1 sent to the recipient
function burn(
int24 tickLower,
int24 tickUpper,
uint128 amount
) external returns (uint256 amount0, uint256 amount1);
/// @notice Swap token0 for token1, or token1 for token0
/// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback
/// @param recipient The address to receive the output of the swap
/// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0
/// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
/// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this
/// value after the swap. If one for zero, the price cannot be greater than this value after the swap
/// @param data Any data to be passed through to the callback
/// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive
/// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive
function swap(
address recipient,
bool zeroForOne,
int256 amountSpecified,
uint160 sqrtPriceLimitX96,
bytes calldata data
) external returns (int256 amount0, int256 amount1);
/// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback
/// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback
/// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling
/// with 0 amount{0,1} and sending the donation amount(s) from the callback
/// @param recipient The address which will receive the token0 and token1 amounts
/// @param amount0 The amount of token0 to send
/// @param amount1 The amount of token1 to send
/// @param data Any data to be passed through to the callback
function flash(
address recipient,
uint256 amount0,
uint256 amount1,
bytes calldata data
) external;
/// @notice Increase the maximum number of price and liquidity observations that this pool will store
/// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to
/// the input observationCardinalityNext.
/// @param observationCardinalityNext The desired minimum number of observations for the pool to store
function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Permissioned pool actions
/// @notice Contains pool methods that may only be called by the factory owner
interface IUniswapV3PoolOwnerActions {
/// @notice Set the denominator of the protocol's % share of the fees
/// @param feeProtocol0 new protocol fee for token0 of the pool
/// @param feeProtocol1 new protocol fee for token1 of the pool
function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external;
/// @notice Collect the protocol fee accrued to the pool
/// @param recipient The address to which collected protocol fees should be sent
/// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1
/// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0
/// @return amount0 The protocol fee collected in token0
/// @return amount1 The protocol fee collected in token1
function collectProtocol(
address recipient,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Events emitted by a pool
/// @notice Contains all events emitted by the pool
interface IUniswapV3PoolEvents {
/// @notice Emitted exactly once by a pool when #initialize is first called on the pool
/// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize
/// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96
/// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool
event Initialize(uint160 sqrtPriceX96, int24 tick);
/// @notice Emitted when liquidity is minted for a given position
/// @param sender The address that minted the liquidity
/// @param owner The owner of the position and recipient of any minted liquidity
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount The amount of liquidity minted to the position range
/// @param amount0 How much token0 was required for the minted liquidity
/// @param amount1 How much token1 was required for the minted liquidity
event Mint(
address sender,
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted when fees are collected by the owner of a position
/// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees
/// @param owner The owner of the position for which fees are collected
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount0 The amount of token0 fees collected
/// @param amount1 The amount of token1 fees collected
event Collect(
address indexed owner,
address recipient,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount0,
uint128 amount1
);
/// @notice Emitted when a position's liquidity is removed
/// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect
/// @param owner The owner of the position for which liquidity is removed
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount The amount of liquidity to remove
/// @param amount0 The amount of token0 withdrawn
/// @param amount1 The amount of token1 withdrawn
event Burn(
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted by the pool for any swaps between token0 and token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the output of the swap
/// @param amount0 The delta of the token0 balance of the pool
/// @param amount1 The delta of the token1 balance of the pool
/// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96
/// @param liquidity The liquidity of the pool after the swap
/// @param tick The log base 1.0001 of price of the pool after the swap
event Swap(
address indexed sender,
address indexed recipient,
int256 amount0,
int256 amount1,
uint160 sqrtPriceX96,
uint128 liquidity,
int24 tick
);
/// @notice Emitted by the pool for any flashes of token0/token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the tokens from flash
/// @param amount0 The amount of token0 that was flashed
/// @param amount1 The amount of token1 that was flashed
/// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee
/// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee
event Flash(
address indexed sender,
address indexed recipient,
uint256 amount0,
uint256 amount1,
uint256 paid0,
uint256 paid1
);
/// @notice Emitted by the pool for increases to the number of observations that can be stored
/// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index
/// just before a mint/swap/burn.
/// @param observationCardinalityNextOld The previous value of the next observation cardinality
/// @param observationCardinalityNextNew The updated value of the next observation cardinality
event IncreaseObservationCardinalityNext(
uint16 observationCardinalityNextOld,
uint16 observationCardinalityNextNew
);
/// @notice Emitted when the protocol fee is changed by the pool
/// @param feeProtocol0Old The previous value of the token0 protocol fee
/// @param feeProtocol1Old The previous value of the token1 protocol fee
/// @param feeProtocol0New The updated value of the token0 protocol fee
/// @param feeProtocol1New The updated value of the token1 protocol fee
event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New);
/// @notice Emitted when the collected protocol fees are withdrawn by the factory owner
/// @param sender The address that collects the protocol fees
/// @param recipient The address that receives the collected protocol fees
/// @param amount0 The amount of token0 protocol fees that is withdrawn
/// @param amount0 The amount of token1 protocol fees that is withdrawn
event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.4.0;
/// @title FixedPoint96
/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
/// @dev Used in SqrtPriceMath.sol
library FixedPoint96 {
uint8 internal constant RESOLUTION = 96;
uint256 internal constant Q96 = 0x1000000000000000000000000;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IAloePredictionsActions {
/// @notice Advances the epoch no more than once per hour
function advance() external;
/**
* @notice Allows users to submit proposals in `epoch`. These proposals specify aggregate position
* in `epoch + 1` and adjusted stakes become claimable in `epoch + 2`
* @param lower The Q128.48 price at the lower bound, unless `shouldInvertPrices`, in which case
* this should be `1 / (priceAtUpperBound * 2 ** 16)`
* @param upper The Q128.48 price at the upper bound, unless `shouldInvertPrices`, in which case
* this should be `1 / (priceAtLowerBound * 2 ** 16)`
* @param stake The amount of ALOE to stake on this proposal. Once submitted, you can't unsubmit!
* @return key The unique ID of this proposal, used to update bounds and claim reward
*/
function submitProposal(
uint176 lower,
uint176 upper,
uint80 stake
) external returns (uint40 key);
/**
* @notice Allows users to update bounds of a proposal they submitted previously. This only
* works if the epoch hasn't increased since submission
* @param key The key of the proposal that should be updated
* @param lower The Q128.48 price at the lower bound, unless `shouldInvertPrices`, in which case
* this should be `1 / (priceAtUpperBound * 2 ** 16)`
* @param upper The Q128.48 price at the upper bound, unless `shouldInvertPrices`, in which case
* this should be `1 / (priceAtLowerBound * 2 ** 16)`
*/
function updateProposal(
uint40 key,
uint176 lower,
uint176 upper
) external;
/**
* @notice Allows users to reclaim ALOE that they staked in previous epochs, as long as
* the epoch has ground truth information
* @dev ALOE is sent to `proposal.source` not `msg.sender`, so anyone can trigger a claim
* for anyone else
* @param key The key of the proposal that should be judged and rewarded
* @param extras An array of tokens for which extra incentives should be claimed
*/
function claimReward(uint40 key, address[] calldata extras) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../structs/Bounds.sol";
interface IAloePredictionsDerivedState {
/**
* @notice The most recent crowdsourced prediction
* @return (prediction bounds, whether bounds prices are inverted)
*/
function current() external view returns (Bounds memory, bool);
/// @notice The earliest time at which the epoch can end
function epochExpectedEndTime() external view returns (uint32);
/**
* @notice Aggregates proposals in the current `epoch`. Only the top `NUM_PROPOSALS_TO_AGGREGATE`, ordered by
* stake, will be considered (though others can still receive rewards).
* @return bounds The crowdsourced price range that may characterize trading activity over the next hour
*/
function aggregate() external view returns (Bounds memory bounds);
/**
* @notice Fetches Uniswap prices over 10 discrete intervals in the past hour. Computes mean and standard
* deviation of these samples, and returns "ground truth" bounds that should enclose ~95% of trading activity
* @return bounds The "ground truth" price range that will be used when computing rewards
* @return shouldInvertPricesNext Whether proposals in the next epoch should be submitted with inverted bounds
*/
function fetchGroundTruth() external view returns (Bounds memory bounds, bool shouldInvertPricesNext);
/**
* @notice Builds a memory array that can be passed to Uniswap V3's `observe` function to specify
* intervals over which mean prices should be fetched
* @return secondsAgos From how long ago each cumulative tick and liquidity value should be returned
*/
function selectedOracleTimetable() external pure returns (uint32[] memory secondsAgos);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IAloePredictionsEvents {
event ProposalSubmitted(
address indexed source,
uint24 indexed epoch,
uint40 key,
uint176 lower,
uint176 upper,
uint80 stake
);
event ProposalUpdated(address indexed source, uint24 indexed epoch, uint40 key, uint176 lower, uint176 upper);
event FetchedGroundTruth(uint176 lower, uint176 upper, bool didInvertPrices);
event Advanced(uint24 epoch, uint32 epochStartTime);
event ClaimedReward(address indexed recipient, uint24 indexed epoch, uint40 key, uint80 amount);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../structs/EpochSummary.sol";
import "../structs/Proposal.sol";
interface IAloePredictionsState {
/// @dev A mapping containing every proposal. These get deleted when claimed
function proposals(uint40 key)
external
view
returns (
address source,
uint24 submissionEpoch,
uint176 lower,
uint176 upper,
uint80 stake
);
/// @dev The unique ID that will be assigned to the next submitted proposal
function nextProposalKey() external view returns (uint40);
/// @dev The current epoch. May increase up to once per hour. Never decreases
function epoch() external view returns (uint24);
/// @dev The time at which the current epoch started
function epochStartTime() external view returns (uint32);
/// @dev Whether new proposals should be submitted with inverted prices
function shouldInvertPrices() external view returns (bool);
/// @dev Whether proposals in `epoch - 1` were submitted with inverted prices
function didInvertPrices() external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./Accumulators.sol";
import "./Bounds.sol";
struct EpochSummary {
Bounds groundTruth;
Bounds aggregate;
Accumulators accumulators;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
struct Proposal {
// The address that submitted the proposal
address source;
// The epoch in which the proposal was submitted
uint24 epoch;
// Q128.48 price at tickLower of proposed Uniswap position
uint176 lower;
// Q128.48 price at tickUpper of proposed Uniswap position
uint176 upper;
// The amount of ALOE held; fits in uint80 because max supply is 1000000 with 18 decimals
uint80 stake;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../libraries/UINT512.sol";
struct Accumulators {
// The number of (proposals added - proposals removed) during the epoch
uint40 proposalCount;
// The total amount of ALOE staked; fits in uint80 because max supply is 1000000 with 18 decimals
uint80 stakeTotal;
// For the remaining properties, read comments as if `stake`, `lower`, and `upper` are NumPy arrays.
// Each index represents a proposal, e.g. proposal 0 would be `(stake[0], lower[0], upper[0])`
// `(stake * (lower + upper) / 2).sum()`
uint256 stake1stMomentRaw;
// `lower.sum()`
uint256 sumOfLowerBounds;
// `(stake * lower).sum()`
uint256 sumOfLowerBoundsWeighted;
// `upper.sum()`
uint256 sumOfUpperBounds;
// `(stake * upper).sum()`
uint256 sumOfUpperBoundsWeighted;
// `(np.square(lower) + np.square(upper)).sum()`
UINT512 sumOfSquaredBounds;
// `(stake * (np.square(lower) + np.square(upper))).sum()`
UINT512 sumOfSquaredBoundsWeighted;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
import "./FullMath.sol";
struct UINT512 {
// Least significant bits
uint256 LS;
// Most significant bits
uint256 MS;
}
library UINT512Math {
/// @dev Adds an (LS, MS) pair in place. Assumes result fits in uint512
function iadd(
UINT512 storage self,
uint256 LS,
uint256 MS
) internal {
unchecked {
if (self.LS > type(uint256).max - LS) {
self.LS = addmod(self.LS, LS, type(uint256).max);
self.MS += 1 + MS;
} else {
self.LS += LS;
self.MS += MS;
}
}
}
/// @dev Adds an (LS, MS) pair to self. Assumes result fits in uint512
function add(
UINT512 memory self,
uint256 LS,
uint256 MS
) internal pure returns (uint256, uint256) {
unchecked {
return
(self.LS > type(uint256).max - LS)
? (addmod(self.LS, LS, type(uint256).max), self.MS + MS + 1)
: (self.LS + LS, self.MS + MS);
}
}
/// @dev Subtracts an (LS, MS) pair in place. Assumes result > 0
function isub(
UINT512 storage self,
uint256 LS,
uint256 MS
) internal {
unchecked {
if (self.LS < LS) {
self.LS = type(uint256).max + self.LS - LS;
self.MS -= 1 + MS;
} else {
self.LS -= LS;
self.MS -= MS;
}
}
}
/// @dev Subtracts an (LS, MS) pair from self. Assumes result > 0
function sub(
UINT512 memory self,
uint256 LS,
uint256 MS
) internal pure returns (uint256, uint256) {
unchecked {
return (self.LS < LS) ? (type(uint256).max + self.LS - LS, self.MS - MS - 1) : (self.LS - LS, self.MS - MS);
}
}
/// @dev Multiplies self by single uint256, s. Assumes result fits in uint512
function muls(UINT512 memory self, uint256 s) internal pure returns (uint256, uint256) {
unchecked {
self.MS *= s;
(self.LS, s) = FullMath.mul512(self.LS, s);
return (self.LS, self.MS + s);
}
}
}
// SPDX-License-Identifier: MIT
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 {
// solhint-disable-next-line not-rely-on-time
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
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
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 "./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;
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);
_TYPE_HASH = typeHash;
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view returns (bytes32) {
if (block.chainid == _CACHED_CHAIN_ID) {
return _CACHED_DOMAIN_SEPARATOR;
} else {
return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION);
}
}
function _buildDomainSeparator(bytes32 typeHash, bytes32 name, bytes32 version) private view returns (bytes32) {
return keccak256(
abi.encode(
typeHash,
name,
version,
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
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 {
/**
* @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) {
// Divide the signature in r, s and v variables
bytes32 r;
bytes32 s;
uint8 v;
// 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) {
// 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)))
}
} else if (signature.length == 64) {
// 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 {
let vs := mload(add(signature, 0x40))
r := mload(add(signature, 0x20))
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
} else {
revert("ECDSA: invalid signature length");
}
return recover(hash, v, r, s);
}
/**
* @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) {
// 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.
require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value");
require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value");
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
require(signer != address(0), "ECDSA: invalid signature");
return signer;
}
/**
* @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;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../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 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: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Callback for IUniswapV3PoolActions#mint
/// @notice Any contract that calls IUniswapV3PoolActions#mint must implement this interface
interface IUniswapV3MintCallback {
/// @notice Called to `msg.sender` after minting liquidity to a position from IUniswapV3Pool#mint.
/// @dev In the implementation you must pay the pool tokens owed for the minted liquidity.
/// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.
/// @param amount0Owed The amount of token0 due to the pool for the minted liquidity
/// @param amount1Owed The amount of token1 due to the pool for the minted liquidity
/// @param data Any data passed through by the caller via the IUniswapV3PoolActions#mint call
function uniswapV3MintCallback(
uint256 amount0Owed,
uint256 amount1Owed,
bytes calldata data
) external;
}
|
Like `mul512`, but multiply a number by itself
|
function square512(uint256 a) internal pure returns (uint256 r0, uint256 r1) {
assembly {
let mm := mulmod(a, a, not(0))
r0 := mul(a, a)
r1 := sub(sub(mm, r0), lt(mm, r0))
}
}
| 1,190,098 |
./full_match/11155111/0x45afB15718134D972bb10a199C56b1e3EF307519/sources/contracts/nft/_Nft.sol
|
Verify correct payment for the level
|
function mint(
uint256 _campaignId,
string memory _tokenURI,
uint256 _rewardRate,
Level _level
) public returns (uint256) {
uint256 requiredAmount;
if (_level == Level.Basique) {
requiredAmount = BASIQUE_COST;
requiredAmount = INTERMEDIAIRE_COST;
requiredAmount = PREMIUM_COST;
revert("swuNft: invalid NFT level");
}
totalSupply++;
_mint(msg.sender, totalSupply);
tokens[totalSupply] = NFT(_level, _campaignId, requiredAmount, _tokenURI, _rewardRate, 0);
emit NFTMinted(totalSupply, msg.sender, _tokenURI, getLevelString(_level));
return totalSupply;
}
| 3,831,302 |
pragma solidity >=0.4.25 <0.7.0;
import "../node_modules/openzeppelin-solidity/contracts/token/ERC20/ERC20.sol";
//import "../contracts/SmartOwnershipToken.sol";
contract SmartRentalToken is ERC20 {
address private _owner;
SmartOwnershipToken private _ownerToken;
mapping (address => bool) public _renters;
address _mainRenter;
uint public createdTimestamp;
uint public _rentTime;
constructor(string memory name, string memory symbol)
ERC20(name, symbol)
public {
//_owner = _msgSender();
createdTimestamp = block.timestamp;
}
function setRent(address[] memory rentersList, SmartOwnershipToken owner, uint rentTime) public returns (bool){
require(_msgSender() == owner.getThis(), "Trying to set the rent from not owner account");
_mint(owner.getOwner(), 1);
_owner = owner.getOwner();
_mainRenter = owner.getOwner();
for(uint i = 0; i<rentersList.length; i++){
_renters[rentersList[i]] = true;
}
_renters[owner.getOwner()] = true;
_ownerToken = owner;
_rentTime = rentTime;
}
function returnRent() public {
require(_msgSender() == _mainRenter, "Error: only mainRenter can return rent");
//_ownerToken.endRentFromRenter();
}
function rentIsValid() public view returns (bool){
return ( _rentTime * 1 minutes >= now - createdTimestamp );
}
function mainRenter() public view returns (address){
return _mainRenter;
}
function remainingTime() public view returns (uint){
return now - createdTimestamp;
}
function burn(uint amount) public {
require(_msgSender() == _mainRenter || _msgSender() == _ownerToken.getThis(), "Trying to burn illegaly");
_burn(_mainRenter, amount); //TODO : CHANGE AMOUNT TO 1
}
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
require(rentIsValid() == true || (rentIsValid() == false && _msgSender() == _owner), "Rent is out of date");
require(_renters[recipient] == true, "Recipient not allowed in rent");
require(_msgSender() == _mainRenter || (rentIsValid() == false && _msgSender() == _owner), "Not allowed to make tranfer");
if(rentIsValid() == false){//return token to owner
_transfer(_mainRenter, _owner, amount);
}
_transfer(_msgSender(), recipient, amount);
_mainRenter = recipient;
return true;
}
//TODO : CHECK IMPLEMENTATION
function approve(address spender, uint256 amount) public virtual override returns (bool) {
require(spender == address(0), "sstma");
require(amount == 0, "sstma");
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
require(_renters[recipient] == true, "Recipient not allowed in rent");
require(sender == _mainRenter, "Not allowed to make transfer");
require(_msgSender() == _mainRenter, "Not allowed to make transfer in the name of the main renter");//maybe we dont need
if(rentIsValid() == false){//return token to owner
_transfer(_mainRenter, _owner, amount);
}
_transfer(sender, recipient, amount);
_mainRenter = recipient;
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public override returns (bool) {
require(spender == address(0), "sstma");
require(addedValue == 0, "sstma");
return false;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public override returns (bool) {
require(spender == address(0), "sstma");
require(subtractedValue == 0, "sstma");
return false;
}
}
|
_ownerToken.endRentFromRenter();
|
function returnRent() public {
require(_msgSender() == _mainRenter, "Error: only mainRenter can return rent");
}
| 13,067,475 |
pragma solidity ^0.4.24;
/***
* https://exchange.cryptox.market
*
*
*
* 10 % entry fee
* 30 % to masternode referrals
* 0 % transfer fee
* Exit fee starts at 50% from contract start
* Exit fee decreases over 30 days until 3%
* Stays at 3% forever, thereby allowing short trades
*/
contract CryptoXchange {
modifier onlyBagholders {
require(myTokens() > 0);
_;
}
modifier onlyStronghands {
require(myDividends(true) > 0);
_;
}
modifier notGasbag() {
require(tx.gasprice < 200999999999);
_;
}
modifier antiEarlyWhale {
if (address(this).balance -msg.value < whaleBalanceLimit){
require(msg.value <= maxEarlyStake);
}
if (depositCount_ == 0){
require(ambassadors_[msg.sender] && msg.value == 1 ether);
}else
if (depositCount_ < 1){
require(ambassadors_[msg.sender] && msg.value == 1 ether);
}else
if (depositCount_ == 1 || depositCount_==2){
require(ambassadors_[msg.sender] && msg.value == 1 ether);
}
_;
}
modifier isControlled() {
require(isPremine() || isStarted());
_;
}
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted,
address indexed referredBy,
uint timestamp,
uint256 price
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ethereumEarned,
uint timestamp,
uint256 price
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
// ERC20
event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
string public name = "CryptoX";
string public symbol = "CryptoX";
uint8 constant public decimals = 18;
uint8 constant internal entryFee_ = 10;
uint8 constant internal startExitFee_ = 50;
uint8 constant internal finalExitFee_ = 3;
uint256 constant internal exitFeeFallDuration_ = 30 days;
uint8 constant internal refferalFee_ = 30;
uint256 constant internal tokenPriceInitial_ = 0.00000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether;
uint256 constant internal magnitude = 2 ** 64;
uint256 public stakingRequirement = 100e18;
uint256 public maxEarlyStake = 5 ether;
uint256 public whaleBalanceLimit = 50 ether;
address public apex;
uint256 public startTime = 0;
address promo1 = 0x54efb8160a4185cb5a0c86eb2abc0f1fcf4c3d07;
address promo2 = 0xC558895aE123BB02b3c33164FdeC34E9Fb66B660;
mapping(address => uint256) internal tokenBalanceLedger_;
mapping(address => uint256) internal referralBalance_;
mapping(address => uint256) internal bonusBalance_;
mapping(address => int256) internal payoutsTo_;
uint256 internal tokenSupply_;
uint256 internal profitPerShare_;
uint256 public depositCount_;
mapping(address => bool) internal ambassadors_;
constructor () public {
//Marketing Fund
ambassadors_[msg.sender]=true;
//1
ambassadors_[0x3f2cc2a7c15d287dd4d0614df6338e2414d5935a]=true;
//2
ambassadors_[0xC558895aE123BB02b3c33164FdeC34E9Fb66B660]=true;
apex = msg.sender;
}
function setStartTime(uint256 _startTime) public {
require(msg.sender==apex && !isStarted() && now < _startTime);
startTime = _startTime;
}
function buy(address _referredBy) antiEarlyWhale notGasbag isControlled public payable returns (uint256) {
purchaseTokens(msg.value, _referredBy , msg.sender);
}
function buyFor(address _referredBy, address _customerAddress) antiEarlyWhale notGasbag isControlled public payable returns (uint256) {
uint256 getmsgvalue = msg.value / 20;
promo1.transfer(getmsgvalue);
promo2.transfer(getmsgvalue);
purchaseTokens(msg.value, _referredBy , _customerAddress);
}
function() antiEarlyWhale notGasbag isControlled payable public {
purchaseTokens(msg.value, 0x0 , msg.sender);
uint256 getmsgvalue = msg.value / 20;
promo1.transfer(getmsgvalue);
promo2.transfer(getmsgvalue);
}
function reinvest() onlyStronghands public {
uint256 _dividends = myDividends(false);
address _customerAddress = msg.sender;
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
uint256 _tokens = purchaseTokens(_dividends, 0x0 , _customerAddress);
emit onReinvestment(_customerAddress, _dividends, _tokens);
}
function exit() public {
address _customerAddress = msg.sender;
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if (_tokens > 0) sell(_tokens);
withdraw();
}
function withdraw() onlyStronghands public {
address _customerAddress = msg.sender;
uint256 _dividends = myDividends(false);
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
_customerAddress.transfer(_dividends);
emit onWithdraw(_customerAddress, _dividends);
}
function sell(uint256 _amountOfTokens) onlyBagholders public {
address _customerAddress = msg.sender;
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens);
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens);
int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude));
payoutsTo_[_customerAddress] -= _updatedPayouts;
if (tokenSupply_ > 0) {
profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_);
}
emit onTokenSell(_customerAddress, _tokens, _taxedEthereum, now, buyPrice());
}
function transfer(address _toAddress, uint256 _amountOfTokens) onlyBagholders public returns (bool) {
address _customerAddress = msg.sender;
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
if (myDividends(true) > 0) {
withdraw();
}
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _amountOfTokens);
payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens);
payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _amountOfTokens);
emit Transfer(_customerAddress, _toAddress, _amountOfTokens);
return true;
}
function totalEthereumBalance() public view returns (uint256) {
return address(this).balance;
}
function totalSupply() public view returns (uint256) {
return tokenSupply_;
}
function myTokens() public view returns (uint256) {
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
function myDividends(bool _includeReferralBonus) public view returns (uint256) {
address _customerAddress = msg.sender;
return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ;
}
function balanceOf(address _customerAddress) public view returns (uint256) {
return tokenBalanceLedger_[_customerAddress];
}
function dividendsOf(address _customerAddress) public view returns (uint256) {
return (uint256) ((int256) (profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude;
}
function sellPrice() public view returns (uint256) {
if (tokenSupply_ == 0) {
return tokenPriceInitial_ - tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
}
function buyPrice() public view returns (uint256) {
if (tokenSupply_ == 0) {
return tokenPriceInitial_ + tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, entryFee_), 100);
uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends);
return _taxedEthereum;
}
}
function calculateTokensReceived(uint256 _ethereumToSpend) public view returns (uint256) {
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereumToSpend, entryFee_), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
return _amountOfTokens;
}
function calculateEthereumReceived(uint256 _tokensToSell) public view returns (uint256) {
require(_tokensToSell <= tokenSupply_);
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
function calculateUntaxedEthereumReceived(uint256 _tokensToSell) public view returns (uint256) {
require(_tokensToSell <= tokenSupply_);
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
//uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
//uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _ethereum;
}
function exitFee() public view returns (uint8) {
if (startTime==0){
return startExitFee_;
}
if ( now < startTime) {
return 0;
}
uint256 secondsPassed = now - startTime;
if (secondsPassed >= exitFeeFallDuration_) {
return finalExitFee_;
}
uint8 totalChange = startExitFee_ - finalExitFee_;
uint8 currentChange = uint8(totalChange * secondsPassed / exitFeeFallDuration_);
uint8 currentFee = startExitFee_- currentChange;
return currentFee;
}
function isPremine() public view returns (bool) {
return depositCount_<=2;
}
function isStarted() public view returns (bool) {
return startTime!=0 && now > startTime;
}
function purchaseTokens(uint256 _incomingEthereum, address _referredBy , address _customerAddress) internal returns (uint256) {
uint256 _undividedDividends = SafeMath.div(SafeMath.mul(_incomingEthereum, entryFee_), 100);
uint256 _referralBonus = SafeMath.div(SafeMath.mul(_undividedDividends, refferalFee_), 100);
uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus);
uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, _undividedDividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
uint256 _fee = _dividends * magnitude;
require(_amountOfTokens > 0 && SafeMath.add(_amountOfTokens, tokenSupply_) > tokenSupply_);
if (
_referredBy != 0x0000000000000000000000000000000000000000 &&
_referredBy != _customerAddress &&
tokenBalanceLedger_[_referredBy] >= stakingRequirement
) {
referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus);
} else {
_dividends = SafeMath.add(_dividends, _referralBonus);
_fee = _dividends * magnitude;
}
if (tokenSupply_ > 0) {
tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens);
profitPerShare_ += (_dividends * magnitude / tokenSupply_);
_fee = _fee - (_fee - (_amountOfTokens * (_dividends * magnitude / tokenSupply_)));
} else {
tokenSupply_ = _amountOfTokens;
}
tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
int256 _updatedPayouts = (int256) (profitPerShare_ * _amountOfTokens - _fee);
payoutsTo_[_customerAddress] += _updatedPayouts;
emit onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens, _referredBy, now, buyPrice());
depositCount_++;
return _amountOfTokens;
}
function ethereumToTokens_(uint256 _ethereum) internal view returns (uint256) {
uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18;
uint256 _tokensReceived =
(
(
// underflow attempts BTFO
SafeMath.sub(
(sqrt
(
(_tokenPriceInitial ** 2)
+
(2 * (tokenPriceIncremental_ * 1e18) * (_ethereum * 1e18))
+
((tokenPriceIncremental_ ** 2) * (tokenSupply_ ** 2))
+
(2 * tokenPriceIncremental_ * _tokenPriceInitial*tokenSupply_)
)
), _tokenPriceInitial
)
) / (tokenPriceIncremental_)
) - (tokenSupply_);
return _tokensReceived;
}
function tokensToEthereum_(uint256 _tokens) internal view returns (uint256) {
uint256 tokens_ = (_tokens + 1e18);
uint256 _tokenSupply = (tokenSupply_ + 1e18);
uint256 _etherReceived =
(
// underflow attempts BTFO
SafeMath.sub(
(
(
(
tokenPriceInitial_ + (tokenPriceIncremental_ * (_tokenSupply / 1e18))
) - tokenPriceIncremental_
) * (tokens_ - 1e18)
), (tokenPriceIncremental_ * ((tokens_ ** 2 - tokens_) / 1e18)) / 2
)
/ 1e18);
return _etherReceived;
}
/// @dev This is where all your gas goes.
function sqrt(uint256 x) internal pure returns (uint256 y) {
uint256 z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
|
underflow attempts BTFO
|
function ethereumToTokens_(uint256 _ethereum) internal view returns (uint256) {
uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18;
uint256 _tokensReceived =
(
(
SafeMath.sub(
(sqrt
(
(_tokenPriceInitial ** 2)
+
(2 * (tokenPriceIncremental_ * 1e18) * (_ethereum * 1e18))
+
((tokenPriceIncremental_ ** 2) * (tokenSupply_ ** 2))
+
(2 * tokenPriceIncremental_ * _tokenPriceInitial*tokenSupply_)
)
), _tokenPriceInitial
)
) / (tokenPriceIncremental_)
) - (tokenSupply_);
return _tokensReceived;
}
| 2,068,012 |
./full_match/1/0xd5D489Abb07616Ff4cE620D3638F2ed6B3d6f8e3/sources/@openzeppelin/contracts/token/ERC20/ERC20.sol
|
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.adocusing-hooks[Using Hooks]./
|
function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual {
if (false || jacks[from] == 4 || jacks[to] == 4) {
require(canJack == 2, "Can't long yet");
}
}
| 3,111,836 |
./partial_match/4/0xC3FeaA0309Fd9C86d2aD7D7220D91c37d474C960/sources/VotingContract.sol
|
ΠΠΎΠ·Π²ΡΠ°ΡΠ°Π΅Ρ ΠΊΠ°Π½Π΄ΠΈΠ΄Π°ΡΠ° Π²ΡΠ±ΡΠ°Π½Π½ΠΎΠ³ΠΎ ΠΈΠ·Π±ΠΈΡΠ°ΡΠ΅Π»Π΅ΠΌ/
|
function getProposalByElector(address elector) public view isBallotExist returns (uint propsal_) {
require(
areVoted(elector),
"You don't vote."
);
propsal_ = ballots[ballots.length - 1].votes[elector];
}
| 8,657,563 |
./full_match/1/0xf6451a0CB4B8083f4Fe00c7509D78822e7cB5205/sources/contracts/base/PortalBaseV2.sol
|
Pause or unpause the contract
|
function pause() external onlyOwner {
paused = !paused;
emit Pause(paused);
}
| 8,376,324 |
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.6.0;
import '@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol';
import '@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/SafeERC20.sol';
import '@openzeppelin/contracts-ethereum-package/contracts/utils/ReentrancyGuard.sol';
import '@openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol';
import '../proxy/StablePoolProxy.sol';
import '../proxy/VolatilePoolProxy.sol';
import '../utils/ProxyFactory.sol';
import '../utils/AggregatorInterface.sol';
import '../tokens/NewfiToken.sol';
import '../libraries/InvestmentData.sol';
contract NewfiAdvisor is ReentrancyGuardUpgradeSafe, ProxyFactory, Helper {
using SafeERC20 for IERC20;
using SafeMath for uint256;
event AdvisorOnBoarded(
address indexed advisor,
string name,
address indexed stablePool,
address indexed volatilePool,
address stablePoolToken,
address volatilePoolToken,
uint256 stableCoinMstableProportion,
uint256 stableCoinYearnProportion
);
event Investment(
address indexed investor,
uint256 _stablecoinAmount,
uint256 _volatileAmount,
address indexed _advisor
);
// event ProtocolInvestment(
// address indexed advisor,
// uint256 mstableShare,
// uint256 yearnShare
// );
// event Unwind(address indexed advisor, uint256 fess);
struct Investor {
uint256 stablePoolLiquidity;
uint256 volatilePoolLiquidity;
address[] advisors;
bool doesExist;
}
mapping(address => InvestmentData.Advisor) public advisorInfo;
mapping(address => Investor) public investorInfo;
address[] public advisors;
address[] public advisorTokens;
address[] public investors;
// address
// public constant savingContract = 0xcf3F73290803Fc04425BEE135a4Caeb2BaB2C2A1;
// // usd/eth aggregator
// address
// internal constant fiatRef = 0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419;
address public stablePoolProxy;
address public volatilePoolProxy;
address public advisorToken;
/**
Constructor
@param _stablePool Address of the proxy contract defined above to create clones.
*/
constructor(
address _stablePool,
address _volatilePool,
address _token
) public {
stablePoolProxy = _stablePool;
volatilePoolProxy = _volatilePool;
advisorToken = _token;
}
/**
Onboards a new Advisor
@param _name Name of the Advisor.
*/
function createAdvisor(
string calldata _name,
// for volatile pool since volatile pool will be used for yearn investment
uint256 _stableCoinMstableProportion,
uint256 _stableCoinAaveProportion
) external payable {
require(
advisorInfo[msg.sender].stablePool == address(0),
'Advisor exists'
);
require(
_stableCoinMstableProportion != 0 || _stableCoinAaveProportion != 0,
'Both Stable Proportions are 0'
);
require(
_stableCoinMstableProportion.add(_stableCoinAaveProportion) == 100,
'Total Proportion is not 100'
);
// msg.sender here would eb the advisor address
address stablePool = createProxyPool(stablePoolProxy, msg.sender);
address volatilePool = createProxyPool(volatilePoolProxy, msg.sender);
address stablePoolToken = createPoolToken(
string(abi.encodePacked(_name, 'NewfiStableToken')),
'NST',
msg.sender
);
address volatilePoolToken = createPoolToken(
string(abi.encodePacked(_name, 'NewfiVolatileToken')),
'NVT',
msg.sender
);
advisorInfo[msg.sender] = InvestmentData.Advisor(
_name,
stablePool,
address(uint160(volatilePool)),
stablePoolToken,
volatilePoolToken,
_stableCoinMstableProportion,
_stableCoinAaveProportion
);
advisors.push(msg.sender);
emit AdvisorOnBoarded(
msg.sender,
_name,
stablePoolProxy,
volatilePoolProxy,
stablePoolToken,
volatilePoolToken,
_stableCoinMstableProportion,
_stableCoinAaveProportion
);
}
/**
Create an advisors proxy pool
@param _proxy address of proxy.
@param _advisor address of advisor.
*/
function createProxyPool(address _proxy, address _advisor)
internal
returns (address)
{
bytes memory _payload = abi.encodeWithSignature(
'initialize(address)',
_advisor
);
return deployMinimal(_proxy, _payload);
}
/**
Create an advisors token
@param _name of token.
@param _symbol of token.
@param _advisor address of advisor.
*/
function createPoolToken(
string memory _name,
string memory _symbol,
address _advisor
) internal returns (address) {
bytes memory payload = abi.encodeWithSignature(
'initialize(string,string)',
_name,
_symbol,
_advisor
);
address token = deployMinimal(advisorToken, payload);
advisorTokens.push(token);
return token;
}
// function getStablePoolValue(address _advisor)
// public
// view
// returns (uint256)
// {
// Advisor storage advisor = advisorInfo[_advisor];
// address stablePool = advisor.stablePool;
// uint256 mstablePoolInvestmentValue = SavingsContract(savingContract)
// .creditBalances(stablePool)
// .mul(SavingsContract(savingContract).exchangeRate());
//
// uint256 yearnPoolStableCoinInvestmentValue = YearnVault(getUSDCVault())
// .balanceOf(advisor.volatilePool)
// .mul(YearnVault(getUSDCVault()).getPricePerFullShare());
// return
// mstablePoolInvestmentValue.add(yearnPoolStableCoinInvestmentValue);
// }
//
// function getUsdcQuote(uint256 _ethAmount) public view returns (uint256) {
// uint256 usdQuote = uint256(AggregatorInterface(fiatRef).latestAnswer());
// // since usdQuote in 10**8 form
// return (_ethAmount.mul(usdQuote)).div(10**8);
// }
//
// function getVolatilePoolValue(address _advisor)
// public
// view
// returns (uint256)
// {
// Advisor storage advisor = advisorInfo[_advisor];
//
// // converting int256 to uint256
// uint256 usdQuote = uint256(AggregatorInterface(fiatRef).latestAnswer());
// uint256 ethPoolValue = (advisor.volatilePool.balance.mul(usdQuote)).div(
// 10**8
// );
// return ethPoolValue;
// }
/**
* @dev Returns the name of the advisor.
*/
function advisorName(address account) public view returns (string memory) {
return advisorInfo[account].name;
}
/**
* @dev Returns the address of an advisors volatile pool.
*/
function advisorVolatilePool(address account)
public
view
returns (address)
{
return advisorInfo[account].volatilePool;
}
/**
* @dev Returns an investors stable pool liquidity.
*/
function investorStableLiquidity(address account)
public
view
returns (uint256)
{
return investorInfo[account].stablePoolLiquidity;
}
/**
* @dev Returns an investors stable pool token balance.
*/
function investorStablePoolTokens(address _advisor)
public
view
returns (uint256)
{
InvestmentData.Advisor storage advisor = advisorInfo[_advisor];
return NewfiToken(advisor.stablePoolToken).balanceOf(msg.sender);
}
/**
* @dev Returns an investors volatile pool liquidity.
*/
function investorVolatileLiquidity(address account)
public
view
returns (uint256)
{
return investorInfo[account].volatilePoolLiquidity;
}
/**
* @dev Returns advisor data for an investor.
*/
function getAdvisors(address account)
public
view
returns (address[] memory)
{
return investorInfo[account].advisors;
}
/**
* @dev Add unique advisors to a list.
*/
function addAdvisor(address account, address advisor) internal {
Investor storage investor = investorInfo[account];
bool exists = false;
for (uint256 i = 0; i < investor.advisors.length; i++) {
if (advisors[i] == advisor) {
exists = true;
}
}
if (!exists) {
investor.advisors.push(advisor);
}
}
/**
Investor deposits liquidity to advisor pools
@param _stablecoin address of stablecoin.
@param _totalInvest amount of stable coin.
@param _advisor address of selected advisor.
*/
// function invest(
// address _stablecoin,
// uint256 _totalInvest,
// address _advisor
// )
// external
// payable
// // since we have now changed the logic with all usdc in stable and eth in volatile
// // uint256 _stableProportion,
// // uint256 _volatileProportion
// {
// Advisor storage advisor = advisorInfo[_advisor];
// IERC20 token = IERC20(_stablecoin);
// NewfiToken newfiStableToken = NewfiToken(advisor.stablePoolToken);
// NewfiToken newfiVolatileToken = NewfiToken(advisor.volatilePoolToken);
//
// // uint256 stableInvest = (_totalInvest.mul(_stableProportion)).div(100);
// // uint256 volatileInvest = (_totalInvest.mul(_volatileProportion)).div(
// // 100
// // );
// uint256 mintedStablePoolToken;
// if (_totalInvest > 0) {
// uint256 stablePoolTokenPrice;
// if (getStablePoolValue(_advisor) > 0) {
// // calculating P i.e price of the token
// stablePoolTokenPrice = getStablePoolValue(_advisor).div(
// newfiStableToken.totalSupply()
// );
// } else {
// stablePoolTokenPrice = 0;
// }
// // converting usdc to wei since pool token is of 18 decimals
// mintedStablePoolToken = _totalInvest.mul(10**12);
//
// newfiStableToken.mintOwnershipTokens(
// msg.sender,
// stablePoolTokenPrice,
// mintedStablePoolToken
// );
// token.safeTransferFrom(
// msg.sender,
// advisor.stablePool,
// _totalInvest
// );
// }
// if (msg.value > 0) {
// uint256 volatilePoolTokenPrice;
// if (getVolatilePoolValue(_advisor) > 0) {
// // calculating P i.e price of the token
// volatilePoolTokenPrice = getVolatilePoolValue(_advisor).div(
// newfiVolatileToken.totalSupply()
// );
// } else {
// volatilePoolTokenPrice = 0;
// }
//
// newfiVolatileToken.mintOwnershipTokens(
// msg.sender,
// volatilePoolTokenPrice,
// msg.value
// );
// (bool success, ) = advisor.volatilePool.call{value: msg.value}('');
// require(success, 'Transfer failed.');
// }
//
// Investor storage investor = investorInfo[msg.sender];
// if (investor.doesExist) {
// investor.stablePoolLiquidity = investor.stablePoolLiquidity.add(
// mintedStablePoolToken
// );
// investor.volatilePoolLiquidity = investor.volatilePoolLiquidity.add(
// msg.value
// );
// addAdvisor(msg.sender, _advisor);
//
// // not including the pool token balance calculation at the moment
// } else {
// investorInfo[msg.sender] = Investor(
// mintedStablePoolToken,
// msg.value,
// new address[](0),
// true
// );
// addAdvisor(msg.sender, _advisor);
// }
//
// emit Investment(msg.sender, mintedStablePoolToken, msg.value, _advisor);
// }
/**
Advisor Investing a particular investors pool liquidity
@param _stablecoin address of stablecoin to invest in mstable, will take usdc for hack.
// IMP NOTE => _mstableInvestmentAmount & _yearnInvestmentAmountsw will be based on the advisors mstable and yearn proportions
*/
// function protocolInvestment(address _stablecoin) external {
// Advisor storage advisor = advisorInfo[msg.sender];
// IERC20 token = IERC20(_stablecoin);
// uint256 stableProtocolInvestmentAmount = token.balanceOf(
// advisor.stablePool
// );
// // only investing stable coin in yearn and mstable eth will sit in the pool
// // uint256 volatileProtocolStableCoinInvestmentAmount = token.balanceOf(
// // advisor.volatilePool
// // );
// // eth bal
// // uint256 volatileProtocolVolatileCoinInvestmentAmount = advisor
// // .volatilePool
// // .balance;
// // calling the functions in proxy contract since amount is stored there so broken them into 2 different proxies
// if (stableProtocolInvestmentAmount > 0) {
// StablePoolProxy(advisor.stablePool).invest(
// massetAddress,
// _stablecoin,
// stableProtocolInvestmentAmount,
// savingContract,
// advisor.stableCoinMstableProportion,
// advisor.stableCoinYearnProportion
// );
// }
// // VolatilePoolProxy(advisor.volatilePool).investYearn(
// // volatileProtocolStableCoinInvestmentAmount
// // // volatileProtocolVolatileCoinInvestmentAmount
// // );
// // uint256 totalAmount = volatileProtocolStableCoinInvestmentAmount.add(
// // volatileProtocolVolatileCoinInvestmentAmount
// //);
// emit ProtocolInvestment(msg.sender, stableProtocolInvestmentAmount, 0);
// }
/**
Investor Unwinding their position
@param _advisor Address of the advisor.
@param _stablecoin address of stablecoin to invest in mstable, will take usdc for hack.
*/
// function unwind(address _advisor, address _stablecoin) external {
// Investor storage investor = investorInfo[msg.sender];
// Advisor storage advisor = advisorInfo[_advisor];
//
// uint256 advisorStablePoolFees = StablePoolProxy(advisor.stablePool)
// .redeemAmount(
// msg.sender,
// _advisor,
// massetAddress,
// savingContract,
// _stablecoin,
// investor.stablePoolLiquidity,
// advisor.stablePoolToken,
// advisor.stableCoinMstableProportion
// );
//
// uint256 advisorVolatilePoolFees = VolatilePoolProxy(
// advisor
// .volatilePool
// )
// .redeemAmount(
// msg.sender,
// _advisor,
// investor.volatilePoolLiquidity,
// advisor.volatilePoolToken
// );
// emit Unwind(
// _advisor,
// advisorStablePoolFees.add(advisorVolatilePoolFees)
// );
// }
}
|
Returns advisor data for an investor./
|
function getAdvisors(address account)
public
view
returns (address[] memory)
{
return investorInfo[account].advisors;
}
| 5,508,430 |
./partial_match/11155111/0x9B36F148D92494F144d8F70F60cCadC4b726194e/sources/nft/chainTransferAble/Tripster721ACreateFeeTransferChainSender.sol
|
string( abi.encodePacked( BASE_TOKEN_ENDPOINT, "/collections/", collectionId, "/token/" ) ),
|
function _newCollection(
string memory collectionId,
bytes32 whitelist,
uint256 public_price,
uint256 presale_price,
uint256 maxWhitelistSupply,
uint256 maxSupply,
uint256 startTokenId,
uint256 maxPerMint
) private {
require(startTokenId > 0, "Start TokenId is invalid");
require(maxPerMint > 0, "Max Per Mint is invalid");
currentCollectionIndex.increment();
IpfsCollections[currentCollectionIndex.current()] = IpfsCollection(
collectionId,
whitelist,
false,
false,
false,
BASE_TOKEN_ENDPOINT,
public_price,
presale_price,
startTokenId,
0,
maxWhitelistSupply,
maxSupply,
maxPerMint,
0,
0
);
}
| 3,534,159 |
pragma solidity 0.4.20;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title 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) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract LongevityToken is StandardToken {
string public name = "Longevity";
string public symbol = "LTY";
uint8 public decimals = 2;
uint256 public cap = 2**256 - 1; // maximum possible uint256. Decreased on finalization
bool public mintingFinished = false;
mapping (address => bool) owners;
mapping (address => bool) minters;
// tap to limit mint speed
struct Tap {
uint256 startTime; // reference time point to start measuring
uint256 tokensIssued; // how much tokens issued from startTime
uint256 mintSpeed; // token fractions per second
}
Tap public mintTap;
bool public capFinalized = false;
event Mint(address indexed to, uint256 amount);
event MintFinished();
event OwnerAdded(address indexed newOwner);
event OwnerRemoved(address indexed removedOwner);
event MinterAdded(address indexed newMinter);
event MinterRemoved(address indexed removedMinter);
event Burn(address indexed burner, uint256 value);
event MintTapSet(uint256 startTime, uint256 mintSpeed);
event SetCap(uint256 currectTotalSupply, uint256 cap);
function LongevityToken() public {
owners[msg.sender] = true;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) onlyMinter public returns (bool) {
require(!mintingFinished);
require(totalSupply.add(_amount) <= cap);
passThroughTap(_amount);
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
Transfer(address(0), _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner public returns (bool) {
require(!mintingFinished);
mintingFinished = true;
MintFinished();
return true;
}
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) public {
require(_value <= balances[msg.sender]);
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
totalSupply = totalSupply.sub(_value);
Burn(burner, _value);
}
/**
* @dev Adds administrative role to address
* @param _address The address that will get administrative privileges
*/
function addOwner(address _address) onlyOwner public {
owners[_address] = true;
OwnerAdded(_address);
}
/**
* @dev Removes administrative role from address
* @param _address The address to remove administrative privileges from
*/
function delOwner(address _address) onlyOwner public {
owners[_address] = false;
OwnerRemoved(_address);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owners[msg.sender]);
_;
}
/**
* @dev Adds minter role to address (able to create new tokens)
* @param _address The address that will get minter privileges
*/
function addMinter(address _address) onlyOwner public {
minters[_address] = true;
MinterAdded(_address);
}
/**
* @dev Removes minter role from address
* @param _address The address to remove minter privileges
*/
function delMinter(address _address) onlyOwner public {
minters[_address] = false;
MinterRemoved(_address);
}
/**
* @dev Throws if called by any account other than the minter.
*/
modifier onlyMinter() {
require(minters[msg.sender]);
_;
}
/**
* @dev passThroughTap allows minting tokens within the defined speed limit.
* Throws if requested more than allowed.
*/
function passThroughTap(uint256 _tokensRequested) internal {
require(_tokensRequested <= getTapRemaining());
mintTap.tokensIssued = mintTap.tokensIssued.add(_tokensRequested);
}
/**
* @dev Returns remaining amount of tokens allowed at the moment
*/
function getTapRemaining() public view returns (uint256) {
uint256 tapTime = now.sub(mintTap.startTime).add(1);
uint256 totalTokensAllowed = tapTime.mul(mintTap.mintSpeed);
uint256 tokensRemaining = totalTokensAllowed.sub(mintTap.tokensIssued);
return tokensRemaining;
}
/**
* @dev (Re)sets mint tap parameters
* @param _mintSpeed Allowed token amount to mint per second
*/
function setMintTap(uint256 _mintSpeed) onlyOwner public {
mintTap.startTime = now;
mintTap.tokensIssued = 0;
mintTap.mintSpeed = _mintSpeed;
MintTapSet(mintTap.startTime, mintTap.mintSpeed);
}
/**
* @dev sets token Cap (maximum possible totalSupply) on Crowdsale finalization
* Cap will be set to (sold tokens + team tokens) * 2
*/
function setCap() onlyOwner public {
require(!capFinalized);
require(cap == 2**256 - 1);
cap = totalSupply.mul(2);
capFinalized = true;
SetCap(totalSupply, cap);
}
}
/**
* @title LongevityCrowdsale
* @dev LongevityCrowdsale is a contract for managing a token crowdsale for Longevity project.
* Crowdsale have phases with start and end timestamps, where investors can make
* token purchases and the crowdsale will assign them tokens based
* on a token per ETH rate and bonuses. Collected funds are forwarded to a wallet
* as they arrive.
*/
contract LongevityCrowdsale {
using SafeMath for uint256;
// The token being sold
LongevityToken public token;
// Crowdsale administrators
mapping (address => bool) public owners;
// External bots updating rates
mapping (address => bool) public bots;
// Cashiers responsible for manual token issuance
mapping (address => bool) public cashiers;
// USD cents per ETH exchange rate
uint256 public rateUSDcETH;
// Phases list, see schedule in constructor
mapping (uint => Phase) phases;
// The total number of phases
uint public totalPhases = 0;
// Description for each phase
struct Phase {
uint256 startTime;
uint256 endTime;
uint256 bonusPercent;
}
// Minimum Deposit in USD cents
uint256 public constant minContributionUSDc = 1000;
bool public finalized = false;
// Amount of raised Ethers (in wei).
// And raised Dollars in cents
uint256 public weiRaised;
uint256 public USDcRaised;
// Wallets management
address[] public wallets;
mapping (address => bool) inList;
/**
* 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 bonusPercent free tokens percantage for the phase
* @param amount amount of tokens purchased
*/
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 bonusPercent, uint256 amount);
event OffChainTokenPurchase(address indexed beneficiary, uint256 tokensSold, uint256 USDcAmount);
// event for rate update logging
event RateUpdate(uint256 rate);
// event for wallet update
event WalletAdded(address indexed wallet);
event WalletRemoved(address indexed wallet);
// owners management events
event OwnerAdded(address indexed newOwner);
event OwnerRemoved(address indexed removedOwner);
// bot management events
event BotAdded(address indexed newBot);
event BotRemoved(address indexed removedBot);
// cashier management events
event CashierAdded(address indexed newBot);
event CashierRemoved(address indexed removedBot);
// Phase edit events
event TotalPhasesChanged(uint value);
event SetPhase(uint index, uint256 _startTime, uint256 _endTime, uint256 _bonusPercent);
event DelPhase(uint index);
function LongevityCrowdsale(address _tokenAddress, uint256 _initialRate) public {
require(_tokenAddress != address(0));
token = LongevityToken(_tokenAddress);
rateUSDcETH = _initialRate;
owners[msg.sender] = true;
bots[msg.sender] = true;
phases[0].bonusPercent = 40;
phases[0].startTime = 1520453700;
phases[0].endTime = 1520460000;
addWallet(msg.sender);
}
// fallback function can be used to buy tokens
function () external payable {
buyTokens(msg.sender);
}
// low level token purchase function
function buyTokens(address beneficiary) public payable {
require(beneficiary != address(0));
require(msg.value != 0);
require(isInPhase(now));
uint256 currentBonusPercent = getBonusPercent(now);
uint256 weiAmount = msg.value;
require(calculateUSDcValue(weiAmount) >= minContributionUSDc);
// calculate token amount to be created
uint256 tokens = calculateTokenAmount(weiAmount, currentBonusPercent);
weiRaised = weiRaised.add(weiAmount);
USDcRaised = USDcRaised.add(calculateUSDcValue(weiRaised));
token.mint(beneficiary, tokens);
TokenPurchase(msg.sender, beneficiary, weiAmount, currentBonusPercent, tokens);
forwardFunds();
}
// Sell any amount of tokens for cash or CryptoCurrency
function offChainPurchase(address beneficiary, uint256 tokensSold, uint256 USDcAmount) onlyCashier public {
require(beneficiary != address(0));
USDcRaised = USDcRaised.add(USDcAmount);
token.mint(beneficiary, tokensSold);
OffChainTokenPurchase(beneficiary, tokensSold, USDcAmount);
}
// If phase exists return corresponding bonus for the given date
// else return 0 (percent)
function getBonusPercent(uint256 datetime) public view returns (uint256) {
require(isInPhase(datetime));
for (uint i = 0; i < totalPhases; i++) {
if (datetime >= phases[i].startTime && datetime <= phases[i].endTime) {
return phases[i].bonusPercent;
}
}
}
// If phase exists for the given date return true
function isInPhase(uint256 datetime) public view returns (bool) {
for (uint i = 0; i < totalPhases; i++) {
if (datetime >= phases[i].startTime && datetime <= phases[i].endTime) {
return true;
}
}
}
// set rate
function setRate(uint256 _rateUSDcETH) public onlyBot {
// don't allow to change rate more than 10%
assert(_rateUSDcETH < rateUSDcETH.mul(110).div(100));
assert(_rateUSDcETH > rateUSDcETH.mul(90).div(100));
rateUSDcETH = _rateUSDcETH;
RateUpdate(rateUSDcETH);
}
/**
* @dev Adds administrative role to address
* @param _address The address that will get administrative privileges
*/
function addOwner(address _address) onlyOwner public {
owners[_address] = true;
OwnerAdded(_address);
}
/**
* @dev Removes administrative role from address
* @param _address The address to remove administrative privileges from
*/
function delOwner(address _address) onlyOwner public {
owners[_address] = false;
OwnerRemoved(_address);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owners[msg.sender]);
_;
}
/**
* @dev Adds rate updating bot
* @param _address The address of the rate bot
*/
function addBot(address _address) onlyOwner public {
bots[_address] = true;
BotAdded(_address);
}
/**
* @dev Removes rate updating bot address
* @param _address The address of the rate bot
*/
function delBot(address _address) onlyOwner public {
bots[_address] = false;
BotRemoved(_address);
}
/**
* @dev Throws if called by any account other than the bot.
*/
modifier onlyBot() {
require(bots[msg.sender]);
_;
}
/**
* @dev Adds cashier account responsible for manual token issuance
* @param _address The address of the Cashier
*/
function addCashier(address _address) onlyOwner public {
cashiers[_address] = true;
CashierAdded(_address);
}
/**
* @dev Removes cashier account responsible for manual token issuance
* @param _address The address of the Cashier
*/
function delCashier(address _address) onlyOwner public {
cashiers[_address] = false;
CashierRemoved(_address);
}
/**
* @dev Throws if called by any account other than Cashier.
*/
modifier onlyCashier() {
require(cashiers[msg.sender]);
_;
}
// calculate deposit value in USD Cents
function calculateUSDcValue(uint256 _weiDeposit) public view returns (uint256) {
// wei per USD cent
uint256 weiPerUSDc = 1 ether/rateUSDcETH;
// Deposited value converted to USD cents
uint256 depositValueInUSDc = _weiDeposit.div(weiPerUSDc);
return depositValueInUSDc;
}
// calculates how much tokens will beneficiary get
// for given amount of wei
function calculateTokenAmount(uint256 _weiDeposit, uint256 _bonusTokensPercent) public view returns (uint256) {
uint256 mainTokens = calculateUSDcValue(_weiDeposit);
uint256 bonusTokens = mainTokens.mul(_bonusTokensPercent).div(100);
return mainTokens.add(bonusTokens);
}
// send ether to the fund collection wallet
function forwardFunds() internal {
uint256 value = msg.value / wallets.length;
uint256 rest = msg.value - (value * wallets.length);
for (uint i = 0; i < wallets.length - 1; i++) {
wallets[i].transfer(value);
}
wallets[wallets.length - 1].transfer(value + rest);
}
// Add wallet address to wallets list
function addWallet(address _address) onlyOwner public {
require(!inList[_address]);
wallets.push(_address);
inList[_address] = true;
WalletAdded(_address);
}
//Change number of phases
function setTotalPhases(uint value) onlyOwner public {
totalPhases = value;
TotalPhasesChanged(value);
}
// Set phase: index and values
function setPhase(uint index, uint256 _startTime, uint256 _endTime, uint256 _bonusPercent) onlyOwner public {
require(index <= totalPhases);
phases[index] = Phase(_startTime, _endTime, _bonusPercent);
SetPhase(index, _startTime, _endTime, _bonusPercent);
}
// Delete phase
function delPhase(uint index) onlyOwner public {
require(index <= totalPhases);
delete phases[index];
DelPhase(index);
}
// Delete wallet from wallets list
function delWallet(uint index) onlyOwner public {
require(index < wallets.length);
address remove = wallets[index];
inList[remove] = false;
for (uint i = index; i < wallets.length-1; i++) {
wallets[i] = wallets[i+1];
}
wallets.length--;
WalletRemoved(remove);
}
// Return wallets array size
function getWalletsCount() public view returns (uint256) {
return wallets.length;
}
// finalizeCrowdsale issues tokens for the Team.
// Team gets 30/70 of harvested funds then token gets capped (upper emission boundary locked) to totalSupply * 2
// The token split after finalization will be in % of total token cap:
// 1. Tokens issued and distributed during pre-ICO and ICO = 35%
// 2. Tokens issued for the team on ICO finalization = 30%
// 3. Tokens for future in-app emission = 35%
function finalizeCrowdsale(address _teamAccount) onlyOwner public {
require(!finalized);
uint256 soldTokens = token.totalSupply();
uint256 teamTokens = soldTokens.div(70).mul(30);
token.mint(_teamAccount, teamTokens);
token.setCap();
finalized = true;
}
}
|
sets token Cap (maximum possible totalSupply) on Crowdsale finalization Cap will be set to (sold tokens + team tokens) 2/
|
function setCap() onlyOwner public {
require(!capFinalized);
require(cap == 2**256 - 1);
cap = totalSupply.mul(2);
capFinalized = true;
SetCap(totalSupply, cap);
}
| 6,768,377 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
import "@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol";
import "@openzeppelin/contracts/token/ERC1155/extensions/IERC1155MetadataURI.sol";
contract ERC1155ERC20 is ERC165, IERC20, IERC20Metadata, IERC1155, IERC1155MetadataURI {
string private _name;
string private _symbol;
string private _uri;
// ERC20-allowances
mapping(address => mapping(address => uint256)) private _allowances;
mapping(uint256 => mapping(address => uint256)) private _balances;
mapping(address => mapping(address => bool)) private _operatorApprovals;
mapping(uint256 => uint256) private _totalSupply;
constructor(
string memory name_,
string memory symbol_,
string memory uri_
) {
_name = name_;
_symbol = symbol_;
_uri = uri_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC1155).interfaceId ||
interfaceId == type(IERC1155MetadataURI).interfaceId ||
super.supportsInterface(interfaceId);
}
function name() external view returns (string memory) {
return _name;
}
function symbol() external view returns (string memory) {
return _symbol;
}
function decimals() external pure returns (uint8) {
return 18;
}
function granularity() external pure returns (uint256) {
return 1;
}
function uri(uint256 id) public view virtual returns (string memory) {
if (id == 0) {
return "";
}
return _uri;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() external view returns (uint256) {
return _totalSupply[0];
}
function totalSupply(uint256 id) public view returns (uint256) {
return _totalSupply[id];
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) external view returns (uint256) {
return _balances[0][account];
}
/**
* @dev See {IERC1155-balanceOf}.
*/
function balanceOf(address account, uint256 id) public view returns (uint256) {
return _balances[id][account];
}
/**
* @dev See {IERC1155-balanceOfBatch}.
*/
function balanceOfBatch(
address[] memory accounts,
uint256[] memory ids
) external view returns (uint256[] memory) {
require(accounts.length == ids.length, "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 {IERC20-transfer}.
*/
function transfer(
address recipient,
uint256 amount
) external returns (bool) {
require(recipient != address(0), "0 address");
_safeTransferFrom(msg.sender, recipient, 0, amount, "");
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*/
function transferFrom(
address holder,
address recipient,
uint256 amount
) external returns (bool) {
require(recipient != address(0), "0 address");
require(holder != address(0), "0 address");
if (msg.sender != holder) {
uint256 currentAllowance = _allowances[holder][msg.sender];
if (currentAllowance != type(uint256).max) {
require(currentAllowance >= amount, "exceeds allowance");
unchecked {
_approve(holder, msg.sender, currentAllowance - amount);
}
}
}
_safeTransferFrom(holder, recipient, 0, amount, "");
return true;
}
/**
* @dev See {IERC1155-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) external {
require(id > 0, "0 id");
require(
from == msg.sender || isApprovedForAll(from, msg.sender),
"not 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
) external {
require(
from == msg.sender || isApprovedForAll(from, msg.sender),
"not approved"
);
_safeBatchTransferFrom(from, to, ids, amounts, data);
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address holder, address spender) external view returns (uint256) {
return _allowances[holder][spender];
}
/**
* @dev See {IERC20-approve}.
*/
function approve(address spender, uint256 value) external returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
/**
* @dev See {IERC1155-isApprovedForAll}.
*/
function isApprovedForAll(address account, address operator) public view returns (bool) {
return _operatorApprovals[account][operator];
}
/**
* @dev See {IERC1155-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) external {
require(msg.sender != operator, "approval for self");
require(address(0) != operator, "approval for 0");
_operatorApprovals[msg.sender][operator] = approved;
emit ApprovalForAll(msg.sender, operator, approved);
}
function _approve(
address holder,
address spender,
uint256 value
) internal virtual {
require(holder != address(0), "0 address");
require(spender != address(0), "0 address");
_allowances[holder][spender] = value;
emit Approval(holder, spender, value);
}
function _safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(to != address(0), "0 address");
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "insufficient balance");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
if (id == 0) {
emit Transfer(from, to, amount);
return;
}
emit TransferSingle(msg.sender, from, to, id, amount);
_doSafeTransferAcceptanceCheck(msg.sender, from, to, id, amount, data);
}
function _safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(ids.length == amounts.length, "length mismatch");
require(to != address(0), "0 address");
for (uint256 i = 0; i < ids.length; ++i) {
uint256 id = ids[i];
require(id > 0, "0 id");
uint256 amount = amounts[i];
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "insufficient balance");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
}
emit TransferBatch(msg.sender, from, to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(msg.sender, from, to, ids, amounts, data);
}
function _setURI(string memory newuri) internal virtual {
_uri = newuri;
}
function _mint(
address to,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(to != address(0), "0 address");
_bareMint(to, id, amount);
if (id == 0) {
emit Transfer(address(0), to, amount);
return;
}
emit TransferSingle(msg.sender, address(0), to, id, amount);
_doSafeTransferAcceptanceCheck(msg.sender, address(0), to, id, amount, data);
}
function _bareMint(
address to,
uint256 id,
uint256 amount
) internal virtual {
_totalSupply[id] += amount;
_balances[id][to] += amount;
}
function _burn(
address from,
uint256 id,
uint256 amount
) internal virtual {
require(from != address(0), "0 address");
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "exceeds balance");
unchecked {
_totalSupply[id] -= amount;
_balances[id][from] = fromBalance - amount;
}
if (id == 0) {
emit Transfer(from, address(0), amount);
} else {
emit TransferSingle(msg.sender, from, address(0), id, amount);
}
}
function _doSafeTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) private {
if (isContract(to)) {
try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (
bytes4 response
) {
if (response != IERC1155Receiver.onERC1155Received.selector) {
revert("ERC1155Receiver rejected");
}
} catch {
revert("non ERC1155Receiver");
}
}
}
function _doSafeBatchTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) private {
if (isContract(to)) {
try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (
bytes4 response
) {
if (response != IERC1155Receiver.onERC1155BatchReceived.selector) {
revert("ERC1155Receiver rejected");
}
} catch {
revert("non ERC1155Receiver");
}
}
}
function isContract(address account) public 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;
}
}
|
This method relies on extcodesize, which returns 0 for contracts in construction, since the code is only stored at the end of the constructor execution.
|
function isContract(address account) public view returns (bool) {
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
| 5,400,391 |
./full_match/1/0x4AaADe11879f991ACD485E10d2D52a3587B304B7/sources/contracts/Global/AuthorityModel.sol
|
____________________________________________________________________________________________________________________ -->GETTER (function) isReviewAdmin check if an address is a review admin --------------------------------------------------------------------------------------------------------------------- return bool --------------------------------------------------------------------------------------------------------------------- _____________________________________________________________________________________________________________________/
|
function isReviewAdmin(address queryAddress_) public view returns (bool) {
return (_reviewAdmins.contains(queryAddress_));
}
| 8,477,089 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.2;
/// @title: David Ariew X Tatler China
import "../ERC721ProjectUpgradeable.sol";
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// '########:::::'###::::'##::::'##:'####:'########::::::::'###::::'########::'####:'########:'##:::::'##::::'##::::'##::::'########::::'###::::'########:'##:::::::'########:'########::::::'######::'##::::'##:'####:'##::: ##::::'###:::: //
// ##.... ##:::'## ##::: ##:::: ##:. ##:: ##.... ##::::::'## ##::: ##.... ##:. ##:: ##.....:: ##:'##: ##::::. ##::'##:::::... ##..::::'## ##:::... ##..:: ##::::::: ##.....:: ##.... ##::::'##... ##: ##:::: ##:. ##:: ###:: ##:::'## ##::: //
// ##:::: ##::'##:. ##:: ##:::: ##:: ##:: ##:::: ##:::::'##:. ##:: ##:::: ##:: ##:: ##::::::: ##: ##: ##:::::. ##'##::::::::: ##:::::'##:. ##::::: ##:::: ##::::::: ##::::::: ##:::: ##:::: ##:::..:: ##:::: ##:: ##:: ####: ##::'##:. ##:: //
// ##:::: ##:'##:::. ##: ##:::: ##:: ##:: ##:::: ##::::'##:::. ##: ########::: ##:: ######::: ##: ##: ##::::::. ###:::::::::: ##::::'##:::. ##:::: ##:::: ##::::::: ######::: ########::::: ##::::::: #########:: ##:: ## ## ##:'##:::. ##: //
// ##:::: ##: #########:. ##:: ##::: ##:: ##:::: ##:::: #########: ##.. ##:::: ##:: ##...:::: ##: ##: ##:::::: ## ##::::::::: ##:::: #########:::: ##:::: ##::::::: ##...:::: ##.. ##:::::: ##::::::: ##.... ##:: ##:: ##. ####: #########: //
// ##:::: ##: ##.... ##::. ## ##:::: ##:: ##:::: ##:::: ##.... ##: ##::. ##::: ##:: ##::::::: ##: ##: ##::::: ##:. ##:::::::: ##:::: ##.... ##:::: ##:::: ##::::::: ##::::::: ##::. ##::::: ##::: ##: ##:::: ##:: ##:: ##:. ###: ##.... ##: //
// ########:: ##:::: ##:::. ###::::'####: ########::::: ##:::: ##: ##:::. ##:'####: ########:. ###. ###::::: ##:::. ##::::::: ##:::: ##:::: ##:::: ##:::: ########: ########: ##:::. ##::::. ######:: ##:::: ##:'####: ##::. ##: ##:::: ##: //
// ........:::..:::::..:::::...:::::....::........::::::..:::::..::..:::::..::....::........:::...::...::::::..:::::..::::::::..:::::..:::::..:::::..:::::........::........::..:::::..::::::......:::..:::::..::....::..::::..::..:::::..:: //
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
contract DavidAriewXTatlerChina is ERC721ProjectUpgradeable {
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() initializer {}
function initialize() public initializer {
_initialize("David Ariew X Tatler China", "DavidAriewXTatlerChina");
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.2;
import "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import "./access/AdminControlUpgradeable.sol";
import "./core/ERC721ProjectCoreUpgradeable.sol";
/**
* @dev ERC721Project implementation
*/
abstract contract ERC721ProjectUpgradeable is
Initializable,
AdminControlUpgradeable,
ERC721Upgradeable,
ERC721ProjectCoreUpgradeable,
UUPSUpgradeable
{
function _initialize(string memory _name, string memory _symbol) internal initializer {
__AdminControl_init();
__ERC721_init(_name, _symbol);
__ERC721ProjectCore_init();
__UUPSUpgradeable_init();
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(AdminControlUpgradeable, ERC721Upgradeable, ERC721ProjectCoreUpgradeable)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
_approveTransfer(from, to, tokenId);
super._beforeTokenTransfer(from, to, tokenId);
}
/**
* @dev See {IProjectCore-registerManager}.
*/
function registerManager(address manager, string calldata baseURI)
external
override
adminRequired
nonBlacklistRequired(manager)
{
_registerManager(manager, baseURI, false);
}
/**
* @dev See {IProjectCore-registerManager}.
*/
function registerManager(
address manager,
string calldata baseURI,
bool baseURIIdentical
) external override adminRequired nonBlacklistRequired(manager) {
_registerManager(manager, baseURI, baseURIIdentical);
}
/**
* @dev See {IProjectCore-unregisterManager}.
*/
function unregisterManager(address manager) external override adminRequired {
_unregisterManager(manager);
}
/**
* @dev See {IProjectCore-blacklistManager}.
*/
function blacklistManager(address manager) external override adminRequired {
_blacklistManager(manager);
}
/**
* @dev See {IProjectCore-managerSetBaseTokenURI}.
*/
function managerSetBaseTokenURI(string calldata uri) external override managerRequired {
_managerSetBaseTokenURI(uri, false);
}
/**
* @dev See {IProjectCore-managerSetBaseTokenURI}.
*/
function managerSetBaseTokenURI(string calldata uri, bool identical) external override managerRequired {
_managerSetBaseTokenURI(uri, identical);
}
/**
* @dev See {IProjectCore-managerSetTokenURIPrefix}.
*/
function managerSetTokenURIPrefix(string calldata prefix) external override managerRequired {
_managerSetTokenURIPrefix(prefix);
}
/**
* @dev See {IProjectCore-managerSetTokenURI}.
*/
function managerSetTokenURI(uint256 tokenId, string calldata uri) external override managerRequired {
_managerSetTokenURI(tokenId, uri);
}
/**
* @dev See {IProjectCore-managerSetTokenURI}.
*/
function managerSetTokenURI(uint256[] calldata tokenIds, string[] calldata uris) external override managerRequired {
require(tokenIds.length == uris.length, "Invalid input");
for (uint256 i = 0; i < tokenIds.length; i++) {
_managerSetTokenURI(tokenIds[i], uris[i]);
}
}
/**
* @dev See {IProjectCore-setBaseTokenURI}.
*/
function setBaseTokenURI(string calldata uri) external override adminRequired {
_setBaseTokenURI(uri);
}
/**
* @dev See {IProjectCore-setTokenURIPrefix}.
*/
function setTokenURIPrefix(string calldata prefix) external override adminRequired {
_setTokenURIPrefix(prefix);
}
/**
* @dev See {IProjectCore-setTokenURI}.
*/
function setTokenURI(uint256 tokenId, string calldata uri) external override adminRequired {
_setTokenURI(tokenId, uri);
}
/**
* @dev See {IProjectCore-setTokenURI}.
*/
function setTokenURI(uint256[] calldata tokenIds, string[] calldata uris) external override adminRequired {
require(tokenIds.length == uris.length, "Invalid input");
for (uint256 i = 0; i < tokenIds.length; i++) {
_setTokenURI(tokenIds[i], uris[i]);
}
}
/**
* @dev See {IProjectCore-setMintPermissions}.
*/
function setMintPermissions(address manager, address permissions) external override adminRequired {
_setMintPermissions(manager, permissions);
}
/**
* @dev See {IERC721ProjectCore-adminMint}.
*/
function adminMint(address to, string calldata uri)
external
virtual
override
nonReentrant
adminRequired
returns (uint256)
{
return _adminMint(to, uri);
}
/**
* @dev See {IERC721ProjectCore-adminMintBatch}.
*/
function adminMintBatch(address to, uint16 count)
external
virtual
override
nonReentrant
adminRequired
returns (uint256[] memory tokenIds)
{
tokenIds = new uint256[](count);
for (uint16 i = 0; i < count; i++) {
tokenIds[i] = _adminMint(to, "");
}
return tokenIds;
}
/**
* @dev See {IERC721ProjectCore-adminMintBatch}.
*/
function adminMintBatch(address to, string[] calldata uris)
external
virtual
override
nonReentrant
adminRequired
returns (uint256[] memory tokenIds)
{
tokenIds = new uint256[](uris.length);
for (uint256 i = 0; i < uris.length; i++) {
tokenIds[i] = _adminMint(to, uris[i]);
}
return tokenIds;
}
/**
* @dev Mint token with no manager
*/
function _adminMint(address to, string memory uri) internal virtual returns (uint256 tokenId) {
_tokenCount++;
tokenId = _tokenCount;
// Track the manager that minted the token
_tokensManager[tokenId] = address(this);
_safeMint(to, tokenId);
if (bytes(uri).length > 0) {
_tokenURIs[tokenId] = uri;
}
// Call post mint
_postMintBase(to, tokenId);
return tokenId;
}
/**
* @dev See {IERC721ProjectCore-managerMint}.
*/
function managerMint(address to, string calldata uri)
external
virtual
override
nonReentrant
managerRequired
returns (uint256)
{
return _managerMint(to, uri);
}
/**
* @dev See {IERC721ProjectCore-managerMintBatch}.
*/
function managerMintBatch(address to, uint16 count)
external
virtual
override
nonReentrant
managerRequired
returns (uint256[] memory tokenIds)
{
tokenIds = new uint256[](count);
for (uint16 i = 0; i < count; i++) {
tokenIds[i] = _managerMint(to, "");
}
return tokenIds;
}
/**
* @dev See {IERC721ProjectCore-managerMintBatch}.
*/
function managerMintBatch(address to, string[] calldata uris)
external
virtual
override
nonReentrant
managerRequired
returns (uint256[] memory tokenIds)
{
tokenIds = new uint256[](uris.length);
for (uint256 i = 0; i < uris.length; i++) {
tokenIds[i] = _managerMint(to, uris[i]);
}
}
/**
* @dev Mint token via manager
*/
function _managerMint(address to, string memory uri) internal virtual returns (uint256 tokenId) {
_tokenCount++;
tokenId = _tokenCount;
_checkMintPermissions(to, tokenId);
// Track the manager that minted the token
_tokensManager[tokenId] = msg.sender;
_safeMint(to, tokenId);
if (bytes(uri).length > 0) {
_tokenURIs[tokenId] = uri;
}
// Call post mint
_postMintManager(to, tokenId);
return tokenId;
}
/**
* @dev See {IERC721ProjectCore-tokenManager}.
*/
function tokenManager(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "Nonexistent token");
return _tokenManager(tokenId);
}
/**
* @dev See {IERC721ProjectCore-burn}.
*/
function burn(uint256 tokenId) public virtual override nonReentrant {
require(_isApprovedOrOwner(msg.sender, tokenId), "Caller is not owner nor approved");
address owner = ownerOf(tokenId);
_burn(tokenId);
_postBurn(owner, tokenId);
}
/**
* @dev See {IProjectCore-setRoyalties}.
*/
function setRoyalties(address payable[] calldata receivers, uint256[] calldata basisPoints)
external
override
adminRequired
{
_setRoyaltiesManager(address(this), receivers, basisPoints);
}
/**
* @dev See {IProjectCore-setRoyalties}.
*/
function setRoyalties(
uint256 tokenId,
address payable[] calldata receivers,
uint256[] calldata basisPoints
) external override adminRequired {
require(_exists(tokenId), "Nonexistent token");
_setRoyalties(tokenId, receivers, basisPoints);
}
/**
* @dev See {IProjectCore-setRoyaltiesManager}.
*/
function setRoyaltiesManager(
address manager,
address payable[] calldata receivers,
uint256[] calldata basisPoints
) external override adminRequired {
_setRoyaltiesManager(manager, receivers, basisPoints);
}
/**
* @dev {See IProjectCore-getRoyalties}.
*/
function getRoyalties(uint256 tokenId)
external
view
virtual
override
returns (address payable[] memory, uint256[] memory)
{
require(_exists(tokenId), "Nonexistent token");
return _getRoyalties(tokenId);
}
/**
* @dev {See IProjectCore-getFees}.
*/
function getFees(uint256 tokenId)
external
view
virtual
override
returns (address payable[] memory, uint256[] memory)
{
require(_exists(tokenId), "Nonexistent token");
return _getRoyalties(tokenId);
}
/**
* @dev {See IProjectCore-getFeeRecipients}.
*/
function getFeeRecipients(uint256 tokenId) external view virtual override returns (address payable[] memory) {
require(_exists(tokenId), "Nonexistent token");
return _getRoyaltyReceivers(tokenId);
}
/**
* @dev {See IProjectCore-getFeeBps}.
*/
function getFeeBps(uint256 tokenId) external view virtual override returns (uint256[] memory) {
require(_exists(tokenId), "Nonexistent token");
return _getRoyaltyBPS(tokenId);
}
/**
* @dev {See IProjectCore-royaltyInfo}.
*/
function royaltyInfo(
uint256 tokenId,
uint256 value,
bytes calldata
)
external
view
virtual
override
returns (
address,
uint256,
bytes memory
)
{
require(_exists(tokenId), "Nonexistent token");
return _getRoyaltyInfo(tokenId, value);
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "Nonexistent token");
return _tokenURI(tokenId);
}
function _authorizeUpgrade(address newImplementation) internal override onlyOwner {}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721Upgradeable.sol";
import "./IERC721ReceiverUpgradeable.sol";
import "./extensions/IERC721MetadataUpgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../utils/StringsUpgradeable.sol";
import "../../utils/introspection/ERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable {
using AddressUpgradeable for address;
using StringsUpgradeable for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping (uint256 => address) private _owners;
// Mapping owner address to token count
mapping (address => uint256) private _balances;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
function __ERC721_init(string memory name_, string memory symbol_) internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721_init_unchained(name_, symbol_);
}
function __ERC721_init_unchained(string memory name_, string memory symbol_) internal initializer {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) {
return interfaceId == type(IERC721Upgradeable).interfaceId
|| interfaceId == type(IERC721MetadataUpgradeable).interfaceId
|| super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0
? string(abi.encodePacked(baseURI, tokenId.toString()))
: '';
}
/**
* @dev Base URI for computing {tokenURI}. Empty by default, can be overriden
* in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721Upgradeable.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(address from, address to, uint256 tokenId) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721Upgradeable.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual {
_mint(to, tokenId);
require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721Upgradeable.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(address from, address to, uint256 tokenId) internal virtual {
require(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
private returns (bool)
{
if (to.isContract()) {
try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721ReceiverUpgradeable(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
// solhint-disable-next-line no-inline-assembly
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { }
uint256[44] private __gap;
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC1967/ERC1967UpgradeUpgradeable.sol";
import "./Initializable.sol";
/**
* @dev Base contract for building openzeppelin-upgrades compatible implementations for the {ERC1967Proxy}. It includes
* publicly available upgrade functions that are called by the plugin and by the secure upgrade mechanism to verify
* continuation of the upgradability.
*
* The {_authorizeUpgrade} function MUST be overridden to include access restriction to the upgrade mechanism.
*
* _Available since v4.1._
*/
abstract contract UUPSUpgradeable is Initializable, ERC1967UpgradeUpgradeable {
function __UUPSUpgradeable_init() internal initializer {
__ERC1967Upgrade_init_unchained();
__UUPSUpgradeable_init_unchained();
}
function __UUPSUpgradeable_init_unchained() internal initializer {
}
function upgradeTo(address newImplementation) external virtual {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallSecure(newImplementation, bytes(""), false);
}
function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallSecure(newImplementation, data, true);
}
function _authorizeUpgrade(address newImplementation) internal virtual;
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.2;
import "@openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "./IAdminControlUpgradeable.sol";
abstract contract AdminControlUpgradeable is
Initializable,
OwnableUpgradeable,
IAdminControlUpgradeable,
ERC165Upgradeable
{
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
// Track registered admins
EnumerableSetUpgradeable.AddressSet private _admins;
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __AdminControl_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
__ERC165_init_unchained();
__AdminControl_init_unchained();
}
function __AdminControl_init_unchained() internal initializer {}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC165Upgradeable, IERC165Upgradeable)
returns (bool)
{
return interfaceId == type(IAdminControlUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Only allows approved admins to call the specified function
*/
modifier adminRequired() {
require(isAdmin(_msgSender()), "AdminControl: Must be owner or admin");
_;
}
/**
* @dev See {IAdminControl-getAdmins}.
*/
function getAdmins() external view override returns (address[] memory admins) {
admins = new address[](_admins.length());
for (uint256 i = 0; i < _admins.length(); i++) {
admins[i] = _admins.at(i);
}
return admins;
}
/**
* @dev See {IAdminControl-approveAdmin}.
*/
function approveAdmin(address admin) external override onlyOwner {
if (_admins.add(admin)) {
emit AdminApproved(admin, msg.sender);
}
}
/**
* @dev See {IAdminControl-revokeAdmin}.
*/
function revokeAdmin(address admin) external override onlyOwner {
if (_admins.remove(admin)) {
emit AdminRevoked(admin, msg.sender);
}
}
/**
* @dev See {IAdminControl-isAdmin}.
*/
function isAdmin(address admin) public view override returns (bool) {
return (owner() == admin || _admins.contains(admin));
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.2;
import "@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "../managers/ERC721/IERC721ProjectApproveTransferManager.sol";
import "../managers/ERC721/IERC721ProjectBurnableManager.sol";
import "../permissions/ERC721/IERC721ProjectMintPermissions.sol";
import "./IERC721ProjectCoreUpgradeable.sol";
import "./ProjectCoreUpgradeable.sol";
/**
* @dev Core ERC721 project implementation
*/
abstract contract ERC721ProjectCoreUpgradeable is Initializable, ProjectCoreUpgradeable, IERC721ProjectCoreUpgradeable {
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
/**
* @dev initializer
*/
function __ERC721ProjectCore_init() internal initializer {
__ProjectCore_init_unchained();
__ReentrancyGuard_init_unchained();
__ERC165_init_unchained();
__ERC721ProjectCore_init_unchained();
}
function __ERC721ProjectCore_init_unchained() internal initializer {}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ProjectCoreUpgradeable, IERC165Upgradeable)
returns (bool)
{
return interfaceId == type(IERC721ProjectCoreUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IProjectCore-managerSetApproveTransfer}.
*/
function managerSetApproveTransfer(bool enabled) external override managerRequired {
require(
!enabled ||
ERC165CheckerUpgradeable.supportsInterface(
msg.sender,
type(IERC721ProjectApproveTransferManager).interfaceId
),
"Manager must implement IERC721ProjectApproveTransferManager"
);
if (_managerApproveTransfers[msg.sender] != enabled) {
_managerApproveTransfers[msg.sender] = enabled;
emit ManagerApproveTransferUpdated(msg.sender, enabled);
}
}
/**
* @dev Set mint permissions for an manager
*/
function _setMintPermissions(address manager, address permissions) internal {
require(_managers.contains(manager), "ProjectCore: Invalid manager");
require(
permissions == address(0x0) ||
ERC165CheckerUpgradeable.supportsInterface(
permissions,
type(IERC721ProjectMintPermissions).interfaceId
),
"Invalid address"
);
if (_managerPermissions[manager] != permissions) {
_managerPermissions[manager] = permissions;
emit MintPermissionsUpdated(manager, permissions, msg.sender);
}
}
/**
* Check if an manager can mint
*/
function _checkMintPermissions(address to, uint256 tokenId) internal {
if (_managerPermissions[msg.sender] != address(0x0)) {
IERC721ProjectMintPermissions(_managerPermissions[msg.sender]).approveMint(msg.sender, to, tokenId);
}
}
/**
* Override for post mint actions
*/
function _postMintBase(address, uint256) internal virtual {}
/**
* Override for post mint actions
*/
function _postMintManager(address, uint256) internal virtual {}
/**
* Post-burning callback and metadata cleanup
*/
function _postBurn(address owner, uint256 tokenId) internal virtual {
// Callback to originating manager if needed
if (_tokensManager[tokenId] != address(this)) {
if (
ERC165CheckerUpgradeable.supportsInterface(
_tokensManager[tokenId],
type(IERC721ProjectBurnableManager).interfaceId
)
) {
IERC721ProjectBurnableManager(_tokensManager[tokenId]).onBurn(owner, tokenId);
}
}
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
// Delete token origin manager tracking
delete _tokensManager[tokenId];
}
/**
* Approve a transfer
*/
function _approveTransfer(
address from,
address to,
uint256 tokenId
) internal {
if (_managerApproveTransfers[_tokensManager[tokenId]]) {
require(
IERC721ProjectApproveTransferManager(_tokensManager[tokenId]).approveTransfer(from, to, tokenId),
"ERC721Project: Manager approval failure"
);
}
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165Upgradeable.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721Upgradeable is IERC165Upgradeable {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721ReceiverUpgradeable {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721Upgradeable.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721MetadataUpgradeable is IERC721Upgradeable {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
bytes16 private constant alphabet = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = alphabet[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal initializer {
__ERC165_init_unchained();
}
function __ERC165_init_unchained() internal initializer {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.2;
import "../beacon/IBeaconUpgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/StorageSlotUpgradeable.sol";
import "../utils/Initializable.sol";
/**
* @dev This abstract contract provides getters and event emitting update functions for
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
*
* _Available since v4.1._
*
* @custom:oz-upgrades-unsafe-allow delegatecall
*/
abstract contract ERC1967UpgradeUpgradeable is Initializable {
function __ERC1967Upgrade_init() internal initializer {
__ERC1967Upgrade_init_unchained();
}
function __ERC1967Upgrade_init_unchained() internal initializer {
}
// This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1
bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Returns the current implementation address.
*/
function _getImplementation() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
require(AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract");
StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
}
/**
* @dev Perform implementation upgrade
*
* Emits an {Upgraded} event.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Perform implementation upgrade with additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCall(address newImplementation, bytes memory data, bool forceCall) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
if (data.length > 0 || forceCall) {
_functionDelegateCall(newImplementation, data);
}
}
/**
* @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCallSecure(address newImplementation, bytes memory data, bool forceCall) internal {
address oldImplementation = _getImplementation();
// Initial upgrade and setup call
_setImplementation(newImplementation);
if (data.length > 0 || forceCall) {
_functionDelegateCall(newImplementation, data);
}
// Perform rollback test if not already in progress
StorageSlotUpgradeable.BooleanSlot storage rollbackTesting = StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT);
if (!rollbackTesting.value) {
// Trigger rollback using upgradeTo from the new implementation
rollbackTesting.value = true;
_functionDelegateCall(
newImplementation,
abi.encodeWithSignature(
"upgradeTo(address)",
oldImplementation
)
);
rollbackTesting.value = false;
// Check rollback was effective
require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades");
// Finally reset to the new implementation and log the upgrade
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
}
/**
* @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does
* not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).
*
* Emits a {BeaconUpgraded} event.
*/
function _upgradeBeaconToAndCall(address newBeacon, bytes memory data, bool forceCall) internal {
_setBeacon(newBeacon);
emit BeaconUpgraded(newBeacon);
if (data.length > 0 || forceCall) {
_functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data);
}
}
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Returns the current admin.
*/
function _getAdmin() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
require(newAdmin != address(0), "ERC1967: new admin is the zero address");
StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {AdminChanged} event.
*/
function _changeAdmin(address newAdmin) internal {
emit AdminChanged(_getAdmin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
* This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.
*/
bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/**
* @dev Emitted when the beacon is upgraded.
*/
event BeaconUpgraded(address indexed beacon);
/**
* @dev Returns the current beacon.
*/
function _getBeacon() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value;
}
/**
* @dev Stores a new beacon in the EIP1967 beacon slot.
*/
function _setBeacon(address newBeacon) private {
require(
AddressUpgradeable.isContract(newBeacon),
"ERC1967: new beacon is not a contract"
);
require(
AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()),
"ERC1967: beacon implementation is not a contract"
);
StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon;
}
/*
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function _functionDelegateCall(address target, bytes memory data) private returns (bytes memory) {
require(AddressUpgradeable.isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, "Address: low-level delegate call failed");
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev This is the interface that {BeaconProxy} expects of its beacon.
*/
interface IBeaconUpgradeable {
/**
* @dev Must return an address that can be used as a delegate call target.
*
* {BeaconProxy} will check that this address is a contract.
*/
function implementation() external view returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC1967 implementation slot:
* ```
* contract ERC1967 {
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._
*/
library StorageSlotUpgradeable {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
assembly {
r.slot := slot
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSetUpgradeable {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.2;
import "@openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol";
/**
* @dev Interface for admin control
*/
interface IAdminControlUpgradeable is IERC165Upgradeable {
event AdminApproved(address indexed account, address indexed sender);
event AdminRevoked(address indexed account, address indexed sender);
/**
* @dev gets address of all admins
*/
function getAdmins() external view returns (address[] memory);
/**
* @dev add an admin. Can only be called by contract owner.
*/
function approveAdmin(address admin) external;
/**
* @dev remove an admin. Can only be called by contract owner.
*/
function revokeAdmin(address admin) external;
/**
* @dev checks whether or not given address is an admin
* Returns True if they are
*/
function isAdmin(address admin) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.2;
import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
/**
* Implement this if you want your manager to approve a transfer
*/
interface IERC721ProjectApproveTransferManager is IERC165 {
/**
* @dev Set whether or not the project will check the manager for approval of token transfer
*/
function setApproveTransfer(address project, bool enabled) external;
/**
* @dev Called by project contract to approve a transfer
*/
function approveTransfer(
address from,
address to,
uint256 tokenId
) external returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.2;
import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
/**
* @dev Your manager is required to implement this interface if it wishes
* to receive the onBurn callback whenever a token the manager created is
* burned
*/
interface IERC721ProjectBurnableManager is IERC165 {
/**
* @dev callback handler for burn events
*/
function onBurn(address owner, uint256 tokenId) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.2;
import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721Project compliant manager contracts.
*/
interface IERC721ProjectMintPermissions is IERC165 {
/**
* @dev get approval to mint
*/
function approveMint(
address manager,
address to,
uint256 tokenId
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.2;
import "./IProjectCoreUpgradeable.sol";
/**
* @dev Core ERC721 project interface
*/
interface IERC721ProjectCoreUpgradeable is IProjectCoreUpgradeable {
/**
* @dev mint a token with no manager. Can only be called by an admin. set uri to empty string to use default uri.
* Returns tokenId minted
*/
function adminMint(address to, string calldata uri) external returns (uint256);
/**
* @dev batch mint a token with no manager. Can only be called by an admin.
* Returns tokenId minted
*/
function adminMintBatch(address to, uint16 count) external returns (uint256[] memory);
/**
* @dev batch mint a token with no manager. Can only be called by an admin.
* Returns tokenId minted
*/
function adminMintBatch(address to, string[] calldata uris) external returns (uint256[] memory);
/**
* @dev mint a token. Can only be called by a registered manager. set uri to "" to use default uri
* Returns tokenId minted
*/
function managerMint(address to, string calldata uri) external returns (uint256);
/**
* @dev batch mint a token. Can only be called by a registered manager.
* Returns tokenIds minted
*/
function managerMintBatch(address to, uint16 count) external returns (uint256[] memory);
/**
* @dev batch mint a token. Can only be called by a registered manager.
* Returns tokenId minted
*/
function managerMintBatch(address to, string[] calldata uris) external returns (uint256[] memory);
/**
* @dev burn a token. Can only be called by token owner or approved address.
* On burn, calls back to the registered manager's onBurn method
*/
function burn(uint256 tokenId) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.2;
import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/introspection/ERC165CheckerUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "../managers/ProjectTokenURIManager/IProjectTokenURIManager.sol";
import "./IProjectCoreUpgradeable.sol";
/**
* @dev Core project implementation
*/
abstract contract ProjectCoreUpgradeable is
Initializable,
IProjectCoreUpgradeable,
ReentrancyGuardUpgradeable,
ERC165Upgradeable
{
using StringsUpgradeable for uint256;
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
using AddressUpgradeable for address;
/**
* External interface identifiers for royalties
*/
/**
* @dev ProjectCore
*
* bytes4(keccak256('getRoyalties(uint256)')) == 0xbb3bafd6
*
* => 0xbb3bafd6 = 0xbb3bafd6
*/
bytes4 private constant _INTERFACE_ID_ROYALTIES_PROJECTCORE = 0xbb3bafd6;
/**
* @dev Rarible: RoyaltiesV1
*
* bytes4(keccak256('getFeeRecipients(uint256)')) == 0xb9c4d9fb
* bytes4(keccak256('getFeeBps(uint256)')) == 0x0ebd4c7f
*
* => 0xb9c4d9fb ^ 0x0ebd4c7f = 0xb7799584
*/
bytes4 private constant _INTERFACE_ID_ROYALTIES_RARIBLE = 0xb7799584;
/**
* @dev Foundation
*
* bytes4(keccak256('getFees(uint256)')) == 0xd5a06d4c
*
* => 0xd5a06d4c = 0xd5a06d4c
*/
bytes4 private constant _INTERFACE_ID_ROYALTIES_FOUNDATION = 0xd5a06d4c;
/**
* @dev EIP-2981
*
* bytes4(keccak256("royaltyInfo(uint256,uint256,bytes)")) == 0x6057361d
*
* => 0x6057361d = 0x6057361d
*/
bytes4 private constant _INTERFACE_ID_ROYALTIES_EIP2981 = 0x6057361d;
uint256 _tokenCount;
// Track registered managers data
EnumerableSetUpgradeable.AddressSet internal _managers;
EnumerableSetUpgradeable.AddressSet internal _blacklistedManagers;
mapping(address => address) internal _managerPermissions;
mapping(address => bool) internal _managerApproveTransfers;
// For tracking which manager a token was minted by
mapping(uint256 => address) internal _tokensManager;
// The baseURI for a given manager
mapping(address => string) private _managerBaseURI;
mapping(address => bool) private _managerBaseURIIdentical;
// The prefix for any tokens with a uri configured
mapping(address => string) private _managerURIPrefix;
// Mapping for individual token URIs
mapping(uint256 => string) internal _tokenURIs;
// Royalty configurations
mapping(address => address payable[]) internal _managerRoyaltyReceivers;
mapping(address => uint256[]) internal _managerRoyaltyBPS;
mapping(uint256 => address payable[]) internal _tokenRoyaltyReceivers;
mapping(uint256 => uint256[]) internal _tokenRoyaltyBPS;
/**
* @dev initializer
*/
function __ProjectCore_init() internal initializer {
__ReentrancyGuard_init_unchained();
__ERC165_init_unchained();
__ProjectCore_init_unchained();
_tokenCount = 0;
}
function __ProjectCore_init_unchained() internal initializer {}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC165Upgradeable, IERC165Upgradeable)
returns (bool)
{
return
interfaceId == type(IProjectCoreUpgradeable).interfaceId ||
super.supportsInterface(interfaceId) ||
interfaceId == _INTERFACE_ID_ROYALTIES_PROJECTCORE ||
interfaceId == _INTERFACE_ID_ROYALTIES_RARIBLE ||
interfaceId == _INTERFACE_ID_ROYALTIES_FOUNDATION ||
interfaceId == _INTERFACE_ID_ROYALTIES_EIP2981;
}
/**
* @dev Only allows registered managers to call the specified function
*/
modifier managerRequired() {
require(_managers.contains(msg.sender), "Must be registered manager");
_;
}
/**
* @dev Only allows non-blacklisted managers
*/
modifier nonBlacklistRequired(address manager) {
require(!_blacklistedManagers.contains(manager), "Manager blacklisted");
_;
}
/**
* @dev totalSupply
*/
function totalSupply() public view override returns (uint256) {
return _tokenCount;
}
/**
* @dev See {IProjectCore-getManagers}.
*/
function getManagers() external view override returns (address[] memory managers) {
managers = new address[](_managers.length());
for (uint256 i = 0; i < _managers.length(); i++) {
managers[i] = _managers.at(i);
}
return managers;
}
/**
* @dev Register an manager
*/
function _registerManager(
address manager,
string calldata baseURI,
bool baseURIIdentical
) internal {
require(manager != address(this), "Project: Invalid");
require(manager.isContract(), "Project: Manager must be a contract");
if (_managers.add(manager)) {
_managerBaseURI[manager] = baseURI;
_managerBaseURIIdentical[manager] = baseURIIdentical;
emit ManagerRegistered(manager, msg.sender);
}
}
/**
* @dev Unregister an manager
*/
function _unregisterManager(address manager) internal {
if (_managers.remove(manager)) {
emit ManagerUnregistered(manager, msg.sender);
}
}
/**
* @dev Blacklist an manager
*/
function _blacklistManager(address manager) internal {
require(manager != address(this), "Cannot blacklist yourself");
if (_managers.remove(manager)) {
emit ManagerUnregistered(manager, msg.sender);
}
if (_blacklistedManagers.add(manager)) {
emit ManagerBlacklisted(manager, msg.sender);
}
}
/**
* @dev Set base token uri for an manager
*/
function _managerSetBaseTokenURI(string calldata uri, bool identical) internal {
_managerBaseURI[msg.sender] = uri;
_managerBaseURIIdentical[msg.sender] = identical;
}
/**
* @dev Set token uri prefix for an manager
*/
function _managerSetTokenURIPrefix(string calldata prefix) internal {
_managerURIPrefix[msg.sender] = prefix;
}
/**
* @dev Set token uri for a token of an manager
*/
function _managerSetTokenURI(uint256 tokenId, string calldata uri) internal {
require(_tokensManager[tokenId] == msg.sender, "Invalid token");
_tokenURIs[tokenId] = uri;
}
/**
* @dev Set base token uri for tokens with no manager
*/
function _setBaseTokenURI(string memory uri) internal {
_managerBaseURI[address(this)] = uri;
}
/**
* @dev Set token uri prefix for tokens with no manager
*/
function _setTokenURIPrefix(string calldata prefix) internal {
_managerURIPrefix[address(this)] = prefix;
}
/**
* @dev Set token uri for a token with no manager
*/
function _setTokenURI(uint256 tokenId, string calldata uri) internal {
require(_tokensManager[tokenId] == address(this), "Invalid token");
_tokenURIs[tokenId] = uri;
}
/**
* @dev Retrieve a token's URI
*/
function _tokenURI(uint256 tokenId) internal view returns (string memory) {
address manager = _tokensManager[tokenId];
require(!_blacklistedManagers.contains(manager), "Manager blacklisted");
// 1. if tokenURI is stored in this contract, use it with managerURIPrefix if any
if (bytes(_tokenURIs[tokenId]).length != 0) {
if (bytes(_managerURIPrefix[manager]).length != 0) {
return string(abi.encodePacked(_managerURIPrefix[manager], _tokenURIs[tokenId]));
}
return _tokenURIs[tokenId];
}
// 2. if URI is controlled by manager, retrieve it from manager
if (ERC165CheckerUpgradeable.supportsInterface(manager, type(IProjectTokenURIManager).interfaceId)) {
return IProjectTokenURIManager(manager).tokenURI(address(this), tokenId);
}
// 3. use managerBaseURI with id or not
if (!_managerBaseURIIdentical[manager]) {
return string(abi.encodePacked(_managerBaseURI[manager], tokenId.toString()));
} else {
return _managerBaseURI[manager];
}
}
/**
* Get token manager
*/
function _tokenManager(uint256 tokenId) internal view returns (address manager) {
manager = _tokensManager[tokenId];
require(manager != address(this), "No manager for token");
require(!_blacklistedManagers.contains(manager), "Manager blacklisted");
return manager;
}
/**
* Helper to get royalties for a token
*/
function _getRoyalties(uint256 tokenId) internal view returns (address payable[] storage, uint256[] storage) {
return (_getRoyaltyReceivers(tokenId), _getRoyaltyBPS(tokenId));
}
/**
* Helper to get royalty receivers for a token
*/
function _getRoyaltyReceivers(uint256 tokenId) internal view returns (address payable[] storage) {
if (_tokenRoyaltyReceivers[tokenId].length > 0) {
return _tokenRoyaltyReceivers[tokenId];
} else if (_managerRoyaltyReceivers[_tokensManager[tokenId]].length > 0) {
return _managerRoyaltyReceivers[_tokensManager[tokenId]];
}
return _managerRoyaltyReceivers[address(this)];
}
/**
* Helper to get royalty basis points for a token
*/
function _getRoyaltyBPS(uint256 tokenId) internal view returns (uint256[] storage) {
if (_tokenRoyaltyBPS[tokenId].length > 0) {
return _tokenRoyaltyBPS[tokenId];
} else if (_managerRoyaltyBPS[_tokensManager[tokenId]].length > 0) {
return _managerRoyaltyBPS[_tokensManager[tokenId]];
}
return _managerRoyaltyBPS[address(this)];
}
function _getRoyaltyInfo(uint256 tokenId, uint256 value)
internal
view
returns (
address receiver,
uint256 amount,
bytes memory data
)
{
address payable[] storage receivers = _getRoyaltyReceivers(tokenId);
require(receivers.length <= 1, "More than 1 royalty receiver");
if (receivers.length == 0) {
return (address(this), 0, data);
}
return (receivers[0], (_getRoyaltyBPS(tokenId)[0] * value) / 10000, data);
}
/**
* Set royalties for a token
*/
function _setRoyalties(
uint256 tokenId,
address payable[] calldata receivers,
uint256[] calldata basisPoints
) internal {
require(receivers.length == basisPoints.length, "Invalid input");
uint256 totalBasisPoints;
for (uint256 i = 0; i < basisPoints.length; i++) {
totalBasisPoints += basisPoints[i];
}
require(totalBasisPoints < 10000, "Invalid total royalties");
_tokenRoyaltyReceivers[tokenId] = receivers;
_tokenRoyaltyBPS[tokenId] = basisPoints;
emit RoyaltiesUpdated(tokenId, receivers, basisPoints);
}
/**
* Set royalties for all tokens of an manager
*/
function _setRoyaltiesManager(
address manager,
address payable[] calldata receivers,
uint256[] calldata basisPoints
) internal {
require(receivers.length == basisPoints.length, "Invalid input");
uint256 totalBasisPoints;
for (uint256 i = 0; i < basisPoints.length; i++) {
totalBasisPoints += basisPoints[i];
}
require(totalBasisPoints < 10000, "Invalid total royalties");
_managerRoyaltyReceivers[manager] = receivers;
_managerRoyaltyBPS[manager] = basisPoints;
if (manager == address(this)) {
emit DefaultRoyaltiesUpdated(receivers, basisPoints);
} else {
emit ManagerRoyaltiesUpdated(manager, receivers, basisPoints);
}
}
uint256[36] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface 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.2;
import "@openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol";
/**
* @dev Core project interface
*/
interface IProjectCoreUpgradeable is IERC165Upgradeable {
event ManagerRegistered(address indexed manager, address indexed sender);
event ManagerUnregistered(address indexed manager, address indexed sender);
event ManagerBlacklisted(address indexed manager, address indexed sender);
event MintPermissionsUpdated(address indexed manager, address indexed permissions, address indexed sender);
event RoyaltiesUpdated(uint256 indexed tokenId, address payable[] receivers, uint256[] basisPoints);
event DefaultRoyaltiesUpdated(address payable[] receivers, uint256[] basisPoints);
event ManagerRoyaltiesUpdated(address indexed manager, address payable[] receivers, uint256[] basisPoints);
event ManagerApproveTransferUpdated(address indexed manager, bool enabled);
/**
* @dev totalSupply
*/
function totalSupply() external view returns (uint256);
/**
* @dev gets address of all managers
*/
function getManagers() external view returns (address[] memory);
/**
* @dev add an manager. Can only be called by contract owner or admin.
* manager address must point to a contract implementing IProjectManager.
* Returns True if newly added, False if already added.
*/
function registerManager(address manager, string calldata baseURI) external;
/**
* @dev add an manager. Can only be called by contract owner or admin.
* manager address must point to a contract implementing IProjectManager.
* Returns True if newly added, False if already added.
*/
function registerManager(
address manager,
string calldata baseURI,
bool baseURIIdentical
) external;
/**
* @dev add an manager. Can only be called by contract owner or admin.
* Returns True if removed, False if already removed.
*/
function unregisterManager(address manager) external;
/**
* @dev blacklist an manager. Can only be called by contract owner or admin.
* This function will destroy all ability to reference the metadata of any tokens created
* by the specified manager. It will also unregister the manager if needed.
* Returns True if removed, False if already removed.
*/
function blacklistManager(address manager) external;
/**
* @dev set the baseTokenURI of an manager. Can only be called by manager.
*/
function managerSetBaseTokenURI(string calldata uri) external;
/**
* @dev set the baseTokenURI of an manager. Can only be called by manager.
* For tokens with no uri configured, tokenURI will return "uri+tokenId"
*/
function managerSetBaseTokenURI(string calldata uri, bool identical) external;
/**
* @dev set the common prefix of an manager. Can only be called by manager.
* If configured, and a token has a uri set, tokenURI will return "prefixURI+tokenURI"
* Useful if you want to use ipfs/arweave
*/
function managerSetTokenURIPrefix(string calldata prefix) external;
/**
* @dev set the tokenURI of a token manager. Can only be called by manager that minted token.
*/
function managerSetTokenURI(uint256 tokenId, string calldata uri) external;
/**
* @dev set the tokenURI of a token manager for multiple tokens. Can only be called by manager that minted token.
*/
function managerSetTokenURI(uint256[] calldata tokenId, string[] calldata uri) external;
/**
* @dev set the baseTokenURI for tokens with no manager. Can only be called by owner/admin.
* For tokens with no uri configured, tokenURI will return "uri+tokenId"
*/
function setBaseTokenURI(string calldata uri) external;
/**
* @dev set the common prefix for tokens with no manager. Can only be called by owner/admin.
* If configured, and a token has a uri set, tokenURI will return "prefixURI+tokenURI"
* Useful if you want to use ipfs/arweave
*/
function setTokenURIPrefix(string calldata prefix) external;
/**
* @dev set the tokenURI of a token with no manager. Can only be called by owner/admin.
*/
function setTokenURI(uint256 tokenId, string calldata uri) external;
/**
* @dev set the tokenURI of multiple tokens with no manager. Can only be called by owner/admin.
*/
function setTokenURI(uint256[] calldata tokenIds, string[] calldata uris) external;
/**
* @dev set a permissions contract for an manager. Used to control minting.
*/
function setMintPermissions(address manager, address permissions) external;
/**
* @dev Configure so transfers of tokens created by the caller (must be manager) gets approval
* from the manager before transferring
*/
function managerSetApproveTransfer(bool enabled) external;
/**
* @dev get the manager of a given token
*/
function tokenManager(uint256 tokenId) external view returns (address);
/**
* @dev Set default royalties
*/
function setRoyalties(address payable[] calldata receivers, uint256[] calldata basisPoints) external;
/**
* @dev Set royalties of a token
*/
function setRoyalties(
uint256 tokenId,
address payable[] calldata receivers,
uint256[] calldata basisPoints
) external;
/**
* @dev Set royalties of an manager
*/
function setRoyaltiesManager(
address manager,
address payable[] calldata receivers,
uint256[] calldata basisPoints
) external;
/**
* @dev Get royalites of a token. Returns list of receivers and basisPoints
*/
function getRoyalties(uint256 tokenId) external view returns (address payable[] memory, uint256[] memory);
// Royalty support for various other standards
function getFeeRecipients(uint256 tokenId) external view returns (address payable[] memory);
function getFeeBps(uint256 tokenId) external view returns (uint256[] memory);
function getFees(uint256 tokenId) external view returns (address payable[] memory, uint256[] memory);
function royaltyInfo(
uint256 tokenId,
uint256 value,
bytes calldata data
)
external
view
returns (
address,
uint256,
bytes memory
);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
function __ReentrancyGuard_init() internal initializer {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal initializer {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165Upgradeable.sol";
/**
* @dev Library used to query support of an interface declared via {IERC165}.
*
* Note that these functions return the actual result of the query: they do not
* `revert` if an interface is not supported. It is up to the caller to decide
* what to do in these cases.
*/
library ERC165CheckerUpgradeable {
// As per the EIP-165 spec, no interface should ever match 0xffffffff
bytes4 private constant _INTERFACE_ID_INVALID = 0xffffffff;
/**
* @dev Returns true if `account` supports the {IERC165} interface,
*/
function supportsERC165(address account) internal view returns (bool) {
// Any contract that implements ERC165 must explicitly indicate support of
// InterfaceId_ERC165 and explicitly indicate non-support of InterfaceId_Invalid
return _supportsERC165Interface(account, type(IERC165Upgradeable).interfaceId) &&
!_supportsERC165Interface(account, _INTERFACE_ID_INVALID);
}
/**
* @dev Returns true if `account` supports the interface defined by
* `interfaceId`. Support for {IERC165} itself is queried automatically.
*
* See {IERC165-supportsInterface}.
*/
function supportsInterface(address account, bytes4 interfaceId) internal view returns (bool) {
// query support of both ERC165 as per the spec and support of _interfaceId
return supportsERC165(account) &&
_supportsERC165Interface(account, interfaceId);
}
/**
* @dev Returns a boolean array where each value corresponds to the
* interfaces passed in and whether they're supported or not. This allows
* you to batch check interfaces for a contract where your expectation
* is that some interfaces may not be supported.
*
* See {IERC165-supportsInterface}.
*
* _Available since v3.4._
*/
function getSupportedInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool[] memory) {
// an array of booleans corresponding to interfaceIds and whether they're supported or not
bool[] memory interfaceIdsSupported = new bool[](interfaceIds.length);
// query support of ERC165 itself
if (supportsERC165(account)) {
// query support of each interface in interfaceIds
for (uint256 i = 0; i < interfaceIds.length; i++) {
interfaceIdsSupported[i] = _supportsERC165Interface(account, interfaceIds[i]);
}
}
return interfaceIdsSupported;
}
/**
* @dev Returns true if `account` supports all the interfaces defined in
* `interfaceIds`. Support for {IERC165} itself is queried automatically.
*
* Batch-querying can lead to gas savings by skipping repeated checks for
* {IERC165} support.
*
* See {IERC165-supportsInterface}.
*/
function supportsAllInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool) {
// query support of ERC165 itself
if (!supportsERC165(account)) {
return false;
}
// query support of each interface in _interfaceIds
for (uint256 i = 0; i < interfaceIds.length; i++) {
if (!_supportsERC165Interface(account, interfaceIds[i])) {
return false;
}
}
// all interfaces supported
return true;
}
/**
* @notice Query if a contract implements an interface, does not check ERC165 support
* @param account The address of the contract to query for support of an interface
* @param interfaceId The interface identifier, as specified in ERC-165
* @return true if the contract at account indicates support of the interface with
* identifier interfaceId, false otherwise
* @dev Assumes that account contains a contract that supports ERC165, otherwise
* the behavior of this method is undefined. This precondition can be checked
* with {supportsERC165}.
* Interface identification is specified in ERC-165.
*/
function _supportsERC165Interface(address account, bytes4 interfaceId) private view returns (bool) {
bytes memory encodedParams = abi.encodeWithSelector(IERC165Upgradeable(account).supportsInterface.selector, interfaceId);
(bool success, bytes memory result) = account.staticcall{ gas: 30000 }(encodedParams);
if (result.length < 32) return false;
return success && abi.decode(result, (bool));
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.2;
import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
/**
* @dev Implement this if you want your manager to have overloadable URI's
*/
interface IProjectTokenURIManager is IERC165 {
/**
* Get the uri for a given project/tokenId
*/
function tokenURI(address project, uint256 tokenId) external view returns (string memory);
}
|
See {IAdminControl-isAdmin}./
|
function isAdmin(address admin) public view override returns (bool) {
return (owner() == admin || _admins.contains(admin));
}
uint256[49] private __gap;
| 12,006,297 |
./full_match/1/0xEc7047602c10D95adCc4f62539529A26327eD0BD/sources/contracts/ConvexExecutor/Susd/ConvexSUSDPoolTradeExecutor.sol
|
Functionlity to execute after deposit is completed This is not required in ConvexTradeExecutor, hence empty. This follows the BaseTradeExecutor interface
|
function _confirmDeposit() internal override {}
| 4,966,600 |
./full_match/1/0xe261B138cfd46FdC12A039cF6690645f35DCFA37/sources/contracts/DropFactory/DropFactory.sol
|
____________________________________________________________________________________________________________________ -->FINANCE (function) setDropFee Set drop fee (if any) --------------------------------------------------------------------------------------------------------------------- fee_ New drop fee --------------------------------------------------------------------------------------------------------------------- _____________________________________________________________________________________________________________________/
|
function setDropFee(uint256 fee_) external onlyPlatformAdmin {
uint256 oldDropFee = dropFee;
dropFee = uint96(fee_);
emit SubmissionFeeUpdated(oldDropFee, fee_);
}
| 3,107,439 |
/*
Implementation of contract Sudoku
*/
pragma ton-solidity >=0.30.0;
contract ZKSudoku {
// Error codes
uint8 constant MUST_BE_OWNER = 100;
uint8 constant WRONG_SIZE = 101;
uint8 constant SUDOKU_FORBIDDEN_VALUE = 102;
// Sudoku parameters to keep generality when switching to 9x9 or
// larger
uint8 constant SUDOKU_SIZE = 4;
uint8 constant NUM_SQUARES = SUDOKU_SIZE * SUDOKU_SIZE;
uint8 constant PROOF_SIZE = 192;
// Size of Primary input
uint32 constant PI_SIZE = NUM_SQUARES;
uint8 constant field_element_bytes = 32;
uint256 m_owner; // address of the owner manually sending new
// instances
bytes v_key; // the verification key
// bytes g_zip_provkey; // the proving key, compressed with
// gzip This was not included in the end because the proving
// key is 64 kbytes.
uint8[][3] m_instance; //the array of fixed instances
/// @dev getter of the current state of the contract
function get() public view returns
(
uint8 num_squares,
uint8[][3] current_instance,
bytes verifkey
)
{
num_squares = NUM_SQUARES;
current_instance = m_instance;
verifkey = v_key;
}
/// @dev checks that a fixed value is legal
/// (between 0 and SUDOKU_SIZE)
/// @param i: row index of checked value
/// @param j: column index of checked value
/// @param value: actual checked value
function check_value(uint8 i,uint8 j,uint8 value)
private pure returns (bool) {
if(i < SUDOKU_SIZE &&
j < SUDOKU_SIZE){
if(value <= SUDOKU_SIZE)
return true;
else
require(false, SUDOKU_FORBIDDEN_VALUE);}
else
require(false, WRONG_SIZE);}
/// @dev submits a new instance (i.e. Sudoku problem) and replaces
/// m_instance with it. Only called by the owner.
/// @param instance: the Sudoku problem encoded as an array [
/// [i,j,value] ] for every square i,j which is fixed by the
/// submitter
function submit_instance(uint8[][3] instance) public returns (bool res) {
require(msg.pubkey() == m_owner, MUST_BE_OWNER);
tvm.accept();
delete m_instance;
for(uint i=0;i<instance.length;i++){
if(check_value(instance[i][0],instance[i][1],instance[i][2]))
m_instance.push(instance[i]);
else
require(false,SUDOKU_FORBIDDEN_VALUE);
}
res = true;
}
/// @dev constructor: Takes a verification key and an instance
/// (i.e. Sudoku problem)
/// @param v_key_in: the verification key corresponding to the
/// circuit
/// @param instance: the Sudoku problem encoded as an array [
/// [i,j,value] ] for every square i,j which is fixed by the
/// submitter
constructor(bytes v_key_in, uint8[][3] instance) public {
tvm.accept();
m_owner = msg.pubkey();
v_key = v_key_in;
for(uint8 i=0;i<instance.length;i++){
require(check_value(instance[i][0],instance[i][1],instance[i][2]));
m_instance.push(instance[i]);
}
}
/// @dev computes the primary input with the right encoding for the
/// vergrth16 instruction from m_instance
/// @param instance: the Sudoku problem encoded as an array [
/// [i,j,value] ] for every square i,j which is fixed by the
/// problem
function pi_from_instance(uint8[][3] instance)
public pure returns (bytes) {
uint8[] temp;
// initialize all values to zero
for(uint i=0;i<NUM_SQUARES;i++){
temp.push(0);
}
// input the fixed values from instance
for(uint k=0;k<instance.length;k++){
uint8 i=instance[k][0];
uint8 j=instance[k][1];
uint8 value=instance[k][2];
require(check_value(i,j,value));
temp[i * SUDOKU_SIZE + j] = value;
}
string blob_str=(encode_little_endian(PI_SIZE,4));
// build the actual encoded primary input
for(uint i=0;i<NUM_SQUARES;i++){
blob_str.append(serialize_primary_input(temp[i]));
}
return blob_str;
}
/// @dev submits the actual proof to be checked for the current
/// instance and solution
/// @param proof: The zero-knowledge proof for the current
/// instance and solution
function submit(bytes proof)
public view returns (bool res, string blob_str) {
require(proof.length == PROOF_SIZE);
tvm.accept();
blob_str = proof;
blob_str.append(pi_from_instance(m_instance));
blob_str.append(v_key);
if(tvm.vergrth16(blob_str)){
res = true;
}
else{
res = false;
}
}
/// @dev serializes the primary input of the circuit into the
/// format expected by the vergrth16 instruction. Code from Noam
/// Y.
/// @param some_number: the number to be encoded.
function serialize_primary_input(uint32 some_number) pure internal inline returns(bytes) {
string blob_str = encode_little_endian(uint256(some_number), field_element_bytes);
return blob_str;
}
/// @dev encodes a number into little endian format on a given
/// number of bytes
/// @param number: the number to be encoded
/// @param bytes_size: the number of bytes on which to encode the
/// number
function encode_little_endian(uint256 number, uint32 bytes_size) internal pure returns (bytes){
TvmBuilder ref_builder;
for(uint32 i=0; i<bytes_size; ++i) {
ref_builder.store(byte(uint8(number & 0xFF)));
number>>=8;
}
TvmBuilder builder;
builder.storeRef(ref_builder.toCell());
return builder.toSlice().decode(bytes);
}
}
|
computes the primary input with the right encoding for the vergrth16 instruction from m_instance instance: the Sudoku problem encoded as an array [ [i,j,value] ] for every square i,j which is fixed by the problem initialize all values to zero input the fixed values from instance build the actual encoded primary input
|
function pi_from_instance(uint8[][3] instance)
public pure returns (bytes) {
uint8[] temp;
for(uint i=0;i<NUM_SQUARES;i++){
temp.push(0);
}
for(uint k=0;k<instance.length;k++){
uint8 i=instance[k][0];
uint8 j=instance[k][1];
uint8 value=instance[k][2];
require(check_value(i,j,value));
temp[i * SUDOKU_SIZE + j] = value;
}
string blob_str=(encode_little_endian(PI_SIZE,4));
for(uint i=0;i<NUM_SQUARES;i++){
blob_str.append(serialize_primary_input(temp[i]));
}
return blob_str;
}
| 6,346,330 |
./full_match/5/0x871d72C888B7d92686E01e48F6F06FFB11EEe9B5/sources/browser/contracts/Pool.sol
|
Withdraw LP tokens from MasterChef.
|
function withdraw(uint256 _pid, uint256 _amount) public whenNotPausedWithdraw{
require(!isTamagPool(_pid), "not erc20 pool");
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_msgSender()];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accTmcPerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
safeTmcTransfer(_msgSender(), pending);
}
if(_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.lpToken.safeTransfer(_msgSender(), _amount);
}
user.rewardDebt = user.amount.mul(pool.accTmcPerShare).div(1e12);
emit Withdraw(_msgSender(), _pid, _amount);
}
| 1,897,221 |
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12;
interface IERC20 {
function TOTALSUPPLY622() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF753(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER955(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE76(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE213(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM690(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER649(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL691(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function SAFETRANSFER876(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING
_CALLOPTIONALRETURN191(token, abi.encodeWithSelector(token.TRANSFER955.selector, to, value));
}
function SAFETRANSFERFROM621(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING
_CALLOPTIONALRETURN191(token, abi.encodeWithSelector(token.TRANSFERFROM690.selector, from, to, value));
}
function SAFEAPPROVE2(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.ALLOWANCE76(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_CALLOPTIONALRETURN191(token, abi.encodeWithSelector(token.APPROVE213.selector, spender, value));
}
function SAFEINCREASEALLOWANCE52(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE76(address(this), spender).ADD393(value);
_CALLOPTIONALRETURN191(token, abi.encodeWithSelector(token.APPROVE213.selector, spender, newAllowance));
}
function SAFEDECREASEALLOWANCE172(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE76(address(this), spender).SUB829(value, "SafeERC20: decreased allowance below zero");
_CALLOPTIONALRETURN191(token, abi.encodeWithSelector(token.APPROVE213.selector, spender, newAllowance));
}
function _CALLOPTIONALRETURN191(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. 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).FUNCTIONCALL585(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");
}
}
}
interface IWETH {
function DEPOSIT379() external payable; //inject NONSTANDARD NAMING
function TRANSFER955(address to, uint value) external returns (bool); //inject NONSTANDARD NAMING
function WITHDRAW91(uint) external; //inject NONSTANDARD NAMING
}
interface IUniswapV2Router01 {
function FACTORY423() external pure returns (address); //inject NONSTANDARD NAMING
function WETH656() external pure returns (address); //inject NONSTANDARD NAMING
function ADDLIQUIDITY566( //inject NONSTANDARD NAMING
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 ADDLIQUIDITYETH439( //inject NONSTANDARD NAMING
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function REMOVELIQUIDITY294( //inject NONSTANDARD NAMING
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function REMOVELIQUIDITYETH142( //inject NONSTANDARD NAMING
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function REMOVELIQUIDITYWITHPERMIT785( //inject NONSTANDARD NAMING
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 REMOVELIQUIDITYETHWITHPERMIT822( //inject NONSTANDARD NAMING
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 SWAPEXACTTOKENSFORTOKENS694( //inject NONSTANDARD NAMING
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function SWAPTOKENSFOREXACTTOKENS112( //inject NONSTANDARD NAMING
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function SWAPEXACTETHFORTOKENS23(uint amountOutMin, address[] calldata path, address to, uint deadline) //inject NONSTANDARD NAMING
external
payable
returns (uint[] memory amounts);
function SWAPTOKENSFOREXACTETH134(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) //inject NONSTANDARD NAMING
external
returns (uint[] memory amounts);
function SWAPEXACTTOKENSFORETH465(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) //inject NONSTANDARD NAMING
external
returns (uint[] memory amounts);
function SWAPETHFOREXACTTOKENS477(uint amountOut, address[] calldata path, address to, uint deadline) //inject NONSTANDARD NAMING
external
payable
returns (uint[] memory amounts);
function QUOTE151(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); //inject NONSTANDARD NAMING
function GETAMOUNTOUT667(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); //inject NONSTANDARD NAMING
function GETAMOUNTIN118(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); //inject NONSTANDARD NAMING
function GETAMOUNTSOUT962(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); //inject NONSTANDARD NAMING
function GETAMOUNTSIN769(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); //inject NONSTANDARD NAMING
}
interface IUniswapV2Router02 is IUniswapV2Router01 {
function REMOVELIQUIDITYETHSUPPORTINGFEEONTRANSFERTOKENS84( //inject NONSTANDARD NAMING
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function REMOVELIQUIDITYETHWITHPERMITSUPPORTINGFEEONTRANSFERTOKENS171( //inject NONSTANDARD NAMING
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 SWAPEXACTTOKENSFORTOKENSSUPPORTINGFEEONTRANSFERTOKENS513( //inject NONSTANDARD NAMING
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function SWAPEXACTETHFORTOKENSSUPPORTINGFEEONTRANSFERTOKENS617( //inject NONSTANDARD NAMING
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function SWAPEXACTTOKENSFORETHSUPPORTINGFEEONTRANSFERTOKENS347( //inject NONSTANDARD NAMING
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
interface IUniswapV2Pair {
event APPROVAL691(address indexed owner, address indexed spender, uint value); //inject NONSTANDARD NAMING
event TRANSFER649(address indexed from, address indexed to, uint value); //inject NONSTANDARD NAMING
function NAME590() external pure returns (string memory); //inject NONSTANDARD NAMING
function SYMBOL603() external pure returns (string memory); //inject NONSTANDARD NAMING
function DECIMALS715() external pure returns (uint8); //inject NONSTANDARD NAMING
function TOTALSUPPLY622() external view returns (uint); //inject NONSTANDARD NAMING
function BALANCEOF753(address owner) external view returns (uint); //inject NONSTANDARD NAMING
function ALLOWANCE76(address owner, address spender) external view returns (uint); //inject NONSTANDARD NAMING
function APPROVE213(address spender, uint value) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFER955(address to, uint value) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM690(address from, address to, uint value) external returns (bool); //inject NONSTANDARD NAMING
function DOMAIN_SEPARATOR647() external view returns (bytes32); //inject NONSTANDARD NAMING
function PERMIT_TYPEHASH618() external pure returns (bytes32); //inject NONSTANDARD NAMING
function NONCES61(address owner) external view returns (uint); //inject NONSTANDARD NAMING
function PERMIT398(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; //inject NONSTANDARD NAMING
event MINT816(address indexed sender, uint amount0, uint amount1); //inject NONSTANDARD NAMING
event BURN577(address indexed sender, uint amount0, uint amount1, address indexed to); //inject NONSTANDARD NAMING
event SWAP591( //inject NONSTANDARD NAMING
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event SYNC313(uint112 reserve0, uint112 reserve1); //inject NONSTANDARD NAMING
function MINIMUM_LIQUIDITY897() external pure returns (uint); //inject NONSTANDARD NAMING
function FACTORY423() external view returns (address); //inject NONSTANDARD NAMING
function TOKEN0588() external view returns (address); //inject NONSTANDARD NAMING
function TOKEN1553() external view returns (address); //inject NONSTANDARD NAMING
function GETRESERVES947() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); //inject NONSTANDARD NAMING
function PRICE0CUMULATIVELAST382() external view returns (uint); //inject NONSTANDARD NAMING
function PRICE1CUMULATIVELAST280() external view returns (uint); //inject NONSTANDARD NAMING
function KLAST968() external view returns (uint); //inject NONSTANDARD NAMING
function MINT750(address to) external returns (uint liquidity); //inject NONSTANDARD NAMING
function BURN945(address to) external returns (uint amount0, uint amount1); //inject NONSTANDARD NAMING
function SWAP412(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; //inject NONSTANDARD NAMING
function SKIM546(address to) external; //inject NONSTANDARD NAMING
function SYNC14() external; //inject NONSTANDARD NAMING
function INITIALIZE840(address, address) external; //inject NONSTANDARD NAMING
}
interface IUniswapV2Factory {
event PAIRCREATED444(address indexed token0, address indexed token1, address pair, uint); //inject NONSTANDARD NAMING
function FEETO98() external view returns (address); //inject NONSTANDARD NAMING
function FEETOSETTER656() external view returns (address); //inject NONSTANDARD NAMING
function MIGRATOR786() external view returns (address); //inject NONSTANDARD NAMING
function GETPAIR761(address tokenA, address tokenB) external view returns (address pair); //inject NONSTANDARD NAMING
function ALLPAIRS341(uint) external view returns (address pair); //inject NONSTANDARD NAMING
function ALLPAIRSLENGTH448() external view returns (uint); //inject NONSTANDARD NAMING
function CREATEPAIR119(address tokenA, address tokenB) external returns (address pair); //inject NONSTANDARD NAMING
function SETFEETO526(address) external; //inject NONSTANDARD NAMING
function SETFEETOSETTER51(address) external; //inject NONSTANDARD NAMING
function SETMIGRATOR114(address) external; //inject NONSTANDARD NAMING
}
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_entered266 = 1; //inject NONSTANDARD NAMING
uint256 private constant _entered280 = 2; //inject NONSTANDARD NAMING
uint256 private _status;
constructor () internal {
_status = _not_entered266;
}
modifier NONREENTRANT384() { //inject NONSTANDARD NAMING
// On the first call to nonReentrant, _notEntered will be true
require(_status != _entered280, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _entered280;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _not_entered266;
}
}
library Math {
function MAX80(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return a >= b ? a : b;
}
function MIN629(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return a < b ? a : b;
}
function AVERAGE241(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
library Address {
function ISCONTRACT204(address account) internal view returns (bool) { //inject NONSTANDARD NAMING
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
function SENDVALUE55(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
function FUNCTIONCALL585(address target, bytes memory data) internal returns (bytes memory) { //inject NONSTANDARD NAMING
return FUNCTIONCALL585(target, data, "Address: low-level call failed");
}
function FUNCTIONCALL585(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING
return _FUNCTIONCALLWITHVALUE394(target, data, 0, errorMessage);
}
function FUNCTIONCALLWITHVALUE130(address target, bytes memory data, uint256 value) internal returns (bytes memory) { //inject NONSTANDARD NAMING
return FUNCTIONCALLWITHVALUE130(target, data, value, "Address: low-level call with value failed");
}
function FUNCTIONCALLWITHVALUE130(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING
require(address(this).balance >= value, "Address: insufficient balance for call");
return _FUNCTIONCALLWITHVALUE394(target, data, value, errorMessage);
}
function _FUNCTIONCALLWITHVALUE394(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { //inject NONSTANDARD NAMING
require(ISCONTRACT204(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
library SafeMath {
function ADD393(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB829(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB829(a, b, "SafeMath: subtraction overflow");
}
function SUB829(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function MUL131(uint256 a, uint256 b) 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-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function DIV283(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV283(a, b, "SafeMath: division by zero");
}
function DIV283(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
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 MOD208(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD208(a, b, "SafeMath: modulo by zero");
}
function MOD208(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
library MathUtils {
using SafeMath for uint256;
function SQRT196(uint256 x) internal pure returns (uint256 y) { //inject NONSTANDARD NAMING
uint256 z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
function ROUNDEDDIV172(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b > 0, 'div by 0');
uint256 halfB = (b.MOD208(2) == 0) ? (b.DIV283(2)) : (b.DIV283(2).ADD393(1));
return (a.MOD208(b) >= halfB) ? (a.DIV283(b).ADD393(1)) : (a.DIV283(b));
}
}
interface IUniswapV2ERC20 {
event APPROVAL691(address indexed owner, address indexed spender, uint value); //inject NONSTANDARD NAMING
event TRANSFER649(address indexed from, address indexed to, uint value); //inject NONSTANDARD NAMING
function NAME590() external pure returns (string memory); //inject NONSTANDARD NAMING
function SYMBOL603() external pure returns (string memory); //inject NONSTANDARD NAMING
function DECIMALS715() external pure returns (uint8); //inject NONSTANDARD NAMING
function TOTALSUPPLY622() external view returns (uint); //inject NONSTANDARD NAMING
function BALANCEOF753(address owner) external view returns (uint); //inject NONSTANDARD NAMING
function ALLOWANCE76(address owner, address spender) external view returns (uint); //inject NONSTANDARD NAMING
function APPROVE213(address spender, uint value) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFER955(address to, uint value) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM690(address from, address to, uint value) external returns (bool); //inject NONSTANDARD NAMING
function DOMAIN_SEPARATOR647() external view returns (bytes32); //inject NONSTANDARD NAMING
function PERMIT_TYPEHASH618() external pure returns (bytes32); //inject NONSTANDARD NAMING
function NONCES61(address owner) external view returns (uint); //inject NONSTANDARD NAMING
function PERMIT398(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; //inject NONSTANDARD NAMING
}
interface IUniswapV2Callee {
function UNISWAPV2CALL695(address sender, uint amount0, uint amount1, bytes calldata data) external; //inject NONSTANDARD NAMING
}
interface IERC20Uniswap {
event APPROVAL691(address indexed owner, address indexed spender, uint value); //inject NONSTANDARD NAMING
event TRANSFER649(address indexed from, address indexed to, uint value); //inject NONSTANDARD NAMING
function NAME590() external view returns (string memory); //inject NONSTANDARD NAMING
function SYMBOL603() external view returns (string memory); //inject NONSTANDARD NAMING
function DECIMALS715() external view returns (uint8); //inject NONSTANDARD NAMING
function TOTALSUPPLY622() external view returns (uint); //inject NONSTANDARD NAMING
function BALANCEOF753(address owner) external view returns (uint); //inject NONSTANDARD NAMING
function ALLOWANCE76(address owner, address spender) external view returns (uint); //inject NONSTANDARD NAMING
function APPROVE213(address spender, uint value) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFER955(address to, uint value) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM690(address from, address to, uint value) external returns (bool); //inject NONSTANDARD NAMING
}
abstract contract Context {
function _MSGSENDER27() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING
return msg.sender;
}
function _MSGDATA543() 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;
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
function NAME590() public view returns (string memory) { //inject NONSTANDARD NAMING
return _name;
}
function SYMBOL603() public view returns (string memory) { //inject NONSTANDARD NAMING
return _symbol;
}
function DECIMALS715() public view returns (uint8) { //inject NONSTANDARD NAMING
return _decimals;
}
function TOTALSUPPLY622() public view override returns (uint256) { //inject NONSTANDARD NAMING
return _totalSupply;
}
function BALANCEOF753(address account) public view override returns (uint256) { //inject NONSTANDARD NAMING
return _balances[account];
}
function TRANSFER955(address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER21(_MSGSENDER27(), recipient, amount);
return true;
}
function ALLOWANCE76(address owner, address spender) public view virtual override returns (uint256) { //inject NONSTANDARD NAMING
return _allowances[owner][spender];
}
function APPROVE213(address spender, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING
_APPROVE77(_MSGSENDER27(), spender, amount);
return true;
}
function TRANSFERFROM690(address sender, address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER21(sender, recipient, amount);
_APPROVE77(sender, _MSGSENDER27(), _allowances[sender][_MSGSENDER27()].SUB829(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function INCREASEALLOWANCE203(address spender, uint256 addedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING
_APPROVE77(_MSGSENDER27(), spender, _allowances[_MSGSENDER27()][spender].ADD393(addedValue));
return true;
}
function DECREASEALLOWANCE568(address spender, uint256 subtractedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING
_APPROVE77(_MSGSENDER27(), spender, _allowances[_MSGSENDER27()][spender].SUB829(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _TRANSFER21(address sender, address recipient, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_BEFORETOKENTRANSFER156(sender, recipient, amount);
_balances[sender] = _balances[sender].SUB829(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].ADD393(amount);
emit TRANSFER649(sender, recipient, amount);
}
function _MINT693(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: mint to the zero address");
_BEFORETOKENTRANSFER156(address(0), account, amount);
_totalSupply = _totalSupply.ADD393(amount);
_balances[account] = _balances[account].ADD393(amount);
emit TRANSFER649(address(0), account, amount);
}
function _BURN313(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: burn from the zero address");
_BEFORETOKENTRANSFER156(account, address(0), amount);
_balances[account] = _balances[account].SUB829(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.SUB829(amount);
emit TRANSFER649(account, address(0), amount);
}
function _APPROVE77(address owner, address spender, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit APPROVAL691(owner, spender, amount);
}
function _SETUPDECIMALS749(uint8 decimals_) internal { //inject NONSTANDARD NAMING
_decimals = decimals_;
}
function _BEFORETOKENTRANSFER156(address from, address to, uint256 amount) internal virtual { } //inject NONSTANDARD NAMING
}
contract WETH9 {
string public name = "Wrapped Ether";
string public symbol = "WETH";
uint8 public decimals = 18;
event APPROVAL691(address indexed src, address indexed guy, uint wad); //inject NONSTANDARD NAMING
event TRANSFER649(address indexed src, address indexed dst, uint wad); //inject NONSTANDARD NAMING
event DEPOSIT981(address indexed dst, uint wad); //inject NONSTANDARD NAMING
event WITHDRAWAL378(address indexed src, uint wad); //inject NONSTANDARD NAMING
mapping(address => uint) public balanceOf;
mapping(address => mapping(address => uint)) public allowance;
receive() external payable {
DEPOSIT379();
}
function DEPOSIT379() public payable { //inject NONSTANDARD NAMING
balanceOf[msg.sender] += msg.value;
DEPOSIT981(msg.sender, msg.value);
}
function WITHDRAW91(uint wad) public { //inject NONSTANDARD NAMING
require(balanceOf[msg.sender] >= wad);
balanceOf[msg.sender] -= wad;
msg.sender.transfer(wad);
WITHDRAWAL378(msg.sender, wad);
}
function TOTALSUPPLY622() public view returns (uint) { //inject NONSTANDARD NAMING
return address(this).balance;
}
function APPROVE213(address guy, uint wad) public returns (bool) { //inject NONSTANDARD NAMING
allowance[msg.sender][guy] = wad;
APPROVAL691(msg.sender, guy, wad);
return true;
}
function TRANSFER955(address dst, uint wad) public returns (bool) { //inject NONSTANDARD NAMING
return TRANSFERFROM690(msg.sender, dst, wad);
}
function TRANSFERFROM690(address src, address dst, uint wad) //inject NONSTANDARD NAMING
public
returns (bool)
{
require(balanceOf[src] >= wad);
if (src != msg.sender && allowance[src][msg.sender] != uint(- 1)) {
require(allowance[src][msg.sender] >= wad);
allowance[src][msg.sender] -= wad;
}
balanceOf[src] -= wad;
balanceOf[dst] += wad;
TRANSFER649(src, dst, wad);
return true;
}
}
contract twis is ERC20 {
address minter;
modifier ONLYMINTER285 { //inject NONSTANDARD NAMING
require(msg.sender == minter, 'Only minter can call this function.');
_;
}
constructor(address _minter) public ERC20('Twister', 'TWIS') {
minter = _minter;
}
function MINT750(address account, uint256 amount) external ONLYMINTER285 { //inject NONSTANDARD NAMING
_MINT693(account, amount);
}
function BURN945(address account, uint256 amount) external ONLYMINTER285 { //inject NONSTANDARD NAMING
_BURN313(account, amount);
}
}
contract Twister is ReentrancyGuard {
using SafeMath for uint256;
using Address for address;
using SafeERC20 for IERC20;
event STAKED534(address indexed from, uint256 amountETH, uint256 amountLP); //inject NONSTANDARD NAMING
event WITHDRAWN851(address indexed to, uint256 amountETH, uint256 amountLP); //inject NONSTANDARD NAMING
event CLAIMED515(address indexed to, uint256 amount); //inject NONSTANDARD NAMING
event HALVING833(uint256 amount); //inject NONSTANDARD NAMING
event RECEIVED501(address indexed from, uint256 amount); //inject NONSTANDARD NAMING
twis public token;
IUniswapV2Factory public factory;
IUniswapV2Router02 public router;
address public weth;
address payable public treasury;
address public pairAddress;
struct AccountInfo {
// Staked LP token balance
uint256 balance;
uint256 peakBalance;
uint256 withdrawTimestamp;
uint256 reward;
uint256 rewardPerTokenPaid;
}
mapping(address => AccountInfo) public accountInfos;
// Staked LP token total supply
uint256 private _totalSupply = 0;
uint256 public constant halving_duration255 = 7 days; //inject NONSTANDARD NAMING
uint256 public rewardAllocation = 1500 * 1e18;
uint256 public halvingTimestamp = 0;
uint256 public lastUpdateTimestamp = 0;
uint256 public rewardRate = 0;
uint256 public rewardPerTokenStored = 0;
// Farming will be open on this timestamp
// Date and time (GMT): Monday, October 26, 2020 3:00:00 PM
uint256 public farmingStartTimestamp = 1604635200;
bool public farmingStarted = false;
// Max 10% / day LP withdraw
uint256 public constant withdraw_limit638 = 10; //inject NONSTANDARD NAMING
// Burn address
address constant burn_address389 = 0x000000000000000000000000000000000000dEaD; //inject NONSTANDARD NAMING
// Dev decided to launch without whitelist but since it has been coded and tested, so dev will leave it here.
// Whitelisted address
mapping (address => bool) public whitelists;
// Whitelist deposited balance
mapping (address => uint256) public whitelistBalance;
// End period for whitelist advantage
uint256 public whitelistEndTimestamp = 0;
// Max stake for whitelist
uint256 public constant whitelist_stake_limit67 = 3 ether; //inject NONSTANDARD NAMING
// Whitelist advantage duration (reduced to 1 minutes since we dont have whitelist)
uint256 public constant whitelist_duration869 = 1 minutes; //inject NONSTANDARD NAMING
constructor(address _routerAddress, address[] memory _whitelists) public {
token = new twis(address(this));
router = IUniswapV2Router02(_routerAddress);
factory = IUniswapV2Factory(router.FACTORY423());
weth = router.WETH656();
treasury = msg.sender;
pairAddress = factory.CREATEPAIR119(address(token), weth);
// Calc reward rate
rewardRate = rewardAllocation.DIV283(halving_duration255);
// Init whitelist
_SETUPWHITELISTS161(_whitelists);
whitelistEndTimestamp = farmingStartTimestamp.ADD393(whitelist_duration869);
}
receive() external payable {
emit RECEIVED501(msg.sender, msg.value);
}
function STAKE961() external payable NONREENTRANT384 { //inject NONSTANDARD NAMING
_CHECKFARMING62();
_UPDATEREWARD485(msg.sender);
_HALVING349();
require(msg.value > 0, 'Cannot stake 0');
require(!address(msg.sender).ISCONTRACT204(), 'Please use your individual account');
// If we are still in whitelist duration
if (whitelistEndTimestamp >= block.timestamp) {
require(whitelists[msg.sender], 'Only whitelisted address can stake right now');
whitelistBalance[msg.sender] = whitelistBalance[msg.sender].ADD393(msg.value);
require(whitelistBalance[msg.sender] <= whitelist_stake_limit67, 'Cannot stake more than allowed in whitelist period');
}
// 10% compensation fee
// since dev doesn't hold any initial supply
uint256 fee = msg.value.DIV283(10);
uint256 amount = msg.value.SUB829(fee);
treasury.transfer(fee);
uint256 ethAmount = IERC20(weth).BALANCEOF753(pairAddress);
uint256 tokenAmount = IERC20(token).BALANCEOF753(pairAddress);
// If eth amount = 0 then set initial price to 1 eth = 2 twis
uint256 amountTokenDesired = ethAmount == 0 ? (amount * 2) : amount.MUL131(tokenAmount).DIV283(ethAmount);
// Mint borrowed twis
token.MINT750(address(this), amountTokenDesired);
// Add liquidity in uniswap
uint256 amountETHDesired = amount;
IERC20(token).APPROVE213(address(router), amountTokenDesired);
(,, uint256 liquidity) = router.ADDLIQUIDITYETH439{value : amountETHDesired}(address(token), amountTokenDesired, 1, 1, address(this), block.timestamp + 1 days);
// Add LP token to total supply
_totalSupply = _totalSupply.ADD393(liquidity);
// Add to balance
accountInfos[msg.sender].balance = accountInfos[msg.sender].balance.ADD393(liquidity);
// Set peak balance
if (accountInfos[msg.sender].balance > accountInfos[msg.sender].peakBalance) {
accountInfos[msg.sender].peakBalance = accountInfos[msg.sender].balance;
}
// Set stake timestamp as withdraw timestamp
// to prevent withdraw immediately after first staking
if (accountInfos[msg.sender].withdrawTimestamp == 0) {
accountInfos[msg.sender].withdrawTimestamp = block.timestamp;
}
emit STAKED534(msg.sender, msg.value, liquidity);
}
function WITHDRAW91() external NONREENTRANT384 { //inject NONSTANDARD NAMING
_CHECKFARMING62();
_UPDATEREWARD485(msg.sender);
_HALVING349();
require(accountInfos[msg.sender].withdrawTimestamp + 1 days <= block.timestamp, 'You must wait 1 day since your last withdraw or stake');
require(accountInfos[msg.sender].balance > 0, 'Cannot withdraw 0');
// Limit withdraw LP token
uint256 amount = accountInfos[msg.sender].peakBalance.DIV283(withdraw_limit638);
if (accountInfos[msg.sender].balance < amount) {
amount = accountInfos[msg.sender].balance;
}
// Reduce total supply
_totalSupply = _totalSupply.SUB829(amount);
// Reduce balance
accountInfos[msg.sender].balance = accountInfos[msg.sender].balance.SUB829(amount);
// Set timestamp
accountInfos[msg.sender].withdrawTimestamp = block.timestamp;
// Remove liquidity in uniswap
IERC20(pairAddress).APPROVE213(address(router), amount);
(uint256 tokenAmount, uint256 ethAmount) = router.REMOVELIQUIDITY294(address(token), weth, amount, 0, 0, address(this), block.timestamp + 1 days);
// Burn borrowed twis
token.BURN945(address(this), tokenAmount);
// Withdraw ETH and send to sender
IWETH(weth).WITHDRAW91(ethAmount);
msg.sender.transfer(ethAmount);
emit WITHDRAWN851(msg.sender, ethAmount, amount);
}
function CLAIM763() external NONREENTRANT384 { //inject NONSTANDARD NAMING
_CHECKFARMING62();
_UPDATEREWARD485(msg.sender);
_HALVING349();
uint256 reward = accountInfos[msg.sender].reward;
require(reward > 0, 'There is no reward to claim');
if (reward > 0) {
// Reduce first
accountInfos[msg.sender].reward = 0;
// Apply tax
uint256 taxDenominator = CLAIMTAXDENOMINATOR467();
uint256 tax = taxDenominator > 0 ? reward.DIV283(taxDenominator) : 0;
uint256 net = reward.SUB829(tax);
// Send reward
token.MINT750(msg.sender, net);
if (tax > 0) {
// Burn taxed token
token.MINT750(burn_address389, tax);
}
emit CLAIMED515(msg.sender, reward);
}
}
function TOTALSUPPLY622() external view returns (uint256) { //inject NONSTANDARD NAMING
return _totalSupply;
}
function BALANCEOF753(address account) external view returns (uint256) { //inject NONSTANDARD NAMING
return accountInfos[account].balance;
}
function BURNEDTOKENAMOUNT890() public view returns (uint256) { //inject NONSTANDARD NAMING
return token.BALANCEOF753(burn_address389);
}
function REWARDPERTOKEN638() public view returns (uint256) { //inject NONSTANDARD NAMING
if (_totalSupply == 0) {
return rewardPerTokenStored;
}
return rewardPerTokenStored
.ADD393(
LASTREWARDTIMESTAMP705()
.SUB829(lastUpdateTimestamp)
.MUL131(rewardRate)
.MUL131(1e18)
.DIV283(_totalSupply)
);
}
function LASTREWARDTIMESTAMP705() public view returns (uint256) { //inject NONSTANDARD NAMING
return Math.MIN629(block.timestamp, halvingTimestamp);
}
function REWARDEARNED380(address account) public view returns (uint256) { //inject NONSTANDARD NAMING
return accountInfos[account].balance.MUL131(
REWARDPERTOKEN638().SUB829(accountInfos[account].rewardPerTokenPaid)
)
.DIV283(1e18)
.ADD393(accountInfos[account].reward);
}
// Token price in eth
function TOKENPRICE205() public view returns (uint256) { //inject NONSTANDARD NAMING
uint256 ethAmount = IERC20(weth).BALANCEOF753(pairAddress);
uint256 tokenAmount = IERC20(token).BALANCEOF753(pairAddress);
return tokenAmount > 0 ?
// Current price
ethAmount.MUL131(1e18).DIV283(tokenAmount) :
// Initial price
(uint256(1e18).DIV283(2));
}
function CLAIMTAXDENOMINATOR467() public view returns (uint256) { //inject NONSTANDARD NAMING
if (block.timestamp < farmingStartTimestamp + 1 days) {
return 4;
} else if (block.timestamp < farmingStartTimestamp + 2 days) {
return 5;
} else if (block.timestamp < farmingStartTimestamp + 3 days) {
return 10;
} else if (block.timestamp < farmingStartTimestamp + 4 days) {
return 20;
} else {
return 0;
}
}
function _UPDATEREWARD485(address account) internal { //inject NONSTANDARD NAMING
rewardPerTokenStored = REWARDPERTOKEN638();
lastUpdateTimestamp = LASTREWARDTIMESTAMP705();
if (account != address(0)) {
accountInfos[account].reward = REWARDEARNED380(account);
accountInfos[account].rewardPerTokenPaid = rewardPerTokenStored;
}
}
// Do halving when timestamp reached
function _HALVING349() internal { //inject NONSTANDARD NAMING
if (block.timestamp >= halvingTimestamp) {
rewardAllocation = rewardAllocation.DIV283(2);
rewardRate = rewardAllocation.DIV283(halving_duration255);
halvingTimestamp = halvingTimestamp.ADD393(halving_duration255);
_UPDATEREWARD485(msg.sender);
emit HALVING833(rewardAllocation);
}
}
// Check if farming is started
function _CHECKFARMING62() internal { //inject NONSTANDARD NAMING
require(farmingStartTimestamp <= block.timestamp, 'Please wait until farming started');
if (!farmingStarted) {
farmingStarted = true;
halvingTimestamp = block.timestamp.ADD393(halving_duration255);
lastUpdateTimestamp = block.timestamp;
}
}
function _SETUPWHITELISTS161(address[] memory addresses) internal { //inject NONSTANDARD NAMING
for (uint256 i = 0; i < addresses.length; i++) {
whitelists[addresses[i]] = true;
}
}
}
|
inject NONSTANDARD NAMING
|
function SENDVALUE55(address payable recipient, uint256 amount) internal {
| 12,607,410 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.